id
stringlengths
40
40
text
stringlengths
29
2.03k
original_text
stringlengths
3
154k
subdomain
stringclasses
20 values
metadata
dict
1092f198006d9f49a18195cdb5b622a7fd00c92b
Stackoverflow Stackexchange Q: what color space will produce most features to train a more accurate CNN on? Most of the times I see people using the RGB channel for the training set. While it is good for facial detection but I have not found it as effective as I thought it would be! So, should I try converting the image into a different (possibly a combination of different color transitions) color space to train an object identifier? I cannot afford to do find it out experimentally as there is a higher cost associated with that(AWS). P.S. I am using dlib's dnn_mmod_ex.cpp! A: this paper might be interesting for you: "Effect of image colourspace on performance of convolution neural networks" by K Sumanth Reddy; Upasna Singh; Prakash K Uttam. Published in: 2017 2nd IEEE International Conference on Recent Trends in Electronics, Information & Communication Technology (RTEICT).(https://ieeexplore.ieee.org/document/8256949) The authors investigated the effect of different colorspaces (RGB, HSL, HSV, LUV, YUV) on the performance of a CNN (AlexNet) trained with CIFAR10 dataset. They found that the LUV colorspace is a good alternative to the widely used RGB colorspace, while the Network trained on YUV data showed the worst performance.
Q: what color space will produce most features to train a more accurate CNN on? Most of the times I see people using the RGB channel for the training set. While it is good for facial detection but I have not found it as effective as I thought it would be! So, should I try converting the image into a different (possibly a combination of different color transitions) color space to train an object identifier? I cannot afford to do find it out experimentally as there is a higher cost associated with that(AWS). P.S. I am using dlib's dnn_mmod_ex.cpp! A: this paper might be interesting for you: "Effect of image colourspace on performance of convolution neural networks" by K Sumanth Reddy; Upasna Singh; Prakash K Uttam. Published in: 2017 2nd IEEE International Conference on Recent Trends in Electronics, Information & Communication Technology (RTEICT).(https://ieeexplore.ieee.org/document/8256949) The authors investigated the effect of different colorspaces (RGB, HSL, HSV, LUV, YUV) on the performance of a CNN (AlexNet) trained with CIFAR10 dataset. They found that the LUV colorspace is a good alternative to the widely used RGB colorspace, while the Network trained on YUV data showed the worst performance. A: After long search for answers and experimenting a lot with the color space in object recognition tasks, I've found out RGB is an optimal choice for the color space. I tried many color Spaces such as YCrCb, Lab etc. While they are certainly great when we are limited to computer vision problems like Lab is exposure invariant(upto some extent) but an image certainly lose data when we convert it to other colorspaces. I was using HOG as a feature descriptor and it didn't go well with changed color spaces. The gradients were misfiring and there was no consistency. However in computer vision, where I am dealing with defect segmentation in potatoes, other color spaces such as YCrCb proved to be a great feature descriptor for defect segmentation via clustering algorithms. Do correct me if you find some thing incorrect in my observations.
stackoverflow
{ "language": "en", "length": 337, "provenance": "stackexchange_0000F.jsonl.gz:874188", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44570926" }
acd7ba325723828c27078b647605f7c32524bfdb
Stackoverflow Stackexchange Q: Calculate minimum and maximum values of each variable in a table in kdb Consider the following table: sym A B X 1 2 Y 4 1 X 6 9 Z 6 3 Z 3 7 Y 1 8 I want to find the minimum A value and maximum B value for each of my symbols X, Y & Z and display them in a new table, i.e. sym minA maxB X 1 9 Y 1 8 Z 3 7 Thanks. A: This should do it; select minA:min A, maxB:max B by sym from table
Q: Calculate minimum and maximum values of each variable in a table in kdb Consider the following table: sym A B X 1 2 Y 4 1 X 6 9 Z 6 3 Z 3 7 Y 1 8 I want to find the minimum A value and maximum B value for each of my symbols X, Y & Z and display them in a new table, i.e. sym minA maxB X 1 9 Y 1 8 Z 3 7 Thanks. A: This should do it; select minA:min A, maxB:max B by sym from table
stackoverflow
{ "language": "en", "length": 95, "provenance": "stackexchange_0000F.jsonl.gz:874189", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44570929" }
ef56111ec967709a2a5ccfd737c406b9622f0c4a
Stackoverflow Stackexchange Q: Django error: could not parse the remainder: ': "Y-m-d"' from 'post.date|date: "Y-m-d"' I'm creating a blog post and after migrating my blog files successfully I am returned an error when I go to the blog page of my website ( Could not parse the remainder: ': "Y-m-d"' from 'post.date|date: "Y-m-d"') I cant seem to find whether this is a syntax error or a logic error HTML: {% extends "personal/header.html" %} {% block content %} {% for post in object_list %} <h5> {{ post.date|date: "Y-m-d"}} <a href="/blog/{{ post.id }}"> {{ post.title }} </a> </h5> {% endfor %} {% endblock %} Python (models.py): from django.db import models class Post (models.Model): title = models.CharField(max_length=140) body = models.TextField() date = models.DateTimeField() def __unicode__(self): return self.title A: You need to remove the space after the colon: {{ post.date|date:"Y-m-d" }}
Q: Django error: could not parse the remainder: ': "Y-m-d"' from 'post.date|date: "Y-m-d"' I'm creating a blog post and after migrating my blog files successfully I am returned an error when I go to the blog page of my website ( Could not parse the remainder: ': "Y-m-d"' from 'post.date|date: "Y-m-d"') I cant seem to find whether this is a syntax error or a logic error HTML: {% extends "personal/header.html" %} {% block content %} {% for post in object_list %} <h5> {{ post.date|date: "Y-m-d"}} <a href="/blog/{{ post.id }}"> {{ post.title }} </a> </h5> {% endfor %} {% endblock %} Python (models.py): from django.db import models class Post (models.Model): title = models.CharField(max_length=140) body = models.TextField() date = models.DateTimeField() def __unicode__(self): return self.title A: You need to remove the space after the colon: {{ post.date|date:"Y-m-d" }} A: there should be no space between colon (:) and date and date format eg. date:"d-m-Y"
stackoverflow
{ "language": "en", "length": 151, "provenance": "stackexchange_0000F.jsonl.gz:874206", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44570965" }
0383f00104cd160b78be449d5e856373074d7a6e
Stackoverflow Stackexchange Q: how to change default file dropify? Hello I am using Dropify.js, and I want to edit some items, so when I click to edit an item, the input with dropify class works fine it upload automatically the given file with this part of code: $('.dropify').dropify({ defaultFile: app.getPath('userData') + '/images/' + doc.image }); but when I want to edit another item, the file doesn't change it still the first one. I hope you understund me. items are in a table. I found this but I dont know how to do it: var drDestroy = $('.dropify').dropify(); drDestroy = drDestroy.data('dropify') $('#toggleDropify').on('click', function(e){ e.preventDefault(); if (drDestroy.isDropified()) { drDestroy.destroy(); } else { drDestroy.init(); } }) if any one can tell me what init() and destroy() and isDropified() functions do exaclty. A: Here is a solution: var imagenUrl = ""; var drEvent = $('#yourInputFileId').dropify( { defaultFile: imagenUrl }); drEvent = drEvent.data('dropify'); drEvent.resetPreview(); drEvent.clearElement(); drEvent.settings.defaultFile = imagenUrl; drEvent.destroy(); drEvent.init();
Q: how to change default file dropify? Hello I am using Dropify.js, and I want to edit some items, so when I click to edit an item, the input with dropify class works fine it upload automatically the given file with this part of code: $('.dropify').dropify({ defaultFile: app.getPath('userData') + '/images/' + doc.image }); but when I want to edit another item, the file doesn't change it still the first one. I hope you understund me. items are in a table. I found this but I dont know how to do it: var drDestroy = $('.dropify').dropify(); drDestroy = drDestroy.data('dropify') $('#toggleDropify').on('click', function(e){ e.preventDefault(); if (drDestroy.isDropified()) { drDestroy.destroy(); } else { drDestroy.init(); } }) if any one can tell me what init() and destroy() and isDropified() functions do exaclty. A: Here is a solution: var imagenUrl = ""; var drEvent = $('#yourInputFileId').dropify( { defaultFile: imagenUrl }); drEvent = drEvent.data('dropify'); drEvent.resetPreview(); drEvent.clearElement(); drEvent.settings.defaultFile = imagenUrl; drEvent.destroy(); drEvent.init(); A: For change dropify image src follow these line: HTML: <input type="file" id="image" /> JS: $("#image").addClass('dropify'); $("#image").attr("data-height", 300); $("#image").attr("data-default-file", "http://www.adamanthr.com/wp-content/uploads/2016/04/dummy-man-570x570.png"); $('.dropify').dropify();
stackoverflow
{ "language": "en", "length": 174, "provenance": "stackexchange_0000F.jsonl.gz:874212", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44570981" }
c486b51eadb59aba943310746669e0ee21480e28
Stackoverflow Stackexchange Q: PHPUnit Mock an object's properties I'm looking for a way to mock an object and populate its properties. Here's an example of a method who uses a property of another object: class MyClass { private $_object; public function methodUnderTest($object) { $this->_object = $object; return $this->_object->property } } To Unit Test this method I should create a mock of $object with the getMockBuilder() method from PHPUnit. But I can't find a way to mock the properties of the $object, just the methods. A: To add properties to a mocked object, you just set them as you'd normally do with an object: $mock = $this->getMockBuilder('MyClass') ->disableOriginalConstructor() ->getMock(); $mock->property = 'some_value'; $mock->property will now return 'some_value' Thanks to akond P.s. for my project, this doesn't work with some classes, and when I try to call $mock->property it just returns NULL
Q: PHPUnit Mock an object's properties I'm looking for a way to mock an object and populate its properties. Here's an example of a method who uses a property of another object: class MyClass { private $_object; public function methodUnderTest($object) { $this->_object = $object; return $this->_object->property } } To Unit Test this method I should create a mock of $object with the getMockBuilder() method from PHPUnit. But I can't find a way to mock the properties of the $object, just the methods. A: To add properties to a mocked object, you just set them as you'd normally do with an object: $mock = $this->getMockBuilder('MyClass') ->disableOriginalConstructor() ->getMock(); $mock->property = 'some_value'; $mock->property will now return 'some_value' Thanks to akond P.s. for my project, this doesn't work with some classes, and when I try to call $mock->property it just returns NULL A: If you have classes with magic methods you can use: $mock->method('__get')->with('property')->willReturn('value');
stackoverflow
{ "language": "en", "length": 150, "provenance": "stackexchange_0000F.jsonl.gz:874222", "question_score": "32", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44571002" }
ddba245116969cd3cc4b740c9ee30862aa466df0
Stackoverflow Stackexchange Q: How can I encode a 32bit integer into a byte array? I'm required to send a 32bit integer over a serial connection like so: 0xc6bf6f34 should become: b'\xc6\xbf\x6f\x34'. To that end, I created this, but, as always after such coding, I wondered if it's pythonicism could be improved with something in the standard libary: def ltonlba(value): ''' ltonlba : Long to Network Long Byte Array ''' from socket import htonl value = htonl(value) ba = b'' for i in range(4): ba += chr((value) & 0xff) value >>= 8 return ba A: If you're using Python 3.2+, you can use int.to_bytes: >>> 0xc6bf6f34.to_bytes(4, 'little') # 4 bytes = 32 bits b'4o\xbf\xc6' >>> 0xc6bf6f34.to_bytes(4, 'little') == b'\x34\x6f\xbf\xc6' True Otherwise, you can use struct.pack with <I format (<: little-endian, I: 4-bytes unsigned integer , see Format strings - struct module doc): >>> import struct >>> struct.pack('<I', 0xc6bf6f34) b'4o\xbf\xc6' UPDATE / NOTE: If you want to get big-endian (or network-endian), you should specify 'big' with int.to_bytes: 0xc6bf6f34.to_bytes(4, 'big') # == b'\xc6\xbf\x6f\x34' and > or ! with struct.pack: struct.pack('>I', 0xc6bf6f34) # == b'\xc6\xbf\x6f\x34' big-endian struct.pack('!I', 0xc6bf6f34) # == b'\xc6\xbf\x6f\x34' network (= big-endian)
Q: How can I encode a 32bit integer into a byte array? I'm required to send a 32bit integer over a serial connection like so: 0xc6bf6f34 should become: b'\xc6\xbf\x6f\x34'. To that end, I created this, but, as always after such coding, I wondered if it's pythonicism could be improved with something in the standard libary: def ltonlba(value): ''' ltonlba : Long to Network Long Byte Array ''' from socket import htonl value = htonl(value) ba = b'' for i in range(4): ba += chr((value) & 0xff) value >>= 8 return ba A: If you're using Python 3.2+, you can use int.to_bytes: >>> 0xc6bf6f34.to_bytes(4, 'little') # 4 bytes = 32 bits b'4o\xbf\xc6' >>> 0xc6bf6f34.to_bytes(4, 'little') == b'\x34\x6f\xbf\xc6' True Otherwise, you can use struct.pack with <I format (<: little-endian, I: 4-bytes unsigned integer , see Format strings - struct module doc): >>> import struct >>> struct.pack('<I', 0xc6bf6f34) b'4o\xbf\xc6' UPDATE / NOTE: If you want to get big-endian (or network-endian), you should specify 'big' with int.to_bytes: 0xc6bf6f34.to_bytes(4, 'big') # == b'\xc6\xbf\x6f\x34' and > or ! with struct.pack: struct.pack('>I', 0xc6bf6f34) # == b'\xc6\xbf\x6f\x34' big-endian struct.pack('!I', 0xc6bf6f34) # == b'\xc6\xbf\x6f\x34' network (= big-endian)
stackoverflow
{ "language": "en", "length": 188, "provenance": "stackexchange_0000F.jsonl.gz:874256", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44571093" }
0dbb623f5c85cf06d21741fb4e51ec6c29184b02
Stackoverflow Stackexchange Q: Conditional formatStyle in DT I want to color rows in column A by values in column B. The code below is based on the example from the vignette Link, but shows only the condition for two columns: mobile_number by mobile_flag. Data: head(test[, c("EMBG","mobile_number", "home_number", "mobile_flag", "home_number_flag")]) EMBG mobile_number home_number mobile_flag 1 101001455126 075-201-543 02/2446-275 correct 2 101010455015 55555555555 55555555555 incorrect 3 101014455095 0 0 incorrect 4 101947455134 075/482-356 02/2460-020 correct 5 101952450264 070 22 16 18 ---------------- correct 6 101953450012 0 02/2446-276 incorrect home_number_flag 1 correct 2 incorrect 3 incorrect 4 correct 5 incorrect 6 correct My DT table: > datatable(test) %>% formatStyle( + 'mobile_number', 'mobile_flag', + backgroundColor = styleEqual(c("correct", "incorrect"), c('green', 'red'))) However, I want to simultaniouslly color both mobile_number and home_number, based on home_number_flag and mobile_flag, respectivly. Any ideas how? A: Try something like this: library(DT) datatable(test) %>% formatStyle( columns = c("mobile_number", "home_number"), valueColumns = c("mobile_flag", "home_number_flag"), backgroundColor = styleEqual(c("correct", "incorrect"), c("green", "red")) ) columns specifies which columns you would like to conditionally format. valueColumns specifies which columns should be evaluated using the conditions specified in styleEqual of backgroundColor. Note that order in columns corresponds with order in valueColumns (e.g "mobile_number" is conditionally colored by "mobile_flag").
Q: Conditional formatStyle in DT I want to color rows in column A by values in column B. The code below is based on the example from the vignette Link, but shows only the condition for two columns: mobile_number by mobile_flag. Data: head(test[, c("EMBG","mobile_number", "home_number", "mobile_flag", "home_number_flag")]) EMBG mobile_number home_number mobile_flag 1 101001455126 075-201-543 02/2446-275 correct 2 101010455015 55555555555 55555555555 incorrect 3 101014455095 0 0 incorrect 4 101947455134 075/482-356 02/2460-020 correct 5 101952450264 070 22 16 18 ---------------- correct 6 101953450012 0 02/2446-276 incorrect home_number_flag 1 correct 2 incorrect 3 incorrect 4 correct 5 incorrect 6 correct My DT table: > datatable(test) %>% formatStyle( + 'mobile_number', 'mobile_flag', + backgroundColor = styleEqual(c("correct", "incorrect"), c('green', 'red'))) However, I want to simultaniouslly color both mobile_number and home_number, based on home_number_flag and mobile_flag, respectivly. Any ideas how? A: Try something like this: library(DT) datatable(test) %>% formatStyle( columns = c("mobile_number", "home_number"), valueColumns = c("mobile_flag", "home_number_flag"), backgroundColor = styleEqual(c("correct", "incorrect"), c("green", "red")) ) columns specifies which columns you would like to conditionally format. valueColumns specifies which columns should be evaluated using the conditions specified in styleEqual of backgroundColor. Note that order in columns corresponds with order in valueColumns (e.g "mobile_number" is conditionally colored by "mobile_flag").
stackoverflow
{ "language": "en", "length": 199, "provenance": "stackexchange_0000F.jsonl.gz:874277", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44571152" }
5cab2ad72abeabb70417259be9b3687a53a785a5
Stackoverflow Stackexchange Q: Bot Framework Event for Postbacks? My question: I have an adaptive card with a postback button whose value is say "thisIsMyPostback". Now, I want to act on this postback as one would. The problem is that this postback can also be typed out to reach the same result. In other words, clicking the button and also just messaging my bot "thisIsMyPostback" straight up result in the same thing. Is there a way to separate a postback message from a 'message_received'? That way a user messaging "thisIsMyPostback" straight up would not result in the same thing as clicking the button. Thanks! A: Is there a way to separate a postback message from a 'message_received'? That way a user messaging "thisIsMyPostback" straight up would not result in the same thing as clicking the button. No, it's not currently possible, because all messages, user or imBack/postBack, are of type "message" so there's no way to tell the difference unless you put some special text in your postBack and configure a triggerAction to recognize it. For more information on using trigger actions, see: https://learn.microsoft.com/en-us/bot-framework/nodejs/bot-builder-nodejs-global-handlers#trigger-a-help-dialog
Q: Bot Framework Event for Postbacks? My question: I have an adaptive card with a postback button whose value is say "thisIsMyPostback". Now, I want to act on this postback as one would. The problem is that this postback can also be typed out to reach the same result. In other words, clicking the button and also just messaging my bot "thisIsMyPostback" straight up result in the same thing. Is there a way to separate a postback message from a 'message_received'? That way a user messaging "thisIsMyPostback" straight up would not result in the same thing as clicking the button. Thanks! A: Is there a way to separate a postback message from a 'message_received'? That way a user messaging "thisIsMyPostback" straight up would not result in the same thing as clicking the button. No, it's not currently possible, because all messages, user or imBack/postBack, are of type "message" so there's no way to tell the difference unless you put some special text in your postBack and configure a triggerAction to recognize it. For more information on using trigger actions, see: https://learn.microsoft.com/en-us/bot-framework/nodejs/bot-builder-nodejs-global-handlers#trigger-a-help-dialog A: The Adaptive Cards readme on the BotFramework WebChat GitHub repo GitHub repo states: The data property of the action may be a string or it may be an object. A string is passed back to your bot as a Bot Builder SDK imBack activity, and an object is passed as a postBack activity. Activities with imBack appear in the chat stream as a user-entered reply. The postBack activities are not displayed. "actions": [ { "type": "Action.Submit", "title": "Next", "data": { "postBack": "thisIsMyPostback" } } ] If the value of the Activity doesn't have an object, then the user did not click the button.
stackoverflow
{ "language": "en", "length": 285, "provenance": "stackexchange_0000F.jsonl.gz:874293", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44571198" }
f3aecedf6c65de80304b90439c137a431e536110
Stackoverflow Stackexchange Q: mocking jquery $.ajax with jest Using jest how can I test a function that makes an ajax request in my jQuery app and mock its response? My app is not compiled in nodejs and runs straight in a browser. The example on the jest site https://github.com/facebook/jest/tree/master/examples/jquery assumes ajax function is a separate module and the whole app gets compiled with something like webpack. Here is my app: (function(root) { "use strict"; // if environment is node then import jquery. var $ = (typeof module === "object" && module.exports) ? require('jquery') : jQuery; function displayUser() { var fetchCurrentUser = function (url) { var xhr = $.get(url); $.when(xhr) .done(function(data) { greet(data); }) .fail(function(jqXHR, textStatus, errorThrown) { console.log(errorThrown); }); }; var greet = function(data) { $('#greet').text('Hello ' + data.name); } fetchCurrentUser('/my/api'); return { fetchCurrentUser: fetchCurrentUser, greet: greet }; } // Added this conditional so I can test in jest if (typeof module === "object" && module.exports) { // Node module.exports = displayUser(); } else { // Browser (root is window) root.displayUser = displayUser(); } })(this); A: Mock $.ajax by using jest.fn(). $.ajax = jest.fn().mockImplementation(() => { const fakeResponse = { id: 1, name: "All", value: "Dummy Data" }; return Promise.resolve(fakeResponse); });
Q: mocking jquery $.ajax with jest Using jest how can I test a function that makes an ajax request in my jQuery app and mock its response? My app is not compiled in nodejs and runs straight in a browser. The example on the jest site https://github.com/facebook/jest/tree/master/examples/jquery assumes ajax function is a separate module and the whole app gets compiled with something like webpack. Here is my app: (function(root) { "use strict"; // if environment is node then import jquery. var $ = (typeof module === "object" && module.exports) ? require('jquery') : jQuery; function displayUser() { var fetchCurrentUser = function (url) { var xhr = $.get(url); $.when(xhr) .done(function(data) { greet(data); }) .fail(function(jqXHR, textStatus, errorThrown) { console.log(errorThrown); }); }; var greet = function(data) { $('#greet').text('Hello ' + data.name); } fetchCurrentUser('/my/api'); return { fetchCurrentUser: fetchCurrentUser, greet: greet }; } // Added this conditional so I can test in jest if (typeof module === "object" && module.exports) { // Node module.exports = displayUser(); } else { // Browser (root is window) root.displayUser = displayUser(); } })(this); A: Mock $.ajax by using jest.fn(). $.ajax = jest.fn().mockImplementation(() => { const fakeResponse = { id: 1, name: "All", value: "Dummy Data" }; return Promise.resolve(fakeResponse); }); A: create a __mocks__/jquery.js in your project root to mock the jquery node_module. You can invoke functions in your mock jquery. Here's a simple code snippet: const $ = { ajax(xhr) { return this }, done(fn) { if (fn) fn(); return this; }, fail(fn) { if (fn) fn(); return this; } }; export default $; And add some expect in your fn to test your real logic. A: The easiest setup that I have found to test files without using modules and webpack is to manually create the scripts and to add them to window.document. You can reference relative paths directly inside the test file using the fs and path modules. Once you have everything working you can follow ycavatars answer in order to mock the ajax calls. Here is a simple snippet testing basic jQuery functionality, you can then add new scripts to test the functions in your own file: const fs = require('fs'); const path = require('path'); const jQueryFile = fs.readFileSync(path.resolve(__dirname, '../relative/path/to/jquery.js'), { encoding: 'utf-8' }); const srcFile = fs.readFileSync(path.resolve(__dirname, '../relative/path/to/yourScript.js'), { encoding: 'utf-8' }); describe('yourScript.js', () => { beforeAll(() => { // load the scripts const scriptEl = window.document.createElement('script'); scriptEl.textContent = jQueryFile; // add jQuery file window.document.body.appendChild(scriptEl); const scriptEl2 = window.document.createElement('script'); scriptEl2.textContent = srcFile; // add your src file window.document.body.appendChild(scriptEl2); }); describe('jQuery behaviour', () => { test('creates and find elements', () => { const $form = $('<form><input type="text" name="query" class="ff_search_input col-xs-11" autocomplete="off" placeholder="Che cosa stai cercando?"></form>'); const $input = $form.find('input'); expect($input.length).toBeGreaterThanOrEqual(1); }); }); });
stackoverflow
{ "language": "en", "length": 446, "provenance": "stackexchange_0000F.jsonl.gz:874298", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44571207" }
54965c8d758616342dc585a40bd33ca8be1c3330
Stackoverflow Stackexchange Q: React Native - Dangerous permissions auto granted without pop-up I am new to react-native and trying out permission model. I added following entry in AndroidManifes <uses-permission android:name="android.permission.READ_CONTACTS" /> Added following function async requestCameraPermission() { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.READ_CONTACTS, { 'title': 'Cool Photo App Camera Permission', 'message': 'Cool Photo App needs access to your camera ' + 'so you can take awesome pictures.' } ) if (granted === PermissionsAndroid.RESULTS.GRANTED) { console.log("You can use the camera") } else { console.log("Camera permission denied") } } catch (err) { console.warn(err) } } And registered it in constructor as follows this.requestCameraPermission = this.requestCameraPermission.bind(this); And called it as componentDidMount() { this.requestCameraPermission(); } I am getting permission auto granted without any pop-up to user. Please let me know if I am doing anything wrong or expecting wrong.
Q: React Native - Dangerous permissions auto granted without pop-up I am new to react-native and trying out permission model. I added following entry in AndroidManifes <uses-permission android:name="android.permission.READ_CONTACTS" /> Added following function async requestCameraPermission() { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.READ_CONTACTS, { 'title': 'Cool Photo App Camera Permission', 'message': 'Cool Photo App needs access to your camera ' + 'so you can take awesome pictures.' } ) if (granted === PermissionsAndroid.RESULTS.GRANTED) { console.log("You can use the camera") } else { console.log("Camera permission denied") } } catch (err) { console.warn(err) } } And registered it in constructor as follows this.requestCameraPermission = this.requestCameraPermission.bind(this); And called it as componentDidMount() { this.requestCameraPermission(); } I am getting permission auto granted without any pop-up to user. Please let me know if I am doing anything wrong or expecting wrong.
stackoverflow
{ "language": "en", "length": 135, "provenance": "stackexchange_0000F.jsonl.gz:874314", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44571248" }
29a46149222d49e70f65c681334ae0b0ba23889a
Stackoverflow Stackexchange Q: What is the use of value_type in STL containers? What's the use of value_type in STL containers? From the MSDN: // vector_value_type.cpp // compile with: /EHsc #include <vector> #include <iostream> int main( ) { using namespace std; vector<int>::value_type AnInt; AnInt = 44; cout << AnInt << endl; } I don't understand what does value_type achieve here? The variable could be an int as well? Is it used because the coders are lazy to check what's the type of objects present in the vector? I think these are also similar to it allocator_type,size_type,difference_type,reference,key_type etc.. A: Yes, in your example, it is pretty easy to know that you need an int. Where it gets complicated is generic programming. For example, if I wanted to write a generic sum() function, I would need it to know what kind of container to iterate and what type its elements are, so I would need to have something like this: template<typename Container> typename Container::value_type sum(const Container& cont) { typename Container::value_type total = 0; for (const auto& e : cont) total += e; return total; }
Q: What is the use of value_type in STL containers? What's the use of value_type in STL containers? From the MSDN: // vector_value_type.cpp // compile with: /EHsc #include <vector> #include <iostream> int main( ) { using namespace std; vector<int>::value_type AnInt; AnInt = 44; cout << AnInt << endl; } I don't understand what does value_type achieve here? The variable could be an int as well? Is it used because the coders are lazy to check what's the type of objects present in the vector? I think these are also similar to it allocator_type,size_type,difference_type,reference,key_type etc.. A: Yes, in your example, it is pretty easy to know that you need an int. Where it gets complicated is generic programming. For example, if I wanted to write a generic sum() function, I would need it to know what kind of container to iterate and what type its elements are, so I would need to have something like this: template<typename Container> typename Container::value_type sum(const Container& cont) { typename Container::value_type total = 0; for (const auto& e : cont) total += e; return total; }
stackoverflow
{ "language": "en", "length": 180, "provenance": "stackexchange_0000F.jsonl.gz:874355", "question_score": "22", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44571362" }
e206c47b391de9406cc17b339a3fc92341851b97
Stackoverflow Stackexchange Q: WebdriverIO: How to read baseURL value from wdio.conf.js. inside step definition file I am using WebdriverIO for test automation. In wdio.conf.js file I have configured the 'baseUrl' property. I want to read the 'baseUrl' property value inside my test .js file. How can I do this? A: Use browser.options.baseUrl . If you use require, you're hard coding from that one file, which is fine, but you cannot do a wdio --baseUrl=http://myTestSite2.net to override the "global" baseUrl. Which you might want to do in multiple deployments in the future.
Q: WebdriverIO: How to read baseURL value from wdio.conf.js. inside step definition file I am using WebdriverIO for test automation. In wdio.conf.js file I have configured the 'baseUrl' property. I want to read the 'baseUrl' property value inside my test .js file. How can I do this? A: Use browser.options.baseUrl . If you use require, you're hard coding from that one file, which is fine, but you cannot do a wdio --baseUrl=http://myTestSite2.net to override the "global" baseUrl. Which you might want to do in multiple deployments in the future. A: ❒ wdio-v5 Lately, after writing a lot of tests for a project rewrite I've came to believe the best way to store/access global config variables is via the global object. You can define them inside the wdio.conf.js file's hooks. I defined mine in the before hook: before: function (capabilities, specs) { // ================= // Assertion Library // ================= const chai = require('chai'); global.expect = chai.expect; global.assert = chai.assert; global.should = chai.should(); // ====================== // Miscellaneous Packages // ====================== global.langCode = langCode; global.countryCode = countryCode; global.request = require('superagent'); global.allowedStatusCodes = [200, 301], // =============== // Custom Commands // =============== require('./test/custom_commands/aFancyMethod'); require('./test/custom_commands/anotherOne'); require('./test/custom_commands/andAnotherOne'); }, Then, you can access them directly, anywhere in your test-files, or page-objects. This way, you greatly reduce the test-file's footprint (errr... codeprint) because you can call these directly in your test case: describe(`Testing a random URL`, () => { it('Should return a HTTP valid status code', async () => { // Issue a HTTP request for the given URL: await request .head('https://random.org') .then(res => { console.info(`\n> Status code found: ${res.status} | MIME type found: '${res.type}'\n`); foundStatusCode = res.status; }) .catch(err => { console.info(`\n> Status code found: ${err.status} | Error response found: '${JSON.stringify(err.response)}'\n`); foundStatusCode = err.status; }); // Assert the HTTP Status Code: assert.include(allowedStatusCodes, foundStatusCode, `!AssertError: Route yields a bad status code! Got: ${foundStatusCode} | Expected: ${allowedStatusCodes}`); }); As opposed to always doing await browser.options.request.head(..., browser.options.baseUrl, etc. ❒ wdio-v4 All the wdio.conf.js file attributes (basically the config object name-value pairs) are also stored inside the browser.options object. Thus, a more elegant approach to access your global config values from inside your tests would be as presented below: > browser.options { port: 4444, protocol: 'http', waitforTimeout: 10000, waitforInterval: 500, coloredLogs: true, deprecationWarnings: false, logLevel: 'verbose', baseUrl: 'http://localhost', // ... etc ... } > browser.options.baseUrl 'http://localhost' I'll go on a limb here and presume you want to read the baseUrl value from your wdio.config.js file, into your test.js file. TL;DR: In your test.js file heading, add the following: var config = require('<pathToWdioConfJS>/wdio.conf.js').config; You can then access any wdio.config.js value via the config.<configOption>, in your case config.baseUrl. Lastly, I would greatly recommend you read about exports and module exports. WebdriverIO is built on NodeJS, so you will shoot yourself in the foot on the long run if you don't know how and when to use exports, module.exports, require, or the difference between them. A: In wdio.config.js file define the url like this var baseUrl = 'YOUR URL' exports.config = { baseUrl: baseUrl, } In Test file use / instead of adding complete url in browser.url('/'), it will use the baseUrl from the wdio.config.js file. browser.url('/') A: BaseUrl is available in the config object browser.config.baseUrl See https://github.com/webdriverio/webdriverio/blob/a4a5a46f786f8548361d7f86834b38f89dcb1690/packages/webdriverio/webdriverio-core.d.ts#L131 A: just save all your variable in before: function and can be used anywhere in your test. like the following example i use retry count wdio config file before: function (capabilities, specs) { expect = require('chai').expect; should = require('chai').should(); assert = require('assert'); retryCount=2; browser.maximizeWindow();
stackoverflow
{ "language": "en", "length": 578, "provenance": "stackexchange_0000F.jsonl.gz:874356", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44571364" }
bab7a5d648b142d353b5643b76cfca429bec4a8e
Stackoverflow Stackexchange Q: Assign value to variable in Postman I'm trying to write a postman collection test and I'm struck at a point where I need to assign a value to global variable and use it in another api call. Here it goes: The api response is like this: { "status": "success", "code": 200, "data": { "expires_time": 10800, "authentication_token": "access-token", "refresh_token": "refresh-token" } } The test I'm writing is something like this: tests["Status code is 200"] = responseCode.code === 200; var jsonData = JSON.parse(responseBody); postman.setEnvironmentVariable("Authorization", jsonData.data.authentication_token); Thoughts? A: You are saying that you need to assign global variable while your code is trying to assign environment variable, which is different. Assigning global variable looks like following: postman.setGlobalVariable("variable_key", "variable_value"); Make sure to create global variable with empty value in the Postman UI first, and than you will be able to assign value to it using above piece of code.
Q: Assign value to variable in Postman I'm trying to write a postman collection test and I'm struck at a point where I need to assign a value to global variable and use it in another api call. Here it goes: The api response is like this: { "status": "success", "code": 200, "data": { "expires_time": 10800, "authentication_token": "access-token", "refresh_token": "refresh-token" } } The test I'm writing is something like this: tests["Status code is 200"] = responseCode.code === 200; var jsonData = JSON.parse(responseBody); postman.setEnvironmentVariable("Authorization", jsonData.data.authentication_token); Thoughts? A: You are saying that you need to assign global variable while your code is trying to assign environment variable, which is different. Assigning global variable looks like following: postman.setGlobalVariable("variable_key", "variable_value"); Make sure to create global variable with empty value in the Postman UI first, and than you will be able to assign value to it using above piece of code.
stackoverflow
{ "language": "en", "length": 146, "provenance": "stackexchange_0000F.jsonl.gz:874361", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44571380" }
34d9a07d5d9c41660323158e972d177858b233d3
Stackoverflow Stackexchange Q: Gradle android, how to exclude a single unit test I have an android project with unit and integration tests in the same folder. If I run ./gradlew test all of them are run, but I just need to exclude the cucumber tests from running, at the moment I just need to actually exclude to run the class with the annotation @RunWith(Cucumber.class). Any suggestions? A: The usual way of adding a test closure like below does not work for some reason with gradle android plugin: test { exclude 'com/example/MyTest.*' } Instead I have found the following option. Use the @Ignore annotation on your test(s). You can also conditionally ignore the test (e.g. based on a system property like RUN_AUTOMATION_TEST=false) using this answer If you are using spock rather than junit then use something like this: @IgnoreIf( {System.getProperty('RUN_AUTOMATION_TESTS') == null} ) public class MainScreenSpec extends BaseUiAutomationSpec { }
Q: Gradle android, how to exclude a single unit test I have an android project with unit and integration tests in the same folder. If I run ./gradlew test all of them are run, but I just need to exclude the cucumber tests from running, at the moment I just need to actually exclude to run the class with the annotation @RunWith(Cucumber.class). Any suggestions? A: The usual way of adding a test closure like below does not work for some reason with gradle android plugin: test { exclude 'com/example/MyTest.*' } Instead I have found the following option. Use the @Ignore annotation on your test(s). You can also conditionally ignore the test (e.g. based on a system property like RUN_AUTOMATION_TEST=false) using this answer If you are using spock rather than junit then use something like this: @IgnoreIf( {System.getProperty('RUN_AUTOMATION_TESTS') == null} ) public class MainScreenSpec extends BaseUiAutomationSpec { }
stackoverflow
{ "language": "en", "length": 147, "provenance": "stackexchange_0000F.jsonl.gz:874391", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44571469" }
b80a75014faf9644d7d3ce6589eba2b9f48b9b26
Stackoverflow Stackexchange Q: Unnecessary stack context saving in disassembly? (Using Apple LLVM version 8.1.0 (clang-802.0.42) Target: x86_64-apple-darwin16.6.0) When disassembling some code compiled with -O2, I noticed that a lot of them have a seemingly unnecessary saving and restoring of the base pointer rbp, usually looking like the following pushq %rbp movq %rsp, %rbp ... popq %rbp I know what this would be for, but it seems to be used even in situations where it seems completely unnecessary, such as in the following disassembled convoluted identity function emited by objdump __Z8identityI5arrayIiLm2EEET_S2_: 60: 55 pushq %rbp 61: 48 89 e5 movq %rsp, %rbp 64: 48 89 f8 movq %rdi, %rax 67: 5d popq %rbp 68: c3 retq 69: 0f 1f 80 00 00 00 00 nopl (%rax) where the only two meaningful instructions are the move from rdi to rax (first argument to return register) and the obviously necessary retq (I assume the nopl is for padding or alignment for whatever follows). Is there a reason for this seemingly unnecessary context save?
Q: Unnecessary stack context saving in disassembly? (Using Apple LLVM version 8.1.0 (clang-802.0.42) Target: x86_64-apple-darwin16.6.0) When disassembling some code compiled with -O2, I noticed that a lot of them have a seemingly unnecessary saving and restoring of the base pointer rbp, usually looking like the following pushq %rbp movq %rsp, %rbp ... popq %rbp I know what this would be for, but it seems to be used even in situations where it seems completely unnecessary, such as in the following disassembled convoluted identity function emited by objdump __Z8identityI5arrayIiLm2EEET_S2_: 60: 55 pushq %rbp 61: 48 89 e5 movq %rsp, %rbp 64: 48 89 f8 movq %rdi, %rax 67: 5d popq %rbp 68: c3 retq 69: 0f 1f 80 00 00 00 00 nopl (%rax) where the only two meaningful instructions are the move from rdi to rax (first argument to return register) and the obviously necessary retq (I assume the nopl is for padding or alignment for whatever follows). Is there a reason for this seemingly unnecessary context save?
stackoverflow
{ "language": "en", "length": 168, "provenance": "stackexchange_0000F.jsonl.gz:874428", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44571577" }
295d20b1e5676d19f1998315e51c347c7ced3c10
Stackoverflow Stackexchange Q: How to enable hocr font info in tesseract 4? I'm using tessseract 4 on ubuntu 16.04. so when using hocr feature in tesseract and after activating font info in hocr config file (hocr_font_info 1) I'm still not getting " x_font "info. Is there any other way to enable font info in tesseract4?
Q: How to enable hocr font info in tesseract 4? I'm using tessseract 4 on ubuntu 16.04. so when using hocr feature in tesseract and after activating font info in hocr config file (hocr_font_info 1) I'm still not getting " x_font "info. Is there any other way to enable font info in tesseract4?
stackoverflow
{ "language": "en", "length": 53, "provenance": "stackexchange_0000F.jsonl.gz:874444", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44571656" }
ff2317e95f82c53ffb6b6625ef697c3327a9d0f1
Stackoverflow Stackexchange Q: Cannot find namespace when using reexported class in generics First of all I was not sure what title should I give to this question. If someone has better idea feel free to edit it. I have a models folder in which I have a set of model classes: export default class Dog { id: string; } export default class Cat { id: string; } In same folder I also have an index.ts file exporting them like this: import Cat from './Cat'; import Dog from './Dog'; export default {Cat, Dog}; The idea is that in other places of my app I should be to import all models at once instead of importing them separately: import models from '../models'; This works as expected - I can create new instances like this: let dog = new models.Dog(); Unfortunately it is not working when I try to use it as a generic argument like this: class Foo extends Bar<models.Cat> { } When I try to do it I get following error: TS2503:Cannot find namespace 'models'. Is there a way to get this working for generic parameters?
Q: Cannot find namespace when using reexported class in generics First of all I was not sure what title should I give to this question. If someone has better idea feel free to edit it. I have a models folder in which I have a set of model classes: export default class Dog { id: string; } export default class Cat { id: string; } In same folder I also have an index.ts file exporting them like this: import Cat from './Cat'; import Dog from './Dog'; export default {Cat, Dog}; The idea is that in other places of my app I should be to import all models at once instead of importing them separately: import models from '../models'; This works as expected - I can create new instances like this: let dog = new models.Dog(); Unfortunately it is not working when I try to use it as a generic argument like this: class Foo extends Bar<models.Cat> { } When I try to do it I get following error: TS2503:Cannot find namespace 'models'. Is there a way to get this working for generic parameters?
stackoverflow
{ "language": "en", "length": 183, "provenance": "stackexchange_0000F.jsonl.gz:874457", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44571689" }
b0e7e79c843c775c14aac0ecebca86f99c99c7af
Stackoverflow Stackexchange Q: Is there a Java 8 equivalent of the collate method in grails? I'm trying to break a list into a list of lists. In groovy I can easily do this: def letters = 'a'..'g' assert letters.collate(3) == [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']] Is there an equivalent in Java 8? I've looked into Collectors, but it seems a bit complicated. I really just want to group the items in the list into x. A: You may look into the Partition API for lists by Guava : public static <T> java.util.List<java.util.List<T>> partition(java.util.List<T> list, int size) Returns consecutive sublists of a list, each of the same size (the final list may be smaller).
Q: Is there a Java 8 equivalent of the collate method in grails? I'm trying to break a list into a list of lists. In groovy I can easily do this: def letters = 'a'..'g' assert letters.collate(3) == [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']] Is there an equivalent in Java 8? I've looked into Collectors, but it seems a bit complicated. I really just want to group the items in the list into x. A: You may look into the Partition API for lists by Guava : public static <T> java.util.List<java.util.List<T>> partition(java.util.List<T> list, int size) Returns consecutive sublists of a list, each of the same size (the final list may be smaller). A: How about this? char start = 'a'; char last = 'g'; int n = 3; List<Character> letters = IntStream.rangeClosed(start, last) .mapToObj(it -> (char) it) .collect(toList()); List<List<Character>> result = IntStream.range(0, (letters.size() + n - 1) / n) .map(i -> i * n) .mapToObj(i -> letters.subList(i, Math.min(i + n, letters.size()))) .collect(toList()); OR List<List<Character>> result = IntStream.range(0, letters.size()).boxed(). collect(collectingAndThen( groupingBy(i -> i / n, mapping(letters::get, toList())), map -> new ArrayList<>(map.values()) )); A: This has been discussed before but I can't find it right now, so here is a neat way to do it: private static <T> Collector<T, ?, List<List<T>>> partitioning(int size) { class Acc { int count = 0; List<List<T>> list = new ArrayList<>(); void add(T elem) { int index = count++ / size; if (index == list.size()) { list.add(new ArrayList<>()); } list.get(index).add(elem); } Acc merge(Acc right) { List<T> lastLeftList = list.get(list.size() - 1); List<T> firstRightList = right.list.get(0); int lastLeftSize = lastLeftList.size(); int firstRightSize = firstRightList.size(); // they are both size, simply addAll will work if (lastLeftSize + firstRightSize == 2 * size) { System.out.println("Perfect!"); list.addAll(right.list); return this; } // last and first from each chunk are merged "perfectly" if (lastLeftSize + firstRightSize == size) { System.out.println("Almost perfect"); int x = 0; while (x < firstRightSize) { lastLeftList.add(firstRightList.remove(x)); --firstRightSize; } right.list.remove(0); list.addAll(right.list); return this; } right.list.stream().flatMap(List::stream).forEach(this::add); return this; } public List<List<T>> finisher() { return list; } } return Collector.of(Acc::new, Acc::add, Acc::merge, Acc::finisher); } And the usage: List<List<Integer>> list = Arrays.asList(1, 3, 4, 5, 9, 8, 7) .stream() .parallel() .collect(partitioning(3)); The thing is the this does a good job for parallel streams via the combiner. Also less code does not mean better or more productive solutions. A: Try my library abacus-common CharStream.rangeClosed('a', 'g').split(3).println(); // print out: [[a, b, c], [d, e, f], [g]]
stackoverflow
{ "language": "en", "length": 403, "provenance": "stackexchange_0000F.jsonl.gz:874464", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44571715" }
5a747fde2f5762b4c9dda607fa0fd754c9106cbc
Stackoverflow Stackexchange Q: Python 3 range Vs Python 2 range I recently started learning python 3. In python 2 the range() function can be used to assign list elements: >>> A = [] >>> A = range(0,6) >>> print A [0, 1, 2, 3, 4, 5] But in python 3 the range() function outputs this: >>> A = [] >>> A = range(0,6) >>> print(A) range(0, 6) Why is this happening? Why did python do this change? Is it a boon or a bane? A: in python 2, range is a built-in function. below is from the official python docs. it returns a list. range(stop) range(start, stop[, step]) This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. also you may check xrange only existing in python 2. it returns xrange object, mainly for fast iteration. xrange(stop) xrange(start, stop[, step]) This function is very similar to range(), but returns an xrange object instead of a list. by the way, python 3 merges these two into one range data type, working in a similar way of xrange in python 2. check the docs.
Q: Python 3 range Vs Python 2 range I recently started learning python 3. In python 2 the range() function can be used to assign list elements: >>> A = [] >>> A = range(0,6) >>> print A [0, 1, 2, 3, 4, 5] But in python 3 the range() function outputs this: >>> A = [] >>> A = range(0,6) >>> print(A) range(0, 6) Why is this happening? Why did python do this change? Is it a boon or a bane? A: in python 2, range is a built-in function. below is from the official python docs. it returns a list. range(stop) range(start, stop[, step]) This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. also you may check xrange only existing in python 2. it returns xrange object, mainly for fast iteration. xrange(stop) xrange(start, stop[, step]) This function is very similar to range(), but returns an xrange object instead of a list. by the way, python 3 merges these two into one range data type, working in a similar way of xrange in python 2. check the docs. A: Python 3 uses iterators for a lot of things where python 2 used lists.The docs give a detailed explanation including the change to range. The advantage is that Python 3 doesn't need to allocate the memory if you're using a large range iterator or mapping. For example for i in range(1000000000): print(i) requires a lot less memory in python 3. If you do happen to want Python to expand out the list all at once you can list_of_range = list(range(10)) A: Python 3 range() function is equivalent to python 2 xrange() function not range() Explanation In python 3 most function return Iterable objects not lists as in python 2 in order to save memory. Some of those are zip() filter() map() including .keys .values .items() dictionary methods But iterable objects are not efficient if your trying to iterate several times so you can still use list() method to convert them to lists A: In python3, do A = range(0,6) A = list(A) print(A) You will get the same result.
stackoverflow
{ "language": "en", "length": 359, "provenance": "stackexchange_0000F.jsonl.gz:874465", "question_score": "31", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44571718" }
00d0545694b6b10f83246d61f3a1ffe6b8f258cd
Stackoverflow Stackexchange Q: Is it safe to store per-request data on flask.request? Can the flask.request object be used similarly to flask.g to store per-request data? I am writing a library that is compatible with both Flask and Django. I plan to store information on the request object in both cases. Can I safely store objects on the request, say request.user, with the assurance that it will not be shared between different requests? A: Yes, it is safe. The request object is unique per request. Typically g is used because it is an empty namespace specifically created for holding data during a request. request is an internal object with existing meaning, although it is common for libraries to use it for storage, leaving g for "application level" data.
Q: Is it safe to store per-request data on flask.request? Can the flask.request object be used similarly to flask.g to store per-request data? I am writing a library that is compatible with both Flask and Django. I plan to store information on the request object in both cases. Can I safely store objects on the request, say request.user, with the assurance that it will not be shared between different requests? A: Yes, it is safe. The request object is unique per request. Typically g is used because it is an empty namespace specifically created for holding data during a request. request is an internal object with existing meaning, although it is common for libraries to use it for storage, leaving g for "application level" data.
stackoverflow
{ "language": "en", "length": 125, "provenance": "stackexchange_0000F.jsonl.gz:874482", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44571764" }
32ef041d17546676ae58fba526072f6902c1bc82
Stackoverflow Stackexchange Q: PostgreSQL ON CONFLICT with a WHERE clause Postgres documentation makes it seem like a WHERE clause is possible as an ON CONFLICT condition: https://www.postgresql.org/docs/9.5/static/sql-insert.html I have not been able to get this working (if it's possible). Here is one of the many permutations I've tried: INSERT INTO friends (id, dob, frn, status, "groupId", "createdAt", "updatedAt") VALUES ('1da04305-68ef-4dc1-be6c- 826ab83a6479', '1937-06-01T08:29:08-07:00', 100001, 'New', 'bc1567bc- 14ff-4ba2-b108-4cb2e0f0f768', NOW(), NOW()) ON CONFLICT WHERE frn=100001 DO NOTHING frn does not have any constraints, so the simpler syntax: ON CONFLICT (frn) DO NOTHING throws database errors. My hope is this is a simple syntax issue. A: The WHERE clause is subordinate to the ON CONFLICT (constraint) DO UPDATE SET ... clause. It only looks at the single row that violated the specified constraint when trying to INSERT. A syntactically valid example: INSERT INTO friends ( id, dob, frn, status, "groupId", "createdAt", "updatedAt" ) VALUES ( '1da04305-68ef-4dc1-be6c-826ab83a6479', '1937-06-01T08:29:08-07:00', 100001, 'New', 'bc1567bc-14ff-4ba2-b108-4cb2e0f0f768', NOW(), NOW() ) ON CONFLICT ("groupId", frn) DO UPDATE SET status='Revised', "updatedAt"=NOW() WHERE friends.status<>'Deleted'; Or as an operational example.
Q: PostgreSQL ON CONFLICT with a WHERE clause Postgres documentation makes it seem like a WHERE clause is possible as an ON CONFLICT condition: https://www.postgresql.org/docs/9.5/static/sql-insert.html I have not been able to get this working (if it's possible). Here is one of the many permutations I've tried: INSERT INTO friends (id, dob, frn, status, "groupId", "createdAt", "updatedAt") VALUES ('1da04305-68ef-4dc1-be6c- 826ab83a6479', '1937-06-01T08:29:08-07:00', 100001, 'New', 'bc1567bc- 14ff-4ba2-b108-4cb2e0f0f768', NOW(), NOW()) ON CONFLICT WHERE frn=100001 DO NOTHING frn does not have any constraints, so the simpler syntax: ON CONFLICT (frn) DO NOTHING throws database errors. My hope is this is a simple syntax issue. A: The WHERE clause is subordinate to the ON CONFLICT (constraint) DO UPDATE SET ... clause. It only looks at the single row that violated the specified constraint when trying to INSERT. A syntactically valid example: INSERT INTO friends ( id, dob, frn, status, "groupId", "createdAt", "updatedAt" ) VALUES ( '1da04305-68ef-4dc1-be6c-826ab83a6479', '1937-06-01T08:29:08-07:00', 100001, 'New', 'bc1567bc-14ff-4ba2-b108-4cb2e0f0f768', NOW(), NOW() ) ON CONFLICT ("groupId", frn) DO UPDATE SET status='Revised', "updatedAt"=NOW() WHERE friends.status<>'Deleted'; Or as an operational example.
stackoverflow
{ "language": "en", "length": 173, "provenance": "stackexchange_0000F.jsonl.gz:874522", "question_score": "13", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44571870" }
a7d9ded8c2c0def1cd3f651c0014ca0d92913eba
Stackoverflow Stackexchange Q: Difference between concat and push? Why does a return of the push method cause Uncaught TypeError: acc.push is not a function But a return concat results in the correct solution? [1, 2, 3, 4].reduce(function name(acc, curr) { if (even(curr)) { return acc.push(curr); } return acc; }, []); function even(number) { if (number % 2 === 0) { return true; } return false; } [1, 2, 3, 4].reduce(function name(acc, curr) { if (even(curr)) { return acc.concat(curr); } return acc; }, []); function even(number) { if (number % 2 === 0) { return true; } return false; } A: acc should not be an array. Look at the documentation. It can be one, but.. It makes no sense at all to reduce an array to an array. What you want is filter. I mean, reduce using an array as the accumulator and concating each element to it technically does work, but it is just not the right approach. var res = [1, 2, 3, 4].filter(even); console.log(res); function even(number) { return (number % 2 === 0); }
Q: Difference between concat and push? Why does a return of the push method cause Uncaught TypeError: acc.push is not a function But a return concat results in the correct solution? [1, 2, 3, 4].reduce(function name(acc, curr) { if (even(curr)) { return acc.push(curr); } return acc; }, []); function even(number) { if (number % 2 === 0) { return true; } return false; } [1, 2, 3, 4].reduce(function name(acc, curr) { if (even(curr)) { return acc.concat(curr); } return acc; }, []); function even(number) { if (number % 2 === 0) { return true; } return false; } A: acc should not be an array. Look at the documentation. It can be one, but.. It makes no sense at all to reduce an array to an array. What you want is filter. I mean, reduce using an array as the accumulator and concating each element to it technically does work, but it is just not the right approach. var res = [1, 2, 3, 4].filter(even); console.log(res); function even(number) { return (number % 2 === 0); } A: https://dev.to/uilicious/javascript-array-push-is-945x-faster-than-array-concat-1oki Concat is 945x slower than push only because it has to create a new array. A: The push() adds elements to the end of an array and returns the new length of the array. Thus your return here is invalid. The concat() method is used to merge arrays. Concat does not change the existing arrays, but instead returns a new array. Better to filter, if you want a NEW array like so: var arr = [1, 2, 3, 4]; var filtered = arr.filter(function(element, index, array) { return (index % 2 === 0); }); Note that assumes the array arr is complete with no gaps - all even indexed values. If you need each individual, use the element instead of index var arr = [1, 2, 3, 4]; var filtered = arr.filter(function(element, index, array) { return (element% 2 === 0); }); A: According to the MDN document say that: * *push() method: adds one or more elements to the end of an array and returns the new length of the array. const count = ['pigs', 'goats'].push('cows'); console.log(count); // expected output: 3 * *concat() method is used to merge two or more arrays. This method does not change the existing arrays but instead returns a new array console.log(['a'].concat(['b']));// expected output: Array ["a", "b"] And combined with the final Array#reduce's parameter is the array initialize []), which means that you want to return an array result. ==> So that's the reason why in case that you use concat working well. Refactor code * *If you still want to use Array#reduce and Array#push const even = (number) => number%2 === 0; const result = [1, 2, 3, 4].reduce(function name(acc, curr) { if(even(curr)) acc.push(curr); // Just add one more item instead of return return acc; }, []); console.log(result); *The simpler way is to use Array#filter const even = (number) => number%2 === 0; console.log([1, 2, 3, 4].filter(even));
stackoverflow
{ "language": "en", "length": 489, "provenance": "stackexchange_0000F.jsonl.gz:874572", "question_score": "71", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44572026" }
f92f937c35fea920e9df73422a978991aa765283
Stackoverflow Stackexchange Q: What are the arguments for scipy.stats.uniform? I'm trying to create a uniform distribution between two numbers (lower bound and upper bound) in order to feed it to sklearn's ParameterSampler. I am using scipy.stats.uniform in the following format: from scipy.stats import uniform params = ParameterSampler({'bandwidth':uniform(5,50)}, 20) But when I get the random selections of the 'bandwidth' parameter, they are not all between 5 and 50. Some of them are bigger than 50 by a bit. So my question is what do the arguments in scipy.stats.uniform represent? Are they not a lower bound and upper bound? The documentation shows no arguments so I can't figure it out from that. A: In the given case the call should look like that: uniform.rvs(loc=5, scale=45) Even though it's possible to call the distribution directly with parameters, scipy.stats has the following logic: <dist_name>.rvs(loc=<param1>, scale=<param2>, size=(Nx, Ny))
Q: What are the arguments for scipy.stats.uniform? I'm trying to create a uniform distribution between two numbers (lower bound and upper bound) in order to feed it to sklearn's ParameterSampler. I am using scipy.stats.uniform in the following format: from scipy.stats import uniform params = ParameterSampler({'bandwidth':uniform(5,50)}, 20) But when I get the random selections of the 'bandwidth' parameter, they are not all between 5 and 50. Some of them are bigger than 50 by a bit. So my question is what do the arguments in scipy.stats.uniform represent? Are they not a lower bound and upper bound? The documentation shows no arguments so I can't figure it out from that. A: In the given case the call should look like that: uniform.rvs(loc=5, scale=45) Even though it's possible to call the distribution directly with parameters, scipy.stats has the following logic: <dist_name>.rvs(loc=<param1>, scale=<param2>, size=(Nx, Ny)) A: The first argument is the lower bound, and the second argument is the range of the distribution. So the example distribution in your question is uniform between 5 and 55. Quoting from the documentation linked in your question: A uniform continuous random variable. This distribution is constant between loc and loc + scale. loc is the first argument and scale is the second argument. A: The loc is the lower bound and scale is upper bound subtracted from the lower bound. Function Here is a function to do that for you: from scipy.stats import uniform def get_uniform(min, max): """Transform min (lower bound) and max (upper bound) to scipy.stats.uniform parameters""" return uniform(loc=min, scale=max-min) Proof I tested it with this: size = 100000 experiments = [ (5_000, 10_000), (-10_000, -5_000), (-1_000, 0), (0, 1_000), ] for lb, ub in experiments: print(f"Experiment (Lower: {lb}, Upper: {ub})") rand_values = get_uniform(min=lb, max=ub).rvs(size) print(f"Observed range: {int(round(rand_values.min(), 0))} to {int(round(rand_values.max(), 0))}") print() Which gives: Experiment (Lower: 5000, Upper: 10000) Observed range: 5000 to 10000 Experiment (Lower: -10000, Upper: -5000) Observed range: -10000 to -5000 Experiment (Lower: -1000, Upper: 0) Observed range: -1000 to 0 Experiment (Lower: 0, Upper: 1000) Observed range: 0 to 1000 Which is exactly as you would expect.
stackoverflow
{ "language": "en", "length": 346, "provenance": "stackexchange_0000F.jsonl.gz:874601", "question_score": "14", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44572109" }
87a74418ac7f6ce6cbbbfda0ea1979e01ae741d7
Stackoverflow Stackexchange Q: React Grid System equivalent to Bootstrap's Grid system? I'm looking to start styling my React app. I have previously used Bootstrap's Grid system and am now looking for the React grid system. What do React developers commonly use for their App's Grid system / Layout? A: If you are targeting only modern browsers (i.e. those with flexbox support) you may want to investigate react-flexbox-grid which offers a set of React components that implement the usual grid concepts like Row and Column. I've used in successfully in a couple of projects. This option avoids the need to pull in a whole UI library and only use the grid portions.
Q: React Grid System equivalent to Bootstrap's Grid system? I'm looking to start styling my React app. I have previously used Bootstrap's Grid system and am now looking for the React grid system. What do React developers commonly use for their App's Grid system / Layout? A: If you are targeting only modern browsers (i.e. those with flexbox support) you may want to investigate react-flexbox-grid which offers a set of React components that implement the usual grid concepts like Row and Column. I've used in successfully in a couple of projects. This option avoids the need to pull in a whole UI library and only use the grid portions. A: I have just used bootstrap, either styling directly with bootstrap css or via this react-bootstrap library. A: I'm not sure what you mean by React Grid system as it's always CSS grid system. However in my projects I am using react-bootstrap library and I'm guessing it is something you are looking for. The only caveat is that you have to include bootstrap css file (for example from c.d.n.), other than that its working really fine and has great documentation. P.S. If you would like to only use Grid system, you would then have to find css with bootstrap Grid only, and then import only Grid components from library - Grid, Row and Col. A: I used bootstraps grid system for a long time, but after a while I got tired of adding a bunch of classes and it started to make my HTML unreadable. I would suggest using flexbox. It's a great replacement and is becoming the standard for responsive designs. It's also supported by all major browsers which is nice. A: Take a look at fluid-react I built. It doesn't need extra CSS. <Container> <Row> <Col xs="12" sm="6" md="4" lg="3" xl="2">1</Col> <Col xs="12" sm="6" md="4" lg="3" xl="2">2</Col> <Col xs="12" sm="6" md="4" lg="3" xl="2">3</Col> <Col xs="12" sm="6" md="4" lg="3" xl="2">4</Col> <Col xs="12" sm="6" md="4" lg="3" xl="2">5</Col> <Col xs="12" sm="6" md="4" lg="3" xl="2">6</Col> <Col xs="12" sm="6" md="4" lg="3" xl="2">7</Col> <Col xs="12" sm="6" md="4" lg="3" xl="2">8</Col> <Col xs="12" sm="6" md="4" lg="3" xl="2">9</Col> <Col xs="12" sm="6" md="4" lg="3" xl="2">10</Col> <Col xs="12" sm="6" md="4" lg="3" xl="2">11</Col> <Col xs="12" sm="6" md="4" lg="3" xl="2">12</Col> </Row> </Container>
stackoverflow
{ "language": "en", "length": 370, "provenance": "stackexchange_0000F.jsonl.gz:874602", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44572113" }
fe2747b513b7674573f5ab38e0c65b28d11f36d7
Stackoverflow Stackexchange Q: What is the difference between gradlew assemble and gradlew compile I noticed that ./gradlew tasks for my android project gives me assemble* and compile* tasks. What is the difference? I also noticed that the command lists the tasks compileDemoDebugSources as well as compileDemoReleaseSources (where demo is a flavor and release is a build type) but only assembleDemo (instead of assembleDemoDebug and assembleDemoRelease) -- however the latter two work just as fine. Why is that? A: From the official manual: ┏━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ Task ┃ Description ┃ ┣━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ ┃ compileJava ┃ Compiles production Java ┃ ┃ ┃ source files using javac ┃ ┣━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ ┃ assemble ┃ Assembles all the archives ┃ ┃ ┃ in the project ┃ ┗━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ To investigate further, read Gradle 4.0 documentation: * *Table 47.3. Java plugin - lifecycle tasks *Table 47.1. Java plugin - tasks P.S. drkstr1 has already mentioned main differences in the comment.
Q: What is the difference between gradlew assemble and gradlew compile I noticed that ./gradlew tasks for my android project gives me assemble* and compile* tasks. What is the difference? I also noticed that the command lists the tasks compileDemoDebugSources as well as compileDemoReleaseSources (where demo is a flavor and release is a build type) but only assembleDemo (instead of assembleDemoDebug and assembleDemoRelease) -- however the latter two work just as fine. Why is that? A: From the official manual: ┏━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ Task ┃ Description ┃ ┣━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ ┃ compileJava ┃ Compiles production Java ┃ ┃ ┃ source files using javac ┃ ┣━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ ┃ assemble ┃ Assembles all the archives ┃ ┃ ┃ in the project ┃ ┗━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ To investigate further, read Gradle 4.0 documentation: * *Table 47.3. Java plugin - lifecycle tasks *Table 47.1. Java plugin - tasks P.S. drkstr1 has already mentioned main differences in the comment.
stackoverflow
{ "language": "en", "length": 148, "provenance": "stackexchange_0000F.jsonl.gz:874608", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44572129" }
16b6f61092689da90d0679c8809f75c0ada96157
Stackoverflow Stackexchange Q: Making Large Title Display on iOS 11 Right to Left As of iOS 11, Apple has added Large Title Display Mode for UINavigationBar and UINavigationItem which makes an effect like this: We could simply turn this effect on using the following Swift code: navigationBar.prefersLargeTitles = true My question is how we can make the large title right to left to be usable for Eastern right to left languages? Thanks in advance. A: I use this approach : override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.subviews[1].semanticContentAttribute = .forceRightToLeft }
Q: Making Large Title Display on iOS 11 Right to Left As of iOS 11, Apple has added Large Title Display Mode for UINavigationBar and UINavigationItem which makes an effect like this: We could simply turn this effect on using the following Swift code: navigationBar.prefersLargeTitles = true My question is how we can make the large title right to left to be usable for Eastern right to left languages? Thanks in advance. A: I use this approach : override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.subviews[1].semanticContentAttribute = .forceRightToLeft } A: Well, it should be auto RTL for all RTL languages. All you have to do is to set a device language as one of RTL languages. Or, if you debug this in simulator, you can use on of Instruments Xcode is delivered with to simulate RTL while you are actually using LTR language
stackoverflow
{ "language": "en", "length": 141, "provenance": "stackexchange_0000F.jsonl.gz:874618", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44572155" }
2b1ba662ae7888ce22bebb06feef5fdc774a97b6
Stackoverflow Stackexchange Q: Nested Queries not working in iOS sdk, but works fine in loopback explorer Currently I'm working on a project that gets values using iOS loopback sdk. Everything works by the book if its is one query. But when nested query, like below, occurs it shows error Error Domain=AFNetworkingErrorDomain Code=-1011 "Expected status code in (200-299), got 500" UserInfo={NSLocalizedRecoverySuggestion={"error":{"name":"Error","status":500,"message":"Relation \"relation\" is not defined for UserGroup model","stack":"Error: Relation \"relation\" is not defined for UserGroup model The query is as below NSDictionary *filterParams = @{ @"where" : @{ @"group_id" : self.groupDetails[@"groupId"]}, @"include" : @[@"invitedusers", @{ @"relation" : @"userstatus", @"scope": @{ @"include":@[ @"useruploads" ] } }] }; A: NSDictionary *filterParams = @{ @"where" : @{ @"group_id" : self.groupDetails[@"groupId"] }, @"include" : @[ @"invitedusers", @{ @"userstatus" : @"useruploads" } ] }; You can refer to this also: https://loopback.io/doc/en/lb2/Include-filter.html
Q: Nested Queries not working in iOS sdk, but works fine in loopback explorer Currently I'm working on a project that gets values using iOS loopback sdk. Everything works by the book if its is one query. But when nested query, like below, occurs it shows error Error Domain=AFNetworkingErrorDomain Code=-1011 "Expected status code in (200-299), got 500" UserInfo={NSLocalizedRecoverySuggestion={"error":{"name":"Error","status":500,"message":"Relation \"relation\" is not defined for UserGroup model","stack":"Error: Relation \"relation\" is not defined for UserGroup model The query is as below NSDictionary *filterParams = @{ @"where" : @{ @"group_id" : self.groupDetails[@"groupId"]}, @"include" : @[@"invitedusers", @{ @"relation" : @"userstatus", @"scope": @{ @"include":@[ @"useruploads" ] } }] }; A: NSDictionary *filterParams = @{ @"where" : @{ @"group_id" : self.groupDetails[@"groupId"] }, @"include" : @[ @"invitedusers", @{ @"userstatus" : @"useruploads" } ] }; You can refer to this also: https://loopback.io/doc/en/lb2/Include-filter.html
stackoverflow
{ "language": "en", "length": 133, "provenance": "stackexchange_0000F.jsonl.gz:874650", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44572227" }
61be2468120577d6c6a978a5a07113c7f000fb63
Stackoverflow Stackexchange Q: How to validate that value is an Integer with Firebase rules I'm trying to make sure that some field of an object in firebase is an integer and not decimal. There is a method isNumber() but it returns true wheter value is an integer or a decimal. I've tried to check a value with regex, but for some reason it works properly only with values within quotation marks ie strings. This is how my rule looks: "$item_id":{ "created":{ ".validate":"newData.val().matches(/^[0-9]+$/)" } } So when I put an object with string value like this {"created":"123456789"} validation works fine. But when I put an object with number value {"created":123456789} validation fails. Is there a way to do this? A: You cannot use a regular expression to validate a number, since regular expressions match patterns in strings. You can also not really validate that something is an integer, since JavaScript doesn't have a separate integer vs floating point type. They're all just floating point numbers. What you can validate is that something is a whole number. The simplest way I could come up with is: ".validate":"newData.isNumber() && newData.val() % 1 === 0.0" This accepts 1 and 1.0, but will reject 1.1.
Q: How to validate that value is an Integer with Firebase rules I'm trying to make sure that some field of an object in firebase is an integer and not decimal. There is a method isNumber() but it returns true wheter value is an integer or a decimal. I've tried to check a value with regex, but for some reason it works properly only with values within quotation marks ie strings. This is how my rule looks: "$item_id":{ "created":{ ".validate":"newData.val().matches(/^[0-9]+$/)" } } So when I put an object with string value like this {"created":"123456789"} validation works fine. But when I put an object with number value {"created":123456789} validation fails. Is there a way to do this? A: You cannot use a regular expression to validate a number, since regular expressions match patterns in strings. You can also not really validate that something is an integer, since JavaScript doesn't have a separate integer vs floating point type. They're all just floating point numbers. What you can validate is that something is a whole number. The simplest way I could come up with is: ".validate":"newData.isNumber() && newData.val() % 1 === 0.0" This accepts 1 and 1.0, but will reject 1.1.
stackoverflow
{ "language": "en", "length": 198, "provenance": "stackexchange_0000F.jsonl.gz:874675", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44572284" }
5f859a02535b6a5517cce45d43bbd6f39b041613
Stackoverflow Stackexchange Q: Change the default REST response to JSON instead XML I'm pretty new with Java REST, I'm currently confused with the response I'm getting from POSTMAN or Chrome is always defaulted to XML and could not change it to JSON unless I remove the XML part. I'm using Jersey 2, Netbeans and Glassfish 4.1.1/4.1 This only returns XML @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) This will return JSON only @GET @Path("loc/{lat}/{long}") @Produces({MediaType.APPLICATION_JSON}) @SuppressWarnings("unchecked") //@Produces({MediaType.TEXT_PLAIN}) public List<Lastknown> findNearMeLastKnown(@PathParam("lat") String lat, @PathParam("long") String longitude) { //List<Lastknown> results =; return super.findNearMeLastKnown(lat,longitude); } A: A quick guess, you have to add the following header in POSTMAN: Accept: application/json Otherwise the server doesn't know which format you want....
Q: Change the default REST response to JSON instead XML I'm pretty new with Java REST, I'm currently confused with the response I'm getting from POSTMAN or Chrome is always defaulted to XML and could not change it to JSON unless I remove the XML part. I'm using Jersey 2, Netbeans and Glassfish 4.1.1/4.1 This only returns XML @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) This will return JSON only @GET @Path("loc/{lat}/{long}") @Produces({MediaType.APPLICATION_JSON}) @SuppressWarnings("unchecked") //@Produces({MediaType.TEXT_PLAIN}) public List<Lastknown> findNearMeLastKnown(@PathParam("lat") String lat, @PathParam("long") String longitude) { //List<Lastknown> results =; return super.findNearMeLastKnown(lat,longitude); } A: A quick guess, you have to add the following header in POSTMAN: Accept: application/json Otherwise the server doesn't know which format you want....
stackoverflow
{ "language": "en", "length": 108, "provenance": "stackexchange_0000F.jsonl.gz:874681", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44572315" }
5a8fedbe63f8fd467706aa9c0cc59b483e5936fd
Stackoverflow Stackexchange Q: How does Flutter calculate pixels for different resolutions? Flutter apps can run on a variety of hardware, operating systems, and form factors. How are "pixels" calculated for different resolutions? A: From https://api.flutter.dev/flutter/dart-ui/FlutterView/devicePixelRatio.html : The number of device pixels for each logical pixel. This number might not be a power of two. Indeed, it might not even be an integer. For example, the Nexus 6 has a device pixel ratio of 3.5. Device pixels are also referred to as physical pixels. Logical pixels are also referred to as device-independent or resolution-independent pixels. By definition, there are roughly 38 logical pixels per centimeter, or about 96 logical pixels per inch, of the physical display. The value returned by devicePixelRatio is ultimately obtained either from the hardware itself, the device drivers, or a hard-coded value stored in the operating system or firmware, and may be inaccurate, sometimes by a significant margin. The Flutter framework operates in logical pixels, so it is rarely necessary to directly deal with this property.
Q: How does Flutter calculate pixels for different resolutions? Flutter apps can run on a variety of hardware, operating systems, and form factors. How are "pixels" calculated for different resolutions? A: From https://api.flutter.dev/flutter/dart-ui/FlutterView/devicePixelRatio.html : The number of device pixels for each logical pixel. This number might not be a power of two. Indeed, it might not even be an integer. For example, the Nexus 6 has a device pixel ratio of 3.5. Device pixels are also referred to as physical pixels. Logical pixels are also referred to as device-independent or resolution-independent pixels. By definition, there are roughly 38 logical pixels per centimeter, or about 96 logical pixels per inch, of the physical display. The value returned by devicePixelRatio is ultimately obtained either from the hardware itself, the device drivers, or a hard-coded value stored in the operating system or firmware, and may be inaccurate, sometimes by a significant margin. The Flutter framework operates in logical pixels, so it is rarely necessary to directly deal with this property.
stackoverflow
{ "language": "en", "length": 167, "provenance": "stackexchange_0000F.jsonl.gz:874687", "question_score": "18", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44572330" }
10472c7e6687dcb66ffbad69618bd861564b4d07
Stackoverflow Stackexchange Q: Filtering redux-form Actions in redux-logger with Predicate option Can anyone offer a tip on filtering actions from Redux-Logger? I'm attempting to filter @@redux-form/BLUR and the like coming from Redux Form. Based upon the Redux Logger Recipe here https://github.com/evgenyrodionov/redux-logger#log-everything-except-actions-with-certain-type Log everything except actions with certain type createLogger({ predicate: (getState, action) => action.type !== AUTH_REMOVE_TOKEN }); Based upon the recipe cited above I would expect to provide a statement with the expression formatted similarly and to return false. I am logging successfully passing the collapsed option, so I wouldn't suspect I'm doing anything wrong in applyMiddlewear(). predicate:(getState, action) => action.type !== @@redux-form/FOCUS || @@redux-form/BLUR || @@redux-form/FOCUS A: From the creator of Redux-Logger: predicate:(getState, action) => !action.type.includes('@@redux-form') Full Example: import { applyMiddleware, createStore } from 'redux'; import { createLogger } from 'redux-logger'; const logger = createLogger({ predicate: (getState, action) => !action.type.includes('@@redux-form'), //...other options }); const store = createStore( reducer, applyMiddleware(logger) );
Q: Filtering redux-form Actions in redux-logger with Predicate option Can anyone offer a tip on filtering actions from Redux-Logger? I'm attempting to filter @@redux-form/BLUR and the like coming from Redux Form. Based upon the Redux Logger Recipe here https://github.com/evgenyrodionov/redux-logger#log-everything-except-actions-with-certain-type Log everything except actions with certain type createLogger({ predicate: (getState, action) => action.type !== AUTH_REMOVE_TOKEN }); Based upon the recipe cited above I would expect to provide a statement with the expression formatted similarly and to return false. I am logging successfully passing the collapsed option, so I wouldn't suspect I'm doing anything wrong in applyMiddlewear(). predicate:(getState, action) => action.type !== @@redux-form/FOCUS || @@redux-form/BLUR || @@redux-form/FOCUS A: From the creator of Redux-Logger: predicate:(getState, action) => !action.type.includes('@@redux-form') Full Example: import { applyMiddleware, createStore } from 'redux'; import { createLogger } from 'redux-logger'; const logger = createLogger({ predicate: (getState, action) => !action.type.includes('@@redux-form'), //...other options }); const store = createStore( reducer, applyMiddleware(logger) );
stackoverflow
{ "language": "en", "length": 149, "provenance": "stackexchange_0000F.jsonl.gz:874689", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44572341" }
f2ffbe8e10368f5eeb6fd8bacacfb4fb7c737f58
Stackoverflow Stackexchange Q: is not assignable to parameter of type 'Expected>' in editor My tests are passing from command line, however I edit the typescript source using Atom. And when I open one of the test files in my editor, I'm seeing an error on this line: expect(pageObject.name.getText()).toEqual('Some name'); This is the error: Typescript Error Argument of type '"Some name"' is not assignable to parameter of type 'Expected<Promise<string>>'.at line 16 col 50 Why does this show in my editor? Yet tests pass. Command to run protractor tests: protractor dist/protractor.config.js Snippet from package.json "dependencies": { "typescript": "2.3.3" }, "devDependencies": { "@types/jasmine": "2.5.45", "@types/node": "^7.0.13", "jasmine-core": "^2.6.0", "jasmine-spec-reporter": "^4.1.0", "protractor": "^5.1.2" } tsconfig.fvt.test.json { "compilerOptions": { "module": "commonjs", "noImplicitAny": true, "noUnusedLocals": true, "moduleResolution": "node", "sourceMap": false, "emitDecoratorMetadata": true, "experimentalDecorators": true, "noUnusedParameters": true, "outDir": "dist", "skipLibCheck": true, "target": "ES5", "lib": [ "dom", "es5", "es6", "scripthost" ], "types": ["jasmine"] }, "include": [ "protractor.config.ts", "test/e2e/**/*.ts" ] } A: getText() returns promise. See the doc. If you want to assert text from an element you need chai-as-promise. See example.
Q: is not assignable to parameter of type 'Expected>' in editor My tests are passing from command line, however I edit the typescript source using Atom. And when I open one of the test files in my editor, I'm seeing an error on this line: expect(pageObject.name.getText()).toEqual('Some name'); This is the error: Typescript Error Argument of type '"Some name"' is not assignable to parameter of type 'Expected<Promise<string>>'.at line 16 col 50 Why does this show in my editor? Yet tests pass. Command to run protractor tests: protractor dist/protractor.config.js Snippet from package.json "dependencies": { "typescript": "2.3.3" }, "devDependencies": { "@types/jasmine": "2.5.45", "@types/node": "^7.0.13", "jasmine-core": "^2.6.0", "jasmine-spec-reporter": "^4.1.0", "protractor": "^5.1.2" } tsconfig.fvt.test.json { "compilerOptions": { "module": "commonjs", "noImplicitAny": true, "noUnusedLocals": true, "moduleResolution": "node", "sourceMap": false, "emitDecoratorMetadata": true, "experimentalDecorators": true, "noUnusedParameters": true, "outDir": "dist", "skipLibCheck": true, "target": "ES5", "lib": [ "dom", "es5", "es6", "scripthost" ], "types": ["jasmine"] }, "include": [ "protractor.config.ts", "test/e2e/**/*.ts" ] } A: getText() returns promise. See the doc. If you want to assert text from an element you need chai-as-promise. See example. A: Currently, you can try npm i "@types/jasminewd2" -D and add jasminewd2 in your tsconfig.json compilerOptions.types I met the problem either with protractor. It was the typing bug. Here is the issue link. A: Because it is an async method simply change from expect(pageObject.name.getText()).toEqual('Some name'); to expect(await pageObject.name.getText()).toEqual('Some name');
stackoverflow
{ "language": "en", "length": 220, "provenance": "stackexchange_0000F.jsonl.gz:874692", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44572351" }
98502c7b14316af9c1b2df9eb1a91b4bccfff6a3
Stackoverflow Stackexchange Q: Failed to load resource: net::ERR_BLOCKED_BY_RESPONSE I am looking for some solution of this issue of iframe domain.com/:1 Refused to display 'domain.com/?q=node/add/editor' in a frame because it set 'X-Frame-Options' to 'sameorigin'. domain.com/?q=node/add/editor Failed to load resource: net::ERR_BLOCKED_BY_RESPONSE domain.com/:1 Refused to display 'domain.com/?q=node/add/editor' in a frame because it set 'X-Frame-Options' to 'sameorigin'. pay.webintellizer.com/?q=node/add/editor Failed to load resource: net::ERR_BLOCKED_BY_RESPONSE FYI both sites are drupal based, if it has any special code. I have already tested same domain and different domain both url for iframe but same error. A: As explained on https://stackoverflow.com/a/33777934/195812 check your x-frame-options value ... they have disallowed loading of the resource in an iframe outside of their domain. So this iframe is not able to display cross domain.
Q: Failed to load resource: net::ERR_BLOCKED_BY_RESPONSE I am looking for some solution of this issue of iframe domain.com/:1 Refused to display 'domain.com/?q=node/add/editor' in a frame because it set 'X-Frame-Options' to 'sameorigin'. domain.com/?q=node/add/editor Failed to load resource: net::ERR_BLOCKED_BY_RESPONSE domain.com/:1 Refused to display 'domain.com/?q=node/add/editor' in a frame because it set 'X-Frame-Options' to 'sameorigin'. pay.webintellizer.com/?q=node/add/editor Failed to load resource: net::ERR_BLOCKED_BY_RESPONSE FYI both sites are drupal based, if it has any special code. I have already tested same domain and different domain both url for iframe but same error. A: As explained on https://stackoverflow.com/a/33777934/195812 check your x-frame-options value ... they have disallowed loading of the resource in an iframe outside of their domain. So this iframe is not able to display cross domain.
stackoverflow
{ "language": "en", "length": 119, "provenance": "stackexchange_0000F.jsonl.gz:874704", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44572387" }
c94abefe20f4c215699237eae14ddfb6240d51d4
Stackoverflow Stackexchange Q: Angular 4 removing dynamically added components Using something like this: https://netbasal.com/dynamically-creating-components-with-angular-a7346f4a982d I'm adding multiple components, the question is how do I remove the components later on based on which was clicked? what I'm trying to do is create breadCrumbs, and when clicking on the crumb, remove it all all below it. to create them I use this code: createCrumb(name, key, level){ let data = {name:name, key:key, level,level, diagram: this.diagram}; const factory = this.this.resolver.resolveComponentFactory(BreadCrumbsButton); let componentRef = this.container.createOmponent(factory); (<BreadCrumbsButton>componentRef.instance).data = data; } all this works perfectly, but I add multiples of this. the question is how do I remove specific ones while leaving the rest? A: You can call destroy method on it: createComponent(type) { this.container.clear(); const factory: ComponentFactory = this.resolver.resolveComponentFactory(AlertComponent); this.componentRef: ComponentRef = this.container.createComponent(factory); setTimeout(()=>{ this.componentRef.destroy(); <-------------------- }, 2000); } I'm using a timeout here for demonstration purposes so that a component can be seen rendered on the screen.
Q: Angular 4 removing dynamically added components Using something like this: https://netbasal.com/dynamically-creating-components-with-angular-a7346f4a982d I'm adding multiple components, the question is how do I remove the components later on based on which was clicked? what I'm trying to do is create breadCrumbs, and when clicking on the crumb, remove it all all below it. to create them I use this code: createCrumb(name, key, level){ let data = {name:name, key:key, level,level, diagram: this.diagram}; const factory = this.this.resolver.resolveComponentFactory(BreadCrumbsButton); let componentRef = this.container.createOmponent(factory); (<BreadCrumbsButton>componentRef.instance).data = data; } all this works perfectly, but I add multiples of this. the question is how do I remove specific ones while leaving the rest? A: You can call destroy method on it: createComponent(type) { this.container.clear(); const factory: ComponentFactory = this.resolver.resolveComponentFactory(AlertComponent); this.componentRef: ComponentRef = this.container.createComponent(factory); setTimeout(()=>{ this.componentRef.destroy(); <-------------------- }, 2000); } I'm using a timeout here for demonstration purposes so that a component can be seen rendered on the screen. A: Also check this answer with Demo Dynamically ADDING and REMOVING Components in Angular Update You can now use subject instead of interface for components' communication Read about RxJS Subject Removing child components from parent so communication between them must be started but how? Using interface in this case What's happening ? Parent is creating the childs and when a child tries to remove itself, it tells its parent via interface to remove it so the parent does. import { ComponentRef, ComponentFactoryResolver, ViewContainerRef, ViewChild, Component } from "@angular/core"; // Parent Component @Component({ selector: 'parent', template: ` <button type="button" (click)="createComponent()"> Create Child </button> <div> <ng-template #viewContainerRef></ng-template> </div> ` }) export class ParentComponent implements myinterface { @ViewChild('viewContainerRef', { read: ViewContainerRef }) VCR: ViewContainerRef; //manually indexing the child components for better removal //although there is by-default indexing but it is being avoid for now //so index is a unique property here to identify each component individually. index: number = 0; // to store references of dynamically created components componentsReferences = []; constructor(private CFR: ComponentFactoryResolver) { } createComponent() { let componentFactory = this.CFR.resolveComponentFactory(ChildComponent); let componentRef: ComponentRef<ChildComponent> = this.VCR.createComponent(componentFactory); let currentComponent = componentRef.instance; currentComponent.selfRef = currentComponent; currentComponent.index = ++this.index; // prividing parent Component reference to get access to parent class methods currentComponent.compInteraction = this; // add reference for newly created component this.componentsReferences.push(componentRef); } remove(index: number) { if (this.VCR.length < 1) return; let componentRef = this.componentsReferences.filter(x => x.instance.index == index)[0]; let component: ChildComponent = <ChildComponent>componentRef.instance; let vcrIndex: number = this.VCR.indexOf(componentRef) // removing component from container this.VCR.remove(vcrIndex); this.componentsReferences = this.componentsReferences.filter(x => x.instance.index !== index); } } // Child Component @Component({ selector: 'child', template: ` <div> <h1 (click)="removeMe(index)">I am a Child, click to Remove</h1> </div> ` }) export class ChildComponent { public index: number; public selfRef: ChildComponent; //interface for Parent-Child interaction public compInteraction: myinterface; constructor() { } removeMe(index) { this.compInteraction.remove(index) } } // Interface export interface myinterface { remove(index: number); } If you want to test this just create a file like comp.ts and paste that code in this file and add references to the app.module.ts @NgModule({ declarations: [ ParentComponent, ChildComponent ], imports: [ //if using routing then add like so RouterModule.forRoot([ { path: '', component: ParentComponent }, { path: '**', component: NotFoundComponent } ]), ], entryComponents: [ ChildComponent, ], A: Alternatively if you are using ViewContainerRef to hold the injected component ,you can use the clear() method . this.container.clear(); Github source
stackoverflow
{ "language": "en", "length": 544, "provenance": "stackexchange_0000F.jsonl.gz:874714", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44572420" }
0abc86e9dc73cb0c05455de7e355ed51a20d0874
Stackoverflow Stackexchange Q: Linker error while linking DataFlowSanitizer to LLVM IR I am using pre-built LLVM/Clang 3.8.0 binaries on Ubuntu 16.04.2, 64 bit. I tried to lift a minimal program to LLVM IR, then link the IR to DataFlowSanitizer libraries to produce executable code. In the second step, the process throws a bunch of linker errors. #include <sanitizer/dfsan_interface.h> #include <assert.h> int main(void) { int i = 1; dfsan_label i_label = dfsan_create_label("i", 0); dfsan_set_label(i_label, &i, sizeof(i)); return 0; } clang -c -emit-llvm -fsanitize=dataflow test2.c -o test2.bc clang -fsanitize=dataflow test2.bc -o test2 /usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../x86_64-linux-gnu/Scrt1.o: In function _start':(.text+0x20): undefined reference tomain' /tmp/test2-c642ef.o: In function dfs$main': test2.bc:(.text+0x96): undefined reference todfs$dfsan_create_label' test2.bc:(.text+0xeb): undefined reference to dfs$dfsan_set_label' /tmp/test2-c642ef.o: In functiondfs$dfsw$dfsan_create_label': test2.bc:(.text+0x16e): undefined reference to dfs$dfsan_create_label' /tmp/test2-c642ef.o: In functiondfs$dfsw$dfsan_set_label': test2.bc:(.text+0x1e4): undefined reference to `dfs$dfsan_set_label' clang-3.8: error: linker command failed with exit code 1 (use -v to see invocation) Any idea what might I be doing wrong?
Q: Linker error while linking DataFlowSanitizer to LLVM IR I am using pre-built LLVM/Clang 3.8.0 binaries on Ubuntu 16.04.2, 64 bit. I tried to lift a minimal program to LLVM IR, then link the IR to DataFlowSanitizer libraries to produce executable code. In the second step, the process throws a bunch of linker errors. #include <sanitizer/dfsan_interface.h> #include <assert.h> int main(void) { int i = 1; dfsan_label i_label = dfsan_create_label("i", 0); dfsan_set_label(i_label, &i, sizeof(i)); return 0; } clang -c -emit-llvm -fsanitize=dataflow test2.c -o test2.bc clang -fsanitize=dataflow test2.bc -o test2 /usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../x86_64-linux-gnu/Scrt1.o: In function _start':(.text+0x20): undefined reference tomain' /tmp/test2-c642ef.o: In function dfs$main': test2.bc:(.text+0x96): undefined reference todfs$dfsan_create_label' test2.bc:(.text+0xeb): undefined reference to dfs$dfsan_set_label' /tmp/test2-c642ef.o: In functiondfs$dfsw$dfsan_create_label': test2.bc:(.text+0x16e): undefined reference to dfs$dfsan_create_label' /tmp/test2-c642ef.o: In functiondfs$dfsw$dfsan_set_label': test2.bc:(.text+0x1e4): undefined reference to `dfs$dfsan_set_label' clang-3.8: error: linker command failed with exit code 1 (use -v to see invocation) Any idea what might I be doing wrong?
stackoverflow
{ "language": "en", "length": 146, "provenance": "stackexchange_0000F.jsonl.gz:874717", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44572428" }
2ea229de76f2e2b6c8a22f284d6497bf8079cee6
Stackoverflow Stackexchange Q: Mocked patch of os.listdir not working for unittesting I have a class method that I am trying to test that requires two patched methods, ConfigB.__init__ and listdir: from os import listdir from config.ConfigB import ConfigB class FileRunner(object): def runProcess(self, cfgA) cfgB = ConfigB(cfgA) print(listdir()) I have the following test set up: import unittest import unittest.mock imort MagicMock import mock from FileRunner import FileRunner class TestFileRunner(unittest.TestCase): @mock.patch('ConfigB.ConfigB.__init__') @mock.patch('os.listdir') def test_methodscalled(self, osListDir, cfgB): cfgA = MagicMock() fileRunner = FileRunner() cfgB.return_value = None osListDir.return_value = None fileRunner.runProcess(cfgA) Now the patched mock and return value works for ConfigB.ConfigB, but it does not work for os.listdir. When the print(listdir()) method runs I get a list of file in the current directory, not a value of None as I specified in the patched return value. Any idea what is going wrong? A: You need to patch your relative path to your code. patch('os.listdir') doesn't works because you need to patch this: @mock.patch("path.to.your.pythonfile.listdir") Try with that.
Q: Mocked patch of os.listdir not working for unittesting I have a class method that I am trying to test that requires two patched methods, ConfigB.__init__ and listdir: from os import listdir from config.ConfigB import ConfigB class FileRunner(object): def runProcess(self, cfgA) cfgB = ConfigB(cfgA) print(listdir()) I have the following test set up: import unittest import unittest.mock imort MagicMock import mock from FileRunner import FileRunner class TestFileRunner(unittest.TestCase): @mock.patch('ConfigB.ConfigB.__init__') @mock.patch('os.listdir') def test_methodscalled(self, osListDir, cfgB): cfgA = MagicMock() fileRunner = FileRunner() cfgB.return_value = None osListDir.return_value = None fileRunner.runProcess(cfgA) Now the patched mock and return value works for ConfigB.ConfigB, but it does not work for os.listdir. When the print(listdir()) method runs I get a list of file in the current directory, not a value of None as I specified in the patched return value. Any idea what is going wrong? A: You need to patch your relative path to your code. patch('os.listdir') doesn't works because you need to patch this: @mock.patch("path.to.your.pythonfile.listdir") Try with that.
stackoverflow
{ "language": "en", "length": 160, "provenance": "stackexchange_0000F.jsonl.gz:874734", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44572484" }
980bd3d5582e6ed14a46f4d053a8bfb4de455de7
Stackoverflow Stackexchange Q: How to hide the date for meteor server console.log? Meteor logs the date on the server: I20170615-12:55:31.560(2)? my log message Is there a setting/environment variable to disable the date on the left? A: I believe you should pass --raw-logs as a parameter while running meteor. Eg: meteor --settings settings.json --raw-logs Some information I found about this: * *https://github.com/meteor/meteor/issues/7396 *https://forums.meteor.com/t/meteor-test-raw-logs/26361 As masterAM suggested in the comments: --raw-logs Run without parsing logs from stdout and stderr.
Q: How to hide the date for meteor server console.log? Meteor logs the date on the server: I20170615-12:55:31.560(2)? my log message Is there a setting/environment variable to disable the date on the left? A: I believe you should pass --raw-logs as a parameter while running meteor. Eg: meteor --settings settings.json --raw-logs Some information I found about this: * *https://github.com/meteor/meteor/issues/7396 *https://forums.meteor.com/t/meteor-test-raw-logs/26361 As masterAM suggested in the comments: --raw-logs Run without parsing logs from stdout and stderr.
stackoverflow
{ "language": "en", "length": 75, "provenance": "stackexchange_0000F.jsonl.gz:874763", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44572563" }
d7ef6e90f1a47da8a49a96f32bef1172bc8aff12
Stackoverflow Stackexchange Q: Silent notification vs Background fetch I've already read Apple's documentation on background modes, but I still have some questions. Please correct me if I'm wrong: To enable remote notifications: I only need to do: To enable silent notifications: I need to enable Push notifications like above and also enable remote notifications My questions are: * *Are the above statements correct? *For handling silent notifications, do I ever need to enable background fetch from Xcode Capabilities? Or that has nothing to do with silent notifications and it's only to be used when you want to trigger an interval-based download that isn't triggered from server. A: Answer for 1st question : Yes Correct, You have to enable both options, Background mode - Remote notification and push notifications if you need to listen silent push notification also. Else enable only push notification Answer for 2nd question : Background fetch is not related with push/silent notification. Your app will listen the silent push notification only if you enable the background mode remote notification. Otherwise OS won't allow your app to listen silent push notification.
Q: Silent notification vs Background fetch I've already read Apple's documentation on background modes, but I still have some questions. Please correct me if I'm wrong: To enable remote notifications: I only need to do: To enable silent notifications: I need to enable Push notifications like above and also enable remote notifications My questions are: * *Are the above statements correct? *For handling silent notifications, do I ever need to enable background fetch from Xcode Capabilities? Or that has nothing to do with silent notifications and it's only to be used when you want to trigger an interval-based download that isn't triggered from server. A: Answer for 1st question : Yes Correct, You have to enable both options, Background mode - Remote notification and push notifications if you need to listen silent push notification also. Else enable only push notification Answer for 2nd question : Background fetch is not related with push/silent notification. Your app will listen the silent push notification only if you enable the background mode remote notification. Otherwise OS won't allow your app to listen silent push notification.
stackoverflow
{ "language": "en", "length": 181, "provenance": "stackexchange_0000F.jsonl.gz:874908", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44572975" }
b87b15c822220e7374e535a6425480c896fce4c9
Stackoverflow Stackexchange Q: Airflow: when on_success_callback execute a function with parameters i want to execute a function with one parameter that I pass from a task. Here's my function with state parameter: def sns_notify(state): client = boto3.client('sns') if state == "failed": message = config.get('sns', 'message') + state else: message = config.get('sns', 'message') + state response = client.publish(TargetArn=config.get('sns', 'target_arn'), Message=message, Subject=config.get('sns', 'subject')) return response Here's my tasks with state as param: t1 = DummyOperator(task_id='Dummy-1', trigger_rule=TriggerRule.ALL_SUCCESS, on_success_callback=sns_notify("ok"), dag=dag) t2 = DummyOperator(task_id='Dummy-2', trigger_rule=TriggerRule.ONE_FAILED, on_success_callback=sns_notify("failed"), dag=dag) When i run the dag the function doesn't stop sending mails (for this exemple) A: Every time the DAG is loaded by airflow it will execute sns_notify("ok") because you are calling the function. You need to instead pass just the function pointer sns_notify, which will receive context. See docs: https://airflow.apache.org/code.html trigger_rule relates to how dependencies tasks are executed so is not relevant to on_success_callback. I'm not sure how to pass variables to this callback however - came here looking for answers!
Q: Airflow: when on_success_callback execute a function with parameters i want to execute a function with one parameter that I pass from a task. Here's my function with state parameter: def sns_notify(state): client = boto3.client('sns') if state == "failed": message = config.get('sns', 'message') + state else: message = config.get('sns', 'message') + state response = client.publish(TargetArn=config.get('sns', 'target_arn'), Message=message, Subject=config.get('sns', 'subject')) return response Here's my tasks with state as param: t1 = DummyOperator(task_id='Dummy-1', trigger_rule=TriggerRule.ALL_SUCCESS, on_success_callback=sns_notify("ok"), dag=dag) t2 = DummyOperator(task_id='Dummy-2', trigger_rule=TriggerRule.ONE_FAILED, on_success_callback=sns_notify("failed"), dag=dag) When i run the dag the function doesn't stop sending mails (for this exemple) A: Every time the DAG is loaded by airflow it will execute sns_notify("ok") because you are calling the function. You need to instead pass just the function pointer sns_notify, which will receive context. See docs: https://airflow.apache.org/code.html trigger_rule relates to how dependencies tasks are executed so is not relevant to on_success_callback. I'm not sure how to pass variables to this callback however - came here looking for answers! A: Hoju pointed out the exact error. you can use functional programming to help solve this issue. from functools import partial send_success_notification = partial(sns_notify, "OK") t1 = DummyOperator(task_id='Dummy-1', trigger_rule=TriggerRule.ALL_SUCCESS, on_success_callback=send_success_notification , dag=dag) send_failure_notification = partial(sns_notify, "FAILED") t2 = DummyOperator(task_id='Dummy-2', trigger_rule=TriggerRule.ONE_FAILED, on_success_callback=send_failure_notification, dag=dag)
stackoverflow
{ "language": "en", "length": 203, "provenance": "stackexchange_0000F.jsonl.gz:874921", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44573021" }
7b972247a82b508534e55d248d9b4cdfd43c8b6c
Stackoverflow Stackexchange Q: Angular 4 api call turning response to json returns undefined I am following an example and they're making the call to a local web api like so. return this.http.get("http://localhost:26264/api/news").map((response: Response)=>{ response.json(); }); If you watch the value of response before the .json() call everything looks fine. I am then doing this, var data = this.authService.Login(value.Email, value.Password).subscribe((res: any)=>{ console.log(res); }); At this point the value of res is undefined? Ignore the fact that I am calling a login method for a news controller api. I changed my api endpoint because I was getting other errors prior to this. A: Consider changing: .map((response: Response)=>{ response.json(); }); to .map((response: Response) => response.json()) The reason for this is.. .map(response: Response => response.json() ) says create an anonymous function and take in a response object and return the json method from the response object (which returns the object serialized as JSON) .map((response: Response)=>{ response.json(); }); says create an anonymous function which takes in a response object, and in the scope of this anonymous function, run the json method from the response object, which returns nothing. To fix: .map((response: Response)=>{ return response.json(); });
Q: Angular 4 api call turning response to json returns undefined I am following an example and they're making the call to a local web api like so. return this.http.get("http://localhost:26264/api/news").map((response: Response)=>{ response.json(); }); If you watch the value of response before the .json() call everything looks fine. I am then doing this, var data = this.authService.Login(value.Email, value.Password).subscribe((res: any)=>{ console.log(res); }); At this point the value of res is undefined? Ignore the fact that I am calling a login method for a news controller api. I changed my api endpoint because I was getting other errors prior to this. A: Consider changing: .map((response: Response)=>{ response.json(); }); to .map((response: Response) => response.json()) The reason for this is.. .map(response: Response => response.json() ) says create an anonymous function and take in a response object and return the json method from the response object (which returns the object serialized as JSON) .map((response: Response)=>{ response.json(); }); says create an anonymous function which takes in a response object, and in the scope of this anonymous function, run the json method from the response object, which returns nothing. To fix: .map((response: Response)=>{ return response.json(); }); A: You simply use the syntax incorrectly. return this.http.get("http://localhost:26264/api/news").map((response: Response)=>{ response.json(); }); Have a look at your anonymous function (the function inside map). The function receives an input of type Response, and runs the code inside the curly brackets afterwards. For simplicity, your code is equivalent to: myJsonifyFunc(response: Response) { response.json(); // notice there is no return statement! } return this.http.get("http://localhost:26264/api/news").map(myJsonifyFunc); There are two allowed ways to write anonymous functions as function arguments: .....map((x,y,z) => {...}) receives x,y,z arguments and runs the code inside {...}. To return a value, you should explicitly write "return" inside the curly brackets, otherwise the function would return void (which answers your question about why does it return undefined). .....map((x,y,z) => ...) Notice that this time we omitted the curly brackets. The code replacing ... MUST be a single-statement, and is being returned from the function. .....map((x,y,z) => ...) .....map((x,y,z) => {return ...}) The two lines are equivalent, given that ... is a single statement. Wish the point is clear.
stackoverflow
{ "language": "en", "length": 353, "provenance": "stackexchange_0000F.jsonl.gz:874931", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44573060" }
0923847e15a42b404157b0f1ad026f248b994ef7
Stackoverflow Stackexchange Q: http-proxy-middleware: accessing 127.0.0.1 instead of localhost, causing ECONNREFUSED Using webpack2 to compile on the fly an angular application, I configured devServer this way: proxy: { '/api': { target: 'http://localhost:52163' } } The target of the proxy is a IIS Express server. After upgrading from Visual Studio 2012 to 2017, I now get the error ECONNREFUSED when trying to access /api. I changed http-proxy-middleware to get more information about the error and noticed it tries to connect to 127.0.0.1 instead of localhost. How can I ensure http-proxy-middleware connects to localhost ? Thanks
Q: http-proxy-middleware: accessing 127.0.0.1 instead of localhost, causing ECONNREFUSED Using webpack2 to compile on the fly an angular application, I configured devServer this way: proxy: { '/api': { target: 'http://localhost:52163' } } The target of the proxy is a IIS Express server. After upgrading from Visual Studio 2012 to 2017, I now get the error ECONNREFUSED when trying to access /api. I changed http-proxy-middleware to get more information about the error and noticed it tries to connect to 127.0.0.1 instead of localhost. How can I ensure http-proxy-middleware connects to localhost ? Thanks
stackoverflow
{ "language": "en", "length": 92, "provenance": "stackexchange_0000F.jsonl.gz:874947", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44573116" }
57d7826fa0e033281366c8e296f4c97f7a4c7716
Stackoverflow Stackexchange Q: Android using views' handler to run code I saw that in AOSP there's a lot of code run something like: v.post(new Runnable() { @Override public void run() { // Here comes code x += y; } }); What's the advantage of doing this versus just doing plain x += y;? A: This run will get the call when the view attached to the main user interface thread. have a look the post method in View class. /** * <p>Causes the Runnable to be added to the message queue. * The runnable will be run on the user interface thread.</p> * * @param action The Runnable that will be executed. * * @return Returns true if the Runnable was successfully placed in to the * message queue. Returns false on failure, usually because the * looper processing the message queue is exiting. * * @see #postDelayed * @see #removeCallbacks */ public boolean post(Runnable action) { final AttachInfo attachInfo = mAttachInfo; if (attachInfo != null) { return attachInfo.mHandler.post(action); } // Postpone the runnable until we know on which thread it needs to run. // Assume that the runnable will be successfully placed after attach. getRunQueue().post(action); return true; }
Q: Android using views' handler to run code I saw that in AOSP there's a lot of code run something like: v.post(new Runnable() { @Override public void run() { // Here comes code x += y; } }); What's the advantage of doing this versus just doing plain x += y;? A: This run will get the call when the view attached to the main user interface thread. have a look the post method in View class. /** * <p>Causes the Runnable to be added to the message queue. * The runnable will be run on the user interface thread.</p> * * @param action The Runnable that will be executed. * * @return Returns true if the Runnable was successfully placed in to the * message queue. Returns false on failure, usually because the * looper processing the message queue is exiting. * * @see #postDelayed * @see #removeCallbacks */ public boolean post(Runnable action) { final AttachInfo attachInfo = mAttachInfo; if (attachInfo != null) { return attachInfo.mHandler.post(action); } // Postpone the runnable until we know on which thread it needs to run. // Assume that the runnable will be successfully placed after attach. getRunQueue().post(action); return true; }
stackoverflow
{ "language": "en", "length": 197, "provenance": "stackexchange_0000F.jsonl.gz:874970", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44573188" }
da08d65ee1e210bb011a74004180995c5f2e48f8
Stackoverflow Stackexchange Q: Cannot read property 'string' of undefined | React.PropTypes | LayoutPropTypes.js After deleting and reinstalling my node_modules folder, I'm facing an issue that I don't understand in LayoutPropTypes.js file. In node_modules/react-native/Libraries/StyleSheet/LayoutPropTypes.js The following variable is undefined : var ReactPropTypes = require('React').PropTypes; react-native: 0.45.1 react: 16.0.0-alpha.12 A: React.PropTypes is now deprecated: Note: React.PropTypes is deprecated as of React v15.5. Please use the prop-types library instead. You need to add the prop-types package separately now. The error most likely just started to show up because you deleted your node_modules folder and then reinstalled everything which upgraded your react version.
Q: Cannot read property 'string' of undefined | React.PropTypes | LayoutPropTypes.js After deleting and reinstalling my node_modules folder, I'm facing an issue that I don't understand in LayoutPropTypes.js file. In node_modules/react-native/Libraries/StyleSheet/LayoutPropTypes.js The following variable is undefined : var ReactPropTypes = require('React').PropTypes; react-native: 0.45.1 react: 16.0.0-alpha.12 A: React.PropTypes is now deprecated: Note: React.PropTypes is deprecated as of React v15.5. Please use the prop-types library instead. You need to add the prop-types package separately now. The error most likely just started to show up because you deleted your node_modules folder and then reinstalled everything which upgraded your react version. A: I have the similar problem, no solution. Answers talking about 'prop-types' package are meaningless, the problem is come from react-native source code. That is not an option to manually fix react native source in node_modules folder. A: React is no more shipped with PropTypes. You will need to install it. First install the prop-types package by running npm i prop-types --save. Next use the prop-types package into your component like this: import React from 'react' import PropTypes from 'prop-types' export const AwesomeComponent = props => { return( <h1>Hello {props.name}</h1> ) } AwesomeComponent.propTypes = { name: PropTypes.string.isRequired } Or simply use an interface if you are using Typescript like this: import * as React from 'react' interface IAwesomeComponentProps { name: string } export const AwesomeComponent: React.FC<IAwesomeComponentProps> = props => { return( <h1>Hello {props.name}</h1> ) } A: Are you absolutely sure you are using react 16.0.0-alpha.12? Check your package.json if you have a ^ before the react version, if you have, it probably have installed the latest react version, which currently is 16.0.0-alpha.13, in which it breaks as you say (just had the problem myself). Having the ^ before the version, allows it to install newer minor and patch versions. You can read more about it here. To keep it at the exact version you specify, simply remove the ^ before the version, so that your package.json looks like this: "dependencies": { "react": "16.0.0-alpha.12", "react-native": "0.45.1", } Remember to re-install your node_modules after your changes. A: Now you can update to react-native 0.46.4, just follow along this guide: https://facebook.github.io/react-native/docs/upgrading.html my package.json looks like this: "react": "16.0.0-alpha.12", "react-native": "0.46.4", A: instead of defining the value for component as like this: propName: React.PropTypes.string DEFINE LIKE THIS propName: PropTypes.string and finally save it.
stackoverflow
{ "language": "en", "length": 386, "provenance": "stackexchange_0000F.jsonl.gz:874974", "question_score": "26", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44573199" }
a1b4bd39375abd0c3db6c830ccbc6c9598cc2dfc
Stackoverflow Stackexchange Q: Explicit move constructor needed in container? I have a templated container class: template<class Stuff> class Bag{ private: std::vector<Stuff> mData; }; I want to do void InPlace(Bag<Array>& Left){ Bag<Array> temp; Transform(Left, temp); //fills temp with desirable output Left = std::move(temp); } Suppose Array has user-defined move semantics, but Bag does not. Would mData in this case be moved or copied? A: It would be moved, not copied. I would suggest looking at the following image: This clearly shows that the compiler implicitly generates a move constructor as long as the user doesn't define his/her own : * *destructor *copy constructor *copy assignment *move assignment Since your class has none of these user defined constructors the compiler generated move constructor will be called, that constructor will move mData.
Q: Explicit move constructor needed in container? I have a templated container class: template<class Stuff> class Bag{ private: std::vector<Stuff> mData; }; I want to do void InPlace(Bag<Array>& Left){ Bag<Array> temp; Transform(Left, temp); //fills temp with desirable output Left = std::move(temp); } Suppose Array has user-defined move semantics, but Bag does not. Would mData in this case be moved or copied? A: It would be moved, not copied. I would suggest looking at the following image: This clearly shows that the compiler implicitly generates a move constructor as long as the user doesn't define his/her own : * *destructor *copy constructor *copy assignment *move assignment Since your class has none of these user defined constructors the compiler generated move constructor will be called, that constructor will move mData.
stackoverflow
{ "language": "en", "length": 127, "provenance": "stackexchange_0000F.jsonl.gz:874982", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44573222" }
60ee1dc89e0212818f6deb457ddd120fb1f7e4a0
Stackoverflow Stackexchange Q: airflow experimental api dagrun give 400 error: what should be the input parameter A POST request from postman to http://host:8080/api/experimental/dags/test_flow/dag_runs gives "400 Bad Request: The browser (or proxy) sent a request that this server could not understand." when it try to get_json from from request. ie at line data = request.get_json(force=True) What should be the inputs to this API call ..? A: Had the same issue, solved it by POSTing an empty JSON curl -X POST \ http://localhost:8080/api/experimental/dags/<DAG_ID>/dag_runs \ -H 'Cache-Control: no-cache' \ -H 'Content-Type: application/json' \ -d '{}'
Q: airflow experimental api dagrun give 400 error: what should be the input parameter A POST request from postman to http://host:8080/api/experimental/dags/test_flow/dag_runs gives "400 Bad Request: The browser (or proxy) sent a request that this server could not understand." when it try to get_json from from request. ie at line data = request.get_json(force=True) What should be the inputs to this API call ..? A: Had the same issue, solved it by POSTing an empty JSON curl -X POST \ http://localhost:8080/api/experimental/dags/<DAG_ID>/dag_runs \ -H 'Cache-Control: no-cache' \ -H 'Content-Type: application/json' \ -d '{}' A: Your postman request should be sent like this. -H flag means headers and -d flag means data in a POST request
stackoverflow
{ "language": "en", "length": 112, "provenance": "stackexchange_0000F.jsonl.gz:875005", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44573315" }
6e827f64b1c356d2049298ebd168c3afeb05207f
Stackoverflow Stackexchange Q: BaseInputConnection's commitText method doesn't get called when number clicked I'm trying to implement custom soft keyboard behaviour and met an issue. I overrode onCreateInputConnection() and extended BaseInputConnection class. Now I expect method commitText() gets called when a key is clicked... and it does unless the number key is clicked. The number key goes directly to sendKeyEvent() method. Is there a way to handle numeric keys like any other keys? Thanks. Here is the onCreateInputConnection method implementation. Nothing special. @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { outAttrs.inputType = InputType.TYPE_CLASS_NUMBER; outAttrs.imeOptions = EditorInfo.IME_ACTION_NONE; return new BaseInputConnection(this, true) { @Override public Editable getEditable() { return editable; } @Override public boolean commitText(CharSequence text, int newCursorPosition) { return super.commitText(text, newCursorPosition); } @Override public boolean sendKeyEvent(KeyEvent event) { return super.sendKeyEvent(event); } }; }
Q: BaseInputConnection's commitText method doesn't get called when number clicked I'm trying to implement custom soft keyboard behaviour and met an issue. I overrode onCreateInputConnection() and extended BaseInputConnection class. Now I expect method commitText() gets called when a key is clicked... and it does unless the number key is clicked. The number key goes directly to sendKeyEvent() method. Is there a way to handle numeric keys like any other keys? Thanks. Here is the onCreateInputConnection method implementation. Nothing special. @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { outAttrs.inputType = InputType.TYPE_CLASS_NUMBER; outAttrs.imeOptions = EditorInfo.IME_ACTION_NONE; return new BaseInputConnection(this, true) { @Override public Editable getEditable() { return editable; } @Override public boolean commitText(CharSequence text, int newCursorPosition) { return super.commitText(text, newCursorPosition); } @Override public boolean sendKeyEvent(KeyEvent event) { return super.sendKeyEvent(event); } }; }
stackoverflow
{ "language": "en", "length": 127, "provenance": "stackexchange_0000F.jsonl.gz:875057", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44573506" }
2b6582834eb912a18b81484eb1231382f1a3d537
Stackoverflow Stackexchange Q: Notification error: APN invalid token I stopped receiving the push notifications after the certificate got expired and new certificate has been created. I've updated the p12 certificate on the server. I'm using Pusher application to debug the issue further and I tried importing the p12 certificate with the device token. It says "APN invalid token". Same method works for my other application. Please help me with this I'm not an expert, I tried searching the solution in SO but couldn't find the exact problem. Any tips will also be appreciated. Thanks in advance! A: Check project configuration - it has to be Release not Debug.
Q: Notification error: APN invalid token I stopped receiving the push notifications after the certificate got expired and new certificate has been created. I've updated the p12 certificate on the server. I'm using Pusher application to debug the issue further and I tried importing the p12 certificate with the device token. It says "APN invalid token". Same method works for my other application. Please help me with this I'm not an expert, I tried searching the solution in SO but couldn't find the exact problem. Any tips will also be appreciated. Thanks in advance! A: Check project configuration - it has to be Release not Debug.
stackoverflow
{ "language": "en", "length": 106, "provenance": "stackexchange_0000F.jsonl.gz:875077", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44573570" }
c8dbc8331f056d8d443596e58515ed828c71cb42
Stackoverflow Stackexchange Q: Why do Node modules go into .staging folder? I have an Electron app that I'm trying to install node modules for. When I run npm install, it creates the node_modules folder but all the modules go into a subfolder called .staging. Each module also has -xxxxx appended to it, where the x's are some random alphanumerics. Other Electron apps I've created have never done this. All the node modules sit in the root of node_modules and don't have -xxxxx appended. Any idea why this is happening? A: I was also facing the same issue, I tried the steps below: * *Delete package-lock.json *Delete Node Modules folder *Try installing it using below command (should be in open network) npm install Note: - ".staging" means, those dependencies are getting downloaded so for the temporary basis it keeps all those dependencies under ".staging" folder. Once all gets downloaded properly then it will showcase them under node_modules only. I hope this will work.
Q: Why do Node modules go into .staging folder? I have an Electron app that I'm trying to install node modules for. When I run npm install, it creates the node_modules folder but all the modules go into a subfolder called .staging. Each module also has -xxxxx appended to it, where the x's are some random alphanumerics. Other Electron apps I've created have never done this. All the node modules sit in the root of node_modules and don't have -xxxxx appended. Any idea why this is happening? A: I was also facing the same issue, I tried the steps below: * *Delete package-lock.json *Delete Node Modules folder *Try installing it using below command (should be in open network) npm install Note: - ".staging" means, those dependencies are getting downloaded so for the temporary basis it keeps all those dependencies under ".staging" folder. Once all gets downloaded properly then it will showcase them under node_modules only. I hope this will work. A: If you're automatically installing node_modules using CI/CD you should check out npm ci. Also check out this Stackoverflow question. npm ci The documentation points out the differences between npm install and npm ci. * *The project must have an existing package-lock.json or npm-shrinkwrap.json *If dependencies in the package lock do not match those in package.json, npm ci will exit with an error, instead of updating the package lock. *npm ci can only install entire projects at a time: individual dependencies cannot be added with this command. *If a node_modules is already present, it will be automatically removed before npm ci begins its install. This is nice, because it prevents having to do something like rm -rf node_modules. *It will never write to package.json or any of the package-locks: installs are essentially frozen. A: This only happens temporarily until the modules are downloaded and installed. Node seems to do this so it can place together common submodules from all the modules you are installing so it can better structure the node modules folder(mainly for windows users). If this is happening after an npm install finishes it is likely that there is something wrong with your node installation or something in the install failed. A: .staging is a temporary npm folder, where the modules are temporarily saved while they are being downloaded, if the package.json downloads are still not completed, the created folder remains, until the installation is complete. The problem may be lack of space on your hard drive. A: I was having 2 versions of node installed on my system. nodejs v4.2 and node v8.6 I thought this could be conflicting, so I deleted nodejs v4.2 with following commands. sudo apt-get remove nodejs and linked the path with sudo ln -s /usr/bin/node /usr/bin/nodejs Again I ran npm install and it got fixed A: * *Delete package.lock.json *Delete node_modules *run npm update A: This worked for me I moved the project from C drive to other drive and ran the following commands take a backup of older node modules if you are running this and existing project npm cache clean --force npm update A: I faced similar issue and tried the above answers but it did'nt worked for me; I followed below steps to resolve this issue- 1.npm audit By running npm audit I got list of pending packages to install- 2.npm i packagename After installing one or two package one by one from list, I used 3.npm install At this time the installation went smooth without any lag or hangup. Hope this help who is facing similar issue :). A: Sometimes the cache is corrupt and also unremovable. This fixed the issue I was experiencing. * *If you are using nvm *Get the current node version node --version *nvm uninstall (that version) *nvm install (that version) *nvm use *npm install A: If you have a windows machine where you do not posses Admin rights to it. Try deleting node_modules and install using 'npm install' from command line as 'ADMINISTRATOR' It works! Anyways, it comes down to an open network thing ;)
stackoverflow
{ "language": "en", "length": 672, "provenance": "stackexchange_0000F.jsonl.gz:875087", "question_score": "57", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44573592" }
65731cc04a1be39c89e4b4fd2e3fc670f684979e
Stackoverflow Stackexchange Q: Convert youtube api returned time format to seconds using PHP So the received duration/time format from api is this ; PT1H1M6S how can i convert this into seconds using any php function? A: Here is the best solution I've encountered with Google on how to convert ISO 8601 values to seconds. +1 for no preg function use. Right tool for the job in my opinion. Code credit to RuudBurger - copied from gist: https://gist.github.com/w0rldart/9e10aedd1ee55fc4bc74 /** * Convert ISO 8601 values like P2DT15M33S * to a total value of seconds. * * @param string $ISO8601 */ function ISO8601ToSeconds($ISO8601){ $interval = new \DateInterval($ISO8601); return ($interval->d * 24 * 60 * 60) + ($interval->h * 60 * 60) + ($interval->i * 60) + $interval->s; } echo ISO8601ToSeconds('P20DT15M33S'); // Returns a value of 1728933
Q: Convert youtube api returned time format to seconds using PHP So the received duration/time format from api is this ; PT1H1M6S how can i convert this into seconds using any php function? A: Here is the best solution I've encountered with Google on how to convert ISO 8601 values to seconds. +1 for no preg function use. Right tool for the job in my opinion. Code credit to RuudBurger - copied from gist: https://gist.github.com/w0rldart/9e10aedd1ee55fc4bc74 /** * Convert ISO 8601 values like P2DT15M33S * to a total value of seconds. * * @param string $ISO8601 */ function ISO8601ToSeconds($ISO8601){ $interval = new \DateInterval($ISO8601); return ($interval->d * 24 * 60 * 60) + ($interval->h * 60 * 60) + ($interval->i * 60) + $interval->s; } echo ISO8601ToSeconds('P20DT15M33S'); // Returns a value of 1728933 A: PHP Function to convert ISO8601 Duration To Seconds. <?php function convertISO8601DurationToSeconds($iso8601DurationStr) { $interval = new \DateInterval($iso8601DurationStr); $seconds = $interval->h * 3600 + $interval->i * 60 + $interval->s; return (int) $seconds; } echo convertISO8601DurationToSeconds('PT1H1M6S'); ?> A: This can be done using the RegEx: ^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$ You can then use the various PHP methods for manipulating RegEx to store the time in variables.
stackoverflow
{ "language": "en", "length": 192, "provenance": "stackexchange_0000F.jsonl.gz:875111", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44573677" }
76996ae5eb2b72bd802d72685f9e55ce09971016
Stackoverflow Stackexchange Q: How do you remove the related object from a mongoose document array Company collection: { "_id": { "$oid": "594196a685d5c72f00517f64" }, "name": "company", "reports": [ { "$oid": "5942afb5314f0235d9a3a302" }, { "$oid": "5942b1641b10b236075bcd89" } ], } I understand I have to use update $pull to remove an element from reports. How would create the query to achieve this? I have this so far, var Company = require('../models/company'); Company.update( { _id: company}, { $pull: {'reports': report._id} } ) Is there a way to remove reports from this company automatically if I delete a report? For example, instead of having to use update() on Company after a report is deleted, it would be nice if I can just do remove() on a report and Company should know it was deleted. (I come from a rails background so this is annoying)
Q: How do you remove the related object from a mongoose document array Company collection: { "_id": { "$oid": "594196a685d5c72f00517f64" }, "name": "company", "reports": [ { "$oid": "5942afb5314f0235d9a3a302" }, { "$oid": "5942b1641b10b236075bcd89" } ], } I understand I have to use update $pull to remove an element from reports. How would create the query to achieve this? I have this so far, var Company = require('../models/company'); Company.update( { _id: company}, { $pull: {'reports': report._id} } ) Is there a way to remove reports from this company automatically if I delete a report? For example, instead of having to use update() on Company after a report is deleted, it would be nice if I can just do remove() on a report and Company should know it was deleted. (I come from a rails background so this is annoying)
stackoverflow
{ "language": "en", "length": 137, "provenance": "stackexchange_0000F.jsonl.gz:875127", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44573741" }
76ce682843aa9524462e452e22d8752bc083ae3b
Stackoverflow Stackexchange Q: How to use boto3 to get a list of EBS snapshots owned by me? I have used boto3 in the past to find all images which were not public, so as to decrease my list of returned images from the thousands to a manageable number. However, I can not work out how to filter EBS snapshots in this fashion. I have tried the following ec2.describe_snapshots(OwnerIds=self) However, OwnerIds only takes a list of Ids. I have been reading the following documentation: describe_snapshots, and it states that The results can include the AWS account IDs of the specified owners, amazon for snapshots owned by Amazon, or self for snapshots that you own but I can not work out where this self is meant to go. Can anybody help? Thanks. A: Try: client.describe_snapshots(OwnerIds=['self']) or you can specify your account number/id: client.describe_snapshots(OwnerIds=['123456736123']) Both are equivalent.
Q: How to use boto3 to get a list of EBS snapshots owned by me? I have used boto3 in the past to find all images which were not public, so as to decrease my list of returned images from the thousands to a manageable number. However, I can not work out how to filter EBS snapshots in this fashion. I have tried the following ec2.describe_snapshots(OwnerIds=self) However, OwnerIds only takes a list of Ids. I have been reading the following documentation: describe_snapshots, and it states that The results can include the AWS account IDs of the specified owners, amazon for snapshots owned by Amazon, or self for snapshots that you own but I can not work out where this self is meant to go. Can anybody help? Thanks. A: Try: client.describe_snapshots(OwnerIds=['self']) or you can specify your account number/id: client.describe_snapshots(OwnerIds=['123456736123']) Both are equivalent.
stackoverflow
{ "language": "en", "length": 142, "provenance": "stackexchange_0000F.jsonl.gz:875136", "question_score": "14", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44573768" }
0c2ce7708a872dc4355681d5211a240188c8449a
Stackoverflow Stackexchange Q: Using std::string causes Windows "Entry Point Not Found" When I compile this with G.C.C.: #include <iostream> #include <string> int main() { std::cout << std::string("\r\n"); return 0; } By using the following batch: g++ -Wall main.cc And attempt executing the output (a.exe), then Windows crashes the initialization with this error: If I avoid using std::string in the C++ code it executes normally, even including <string>. Any ideas? Note, first time testing std::string. I run Windows 8 / 64 bits. My compiler includes this file build-info.txt: # ************************************************************************** version : MinGW-W64-builds-4.3.0 user : nixman date : 03.30.2017- 1:01:08 PM args : --mode=gcc-6.3.0 --buildroot=/c/mingw630 --jobs=2 --rev=2 --threads=win32 --exceptions=sjlj --arch=i686 --bin-compress [much more here...] # ************************************************************************** Also note that I'm used to disable and uninstall all possible anti-virus utilities (e.g., Windows Defender). A: It was hard to find a solution (zZZzzZzZzZz), but finally, it's on this answer. g++ -Wall -D_GLIBCXX_USE_CXX11_ABI=0 main.cc
Q: Using std::string causes Windows "Entry Point Not Found" When I compile this with G.C.C.: #include <iostream> #include <string> int main() { std::cout << std::string("\r\n"); return 0; } By using the following batch: g++ -Wall main.cc And attempt executing the output (a.exe), then Windows crashes the initialization with this error: If I avoid using std::string in the C++ code it executes normally, even including <string>. Any ideas? Note, first time testing std::string. I run Windows 8 / 64 bits. My compiler includes this file build-info.txt: # ************************************************************************** version : MinGW-W64-builds-4.3.0 user : nixman date : 03.30.2017- 1:01:08 PM args : --mode=gcc-6.3.0 --buildroot=/c/mingw630 --jobs=2 --rev=2 --threads=win32 --exceptions=sjlj --arch=i686 --bin-compress [much more here...] # ************************************************************************** Also note that I'm used to disable and uninstall all possible anti-virus utilities (e.g., Windows Defender). A: It was hard to find a solution (zZZzzZzZzZz), but finally, it's on this answer. g++ -Wall -D_GLIBCXX_USE_CXX11_ABI=0 main.cc
stackoverflow
{ "language": "en", "length": 148, "provenance": "stackexchange_0000F.jsonl.gz:875150", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44573802" }
d7de47be4f80ad57ab2467556f1bdb151b6af55a
Stackoverflow Stackexchange Q: A loop to create the alphabet using JavaScript I've been working on a small project for myself, and it consists of creating the alphabet. I don't want to hard code each individual letter in markup, but rather use JavaScript to do it for me. This is how far I've gotten. for ( i = 0; i < 26; i++ ) { var li = document.createElement("li"); li.innerHTML = "letter" + i + " "; li.style.listStyle = "none"; li.style.display = "inline"; document.getElementById("letter-main").appendChild(li); } That being said, I'm trying to avoid using jQuery for the time, as I am trying to gain a better understanding of JavaScript. There's another post that goes over the same Idea, using character codes but with jQuery. How would I go about this? A: Answer from Convert integer into its character equivalent in Javascript: Assuming you want lower case letters: var chr = String.fromCharCode(97 + n); // where n is 0, 1, 2 ... 97 is the ASCII code for lower case 'a'. If you want uppercase letters, replace 97 with 65 (uppercase 'A'). Note that if n > 25, you will get out of the range of letters.
Q: A loop to create the alphabet using JavaScript I've been working on a small project for myself, and it consists of creating the alphabet. I don't want to hard code each individual letter in markup, but rather use JavaScript to do it for me. This is how far I've gotten. for ( i = 0; i < 26; i++ ) { var li = document.createElement("li"); li.innerHTML = "letter" + i + " "; li.style.listStyle = "none"; li.style.display = "inline"; document.getElementById("letter-main").appendChild(li); } That being said, I'm trying to avoid using jQuery for the time, as I am trying to gain a better understanding of JavaScript. There's another post that goes over the same Idea, using character codes but with jQuery. How would I go about this? A: Answer from Convert integer into its character equivalent in Javascript: Assuming you want lower case letters: var chr = String.fromCharCode(97 + n); // where n is 0, 1, 2 ... 97 is the ASCII code for lower case 'a'. If you want uppercase letters, replace 97 with 65 (uppercase 'A'). Note that if n > 25, you will get out of the range of letters. A: You can use toString() to convert a number to alpha for (i = 0; i < 26; i++) { var li = document.createElement("li"); li.innerHTML = "letter " + (i+10).toString(36) + " "; li.style.listStyle = "none"; li.style.display = "inline"; document.getElementById("letter-main").appendChild(li); } <div id="letter-main"></div>
stackoverflow
{ "language": "en", "length": 235, "provenance": "stackexchange_0000F.jsonl.gz:875170", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44573859" }
67e2f2853e032c38e3fdeac6f481bcb7d91488b6
Stackoverflow Stackexchange Q: Pubsubhubbub - Transient error with every Topic URL We subscribed to YouTube's Pubsubhubbub to get notified if someone published a video on a channel. If we try to look at our Subscription details or the Topic url details through https://pubsubhubbub.appspot.com/ everything shows a "Transient Error" and the Server returns a 503 Error. And it seems to error with every Topic-Url i try. Our Topic Url if it's opened in a browser, however, shows content, so it seems to be right. (https://www.youtube.com/feeds/videos.xml?channel_id=UCyjzn-6YZur2M-qVwTzbQGA) It worked for a few weeks and yesterday we tried to subscribe to another channel und now this error is everywhere. Even our old subscribe won't get any push notifications anymore and the old topic url returns an error, too. Anyone knows where the problem could be? Or has the same problem?
Q: Pubsubhubbub - Transient error with every Topic URL We subscribed to YouTube's Pubsubhubbub to get notified if someone published a video on a channel. If we try to look at our Subscription details or the Topic url details through https://pubsubhubbub.appspot.com/ everything shows a "Transient Error" and the Server returns a 503 Error. And it seems to error with every Topic-Url i try. Our Topic Url if it's opened in a browser, however, shows content, so it seems to be right. (https://www.youtube.com/feeds/videos.xml?channel_id=UCyjzn-6YZur2M-qVwTzbQGA) It worked for a few weeks and yesterday we tried to subscribe to another channel und now this error is everywhere. Even our old subscribe won't get any push notifications anymore and the old topic url returns an error, too. Anyone knows where the problem could be? Or has the same problem?
stackoverflow
{ "language": "en", "length": 134, "provenance": "stackexchange_0000F.jsonl.gz:875239", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574048" }
f9873f99dfca709aa44c31aba90272295efaca92
Stackoverflow Stackexchange Q: Firebase Functions error: .once is not a function I am trying to deploy a simple function to Firebase, but I am having some difficulties. Every time I try to use .once on a reference Firebase tells me that it is not a function. Here is my code exports.testFunction = functions.database.ref('/Rooms/{firstID}/{pushId}/On').onWrite(event => { const value = event.data.val(); var ref = functions.database.ref(roomNum); return ref.once('value').then(snapshot => { console.log(snapshot.numChildren); return true; }); }); I have also tried the following: firebaseRef.once('value', function(dataSnapshot) { console.log(snapshot.numChildren); }); Nothing seems to work. Does anyone know of a fix or a different way of getting the number of children from a ref/snapshot? Thank you. A: functions.database.ref is a different object than the one you're used to using on the client. It's sole purpose is to listen for writes using it's only function, onWrite. You can obtain your intended ref thru the event parameter. var ref = event.data.ref This is a reference to the path you specified in onWrite. If you want the root reference: var rootRef = event.data.ref.root Further reading: https://firebase.google.com/docs/reference/functions/functions.database
Q: Firebase Functions error: .once is not a function I am trying to deploy a simple function to Firebase, but I am having some difficulties. Every time I try to use .once on a reference Firebase tells me that it is not a function. Here is my code exports.testFunction = functions.database.ref('/Rooms/{firstID}/{pushId}/On').onWrite(event => { const value = event.data.val(); var ref = functions.database.ref(roomNum); return ref.once('value').then(snapshot => { console.log(snapshot.numChildren); return true; }); }); I have also tried the following: firebaseRef.once('value', function(dataSnapshot) { console.log(snapshot.numChildren); }); Nothing seems to work. Does anyone know of a fix or a different way of getting the number of children from a ref/snapshot? Thank you. A: functions.database.ref is a different object than the one you're used to using on the client. It's sole purpose is to listen for writes using it's only function, onWrite. You can obtain your intended ref thru the event parameter. var ref = event.data.ref This is a reference to the path you specified in onWrite. If you want the root reference: var rootRef = event.data.ref.root Further reading: https://firebase.google.com/docs/reference/functions/functions.database
stackoverflow
{ "language": "en", "length": 173, "provenance": "stackexchange_0000F.jsonl.gz:875273", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574157" }
c05ae91359a243505976fee91d47a09edf0b32cf
Stackoverflow Stackexchange Q: GuestAdditions versions on your host (5.1.16) and guest (4.3.36) do not match I am trying to add more than 1 VM instance through Vagrant 1.9.2 and Oracle Virtualbox. Getting "mounting" problem followed by the error - GuestAdditions versions on your host (5.1.16) and guest (4.3.36) do not match.
Q: GuestAdditions versions on your host (5.1.16) and guest (4.3.36) do not match I am trying to add more than 1 VM instance through Vagrant 1.9.2 and Oracle Virtualbox. Getting "mounting" problem followed by the error - GuestAdditions versions on your host (5.1.16) and guest (4.3.36) do not match.
stackoverflow
{ "language": "en", "length": 49, "provenance": "stackexchange_0000F.jsonl.gz:875287", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574203" }
92136cf2162a39745f9d0d3853f56787a47ec175
Stackoverflow Stackexchange Q: Which web browsers send ping/pong requests in their websocket connections? I wrote a websocket server but neglected to implement the PING/PONG command. It worked, however I noticed in my logs the server occasionally crashed because one or more clients had sent a PING/PONG request. Is there a list of web browsers that send PING/PONG requests on their websocket connections?
Q: Which web browsers send ping/pong requests in their websocket connections? I wrote a websocket server but neglected to implement the PING/PONG command. It worked, however I noticed in my logs the server occasionally crashed because one or more clients had sent a PING/PONG request. Is there a list of web browsers that send PING/PONG requests on their websocket connections?
stackoverflow
{ "language": "en", "length": 60, "provenance": "stackexchange_0000F.jsonl.gz:875304", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574232" }
0c922e9c174f877dc1be392c0b3203f7a52c569f
Stackoverflow Stackexchange Q: passing multiple arguments or object in (click) Problem is to pass the object or multiple arguments from template to component and use them to add data to API. task.service.ts addTasks(task: Task): Observable<Task>{ let headers = new Headers({'Content-type': 'application/json'}); let options = new RequestOptions({ headers: headers }); return this.http.post(this.tasksUrl, {task}, options) .map(this.extractData) .catch(this.handleError); } task.component.ts addTasks(task){ this.taskService.addTasks(task) .subscribe( task => this.tasks.push(task), error => this.errorMessage = <any> error ); } Template Inputs: <input #todoTime type="text" class="form-control">&nbsp; <input #todoName type="text" class="form-control"> Template Button: <button name="todoAdd" (click)="addTasks({name: todoName.value, time: todoTime.value}); todoName.value='',todoTime.value='' ">add</button> A: Replace the comman(,) with a semicolon when you are handling the click event for the button. That should work. <button name="todoAdd" (click)="addTasks({name: todoName.value, time: todoTime.value}); todoName.value=''; todoTime.value='' ">add</button> I have created this simple Plnkr that shows object is getting passed to addTasks() function.
Q: passing multiple arguments or object in (click) Problem is to pass the object or multiple arguments from template to component and use them to add data to API. task.service.ts addTasks(task: Task): Observable<Task>{ let headers = new Headers({'Content-type': 'application/json'}); let options = new RequestOptions({ headers: headers }); return this.http.post(this.tasksUrl, {task}, options) .map(this.extractData) .catch(this.handleError); } task.component.ts addTasks(task){ this.taskService.addTasks(task) .subscribe( task => this.tasks.push(task), error => this.errorMessage = <any> error ); } Template Inputs: <input #todoTime type="text" class="form-control">&nbsp; <input #todoName type="text" class="form-control"> Template Button: <button name="todoAdd" (click)="addTasks({name: todoName.value, time: todoTime.value}); todoName.value='',todoTime.value='' ">add</button> A: Replace the comman(,) with a semicolon when you are handling the click event for the button. That should work. <button name="todoAdd" (click)="addTasks({name: todoName.value, time: todoTime.value}); todoName.value=''; todoTime.value='' ">add</button> I have created this simple Plnkr that shows object is getting passed to addTasks() function.
stackoverflow
{ "language": "en", "length": 133, "provenance": "stackexchange_0000F.jsonl.gz:875308", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574243" }
3ada6ac836d3cca4ef824dbc2ff393dacd3688c3
Stackoverflow Stackexchange Q: create-react-app: how to use https instead of http? I was wondering if anyone knows how to use https on dev for the 'create-react-app' environment. I can't see anything about that in the README or quick googling. I just want either the https://localhost:3000 to work, or else https://localhost:3001. A: I think it is worth to mention to set PORT=443, default HTTPS standard port. You can avoid to attach :PORT at the end of the address when browsing every time. su export HTTPS=true export PORT=443 export SSL_CRT_FILE=/PATH/TO/cert.pem # recommended export SSL_KEY_FILE=/PATH/TO/privkey.pem # recommended npm start Or you can put them all in to package.json: "scripts": { "start": "HTTPS=true PORT=443 react-scripts start", Then, without exporting: su npm start
Q: create-react-app: how to use https instead of http? I was wondering if anyone knows how to use https on dev for the 'create-react-app' environment. I can't see anything about that in the README or quick googling. I just want either the https://localhost:3000 to work, or else https://localhost:3001. A: I think it is worth to mention to set PORT=443, default HTTPS standard port. You can avoid to attach :PORT at the end of the address when browsing every time. su export HTTPS=true export PORT=443 export SSL_CRT_FILE=/PATH/TO/cert.pem # recommended export SSL_KEY_FILE=/PATH/TO/privkey.pem # recommended npm start Or you can put them all in to package.json: "scripts": { "start": "HTTPS=true PORT=443 react-scripts start", Then, without exporting: su npm start A: "scripts": { "start": "set HTTPS=true&&set PORT=443&&react-scripts start", ........ } In case you need to change the port and set it to https. A: Add to file .env (or .env.local) line: HTTPS=true A: Please use this in command prompt set HTTPS=true&&npm start A: You can edit your package.json scripts section to read: "scripts": { "start": "set HTTPS=true&&react-scripts start", ... } or just run set HTTPS=true&&npm start Just a sidenote, for me, making this change breaks hot reloading for some reason.... -- Note: OS === Windows 10 64-Bit A: You can also create a file called .env in the root of your project, then write HTTPS=true After that, just run "npm start" as you usually do to start your app. Docs: https://facebook.github.io/create-react-app/docs/advanced-configuration Works both on Linux and Windows, unlike some other answers posted here. A: might need to Install self-signed CA chain on both server and browser. Difference between self-signed CA and self-signed certificate A: if it's still not working properly because of "your connection is not private" issues (in chrome), this worked for me just fine: https://github.com/facebook/create-react-app/issues/3441 In short: * *First I exported certificate from chrome (view this). *Imported the certificate into Windows (using certmgr.msc). *Allowed chrome://flags/#allow-insecure-localhost flag. How to allow insecure localhost A: You can create a proxy.HTTPS->HTTP Create a key and cert. openssl req -nodes -new -x509 -keyout server.key -out server.cert Create a file named proxyServer.js var httpProxy = require('http-proxy'); let fs = require('fs'); httpProxy.createServer({ target: { host: 'localhost', port: 3000 }, ssl: { key: fs.readFileSync('server.key', 'utf8'), cert: fs.readFileSync('server.cert', 'utf8') } }).listen(3000); From the terminal run node proxyServer.js A: I`m using Windows 10 and I had the same issue. I realized that you need to: * *Run Command Prompt with Administrator Privileges *Run on the terminal bash this command: set HTTPS=true&&npm start *You can also put this code into your package.json file under the scripts section like this: "scripts": { "start": "set HTTPS=true&&react-scripts start", (...) } *Bonus: If you want to change the PORT use this command insted: set HTTPS=true&&set PORT=443&&react-scripts start Obs.: Pay attention to the blank spaces NOT left in between some characters. You can browse this link for more detais. A: Edit your package.json file and change the starting scripts for starting your secures domain. for example https { "name": "social-login", "version": "0.1.0", "private": true, "dependencies": { "react": "^16.4.1", "react-dom": "^16.4.1", "react-facebook-login": "^4.0.1", "react-google-login": "^3.2.1", "react-scripts": "1.1.4" }, "scripts": { // update this line "start": "HTTPS=true react-scripts start", "start": "set HTTPS=true&&react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" } } thanks A: Windows (cmd.exe) set HTTPS=true&&npm start (Note: the lack of whitespace is intentional.) Windows (Powershell) ($env:HTTPS = "true") -and (npm start) Linux, macOS (Bash) HTTPS=true npm start Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. Custom SSL certificate HTTPS=true SSL_CRT_FILE=<SSLCert.crt> SSL_KEY_FILE=<SSLCert.key> npm start Linux, macOS (Bash) HTTPS=true SSL_CRT_FILE=<SSLCert.crt> SSL_KEY_FILE=<SSLCert.key> npm start To avoid doing it each time: You can include in the npm start script like so: { "start": "HTTPS=true react-scripts start" } Or you can create a .env file with HTTPS=true A: In Windows environment add following lines to package.json: "scripts": { "start-dev": "set HTTPS=true&&set PORT=443&&react-scripts start" }, It will start development server with https and port 443. At the present moment NodeJs have known bug to run this correctly but it worked with nodeJs v8.11.3 - https://nodejs.org/dist/v8.11.3/node-v8.11.3-x64.msi for me. A: For Windows, try this one ($env:HTTPS = "true") -and (npm start) I am using VS Code Terminal (powershell). A: In Case of MAC/UNIX do export HTTPS=true npm start Or simple one liner export HTTPS=true&&npm start Or update start script in package.json to "start": "export HTTPS=true&&PORT=3000 react-scripts start", you should be able to hit https. A: set HTTPS=true&&react-scripts start in scripts > start: of package.json as shown below. "scripts" in package.json: "scripts": { "start": "set HTTPS=true&&react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, * *Please don't leave any space in between the commands i.e, HTTPS=true && npm start won't work. Refer it in official doc. Using HTTPS in Development (Note: the lack of whitespace is intentional.) A: Set HTTPS=true before you run the start command. Documentation The implementation uses the HTTPS Environment Variable to determine which protocol to use when starting the server. A: I could not get that to work (setting HTTPS=true), instead, i used react-https-redirect A simple wrapper around your App component. A: I am using Windows 10 latest build with Windows Insider Program till this date. It seems like there are three cases while using Windows 10: * *Windows 10 with CMD command line for your NPM set HTTPS=true&&npm start *Windows 10 with PowerShell command line for your NPM set HTTPS=true&&npm start *Windows 10 with Linux Bash command line for your NPM ( My Case was this ) HTTPS=true npm start Documentation: Create react app dev A: To avoid untrusted certificate errors in Chrome and Safari you should manually specify a self-signed key pair. CRA allows you to specify them. Also, use .env file to store these vars. On macOS, just add your certificate to Keychain Access and then set Trust Always in its details. A: Important point about this issue: if you are looking to use https on LAN (rather than localhost) then SSL certification is an issue because the IP is not static! This is a nice read on the subject where they explore the option of doing it anyway: SSL For Devices in Local Networks A: Open the package.json file and change the start script file like given below. "start": "react-scripts start", to "start": "HTTPS=true react-scripts start", Restart your localhost and check the terminal you are probably able to see the local and on your network runs by HTTPS. A: HTTPS=true npm start in the terminal worked for me on Create-React-App A: // add this line to android manifest to use http when releasing apk in react native <application android:usesCleartextTraffic="true">
stackoverflow
{ "language": "en", "length": 1102, "provenance": "stackexchange_0000F.jsonl.gz:875358", "question_score": "119", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574399" }
68aaaac4a309ebda6f33cddf249dfe4a7c6c8c79
Stackoverflow Stackexchange Q: Retrofit 2 + RxJava cancel/unsubscribe I am performing a network request where I send files and a message. I would like to have an option to cancel current request. I have found two similar questions and both suggests that observable.subscribe(Observer) returns Subscription object which has method unsubscribe(). Here is the first one And the second one In my case, I use observable.subscribe(Observer) which is void. Here is my code: Observable<MessengerRaw> observable = mModel.sendMessage(message, companion, description, multiParts); observable.subscribe(new Observer<MessengerRaw>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(MessengerRaw value) { if (getView() != null) { ((MessengerActivity) getView()).resetMessegeView(); ((MessengerActivity) getView()).updateMessageList(); } } @Override public void onError(Throwable e) { getData().remove(0); if (getView() != null) { ((MessengerActivity) getView()).updateMessageList(); } } @Override public void onComplete() { hideProgress(); } }); So how do I unsubscribe/cancel my request? Thank you. A: In RXJava You must use subscriptions for unsubscribe private Subscription mSubscription; /.../ Observable<MessengerRaw> observable = mModel.sendMessage(message, companion, description, multiParts); Subscription subscription = observable.subscribe(new Observer<MessengerRaw>() {/.../}); When you want to unsubscribe you can call if(!subscription.isUnsubscribed()){ subscription.unsubscribe(); } In RXJava 2 observable.subscribe(new Observer<MessengerRaw>() {/.../}); returns Disposable object, you can call dispose();
Q: Retrofit 2 + RxJava cancel/unsubscribe I am performing a network request where I send files and a message. I would like to have an option to cancel current request. I have found two similar questions and both suggests that observable.subscribe(Observer) returns Subscription object which has method unsubscribe(). Here is the first one And the second one In my case, I use observable.subscribe(Observer) which is void. Here is my code: Observable<MessengerRaw> observable = mModel.sendMessage(message, companion, description, multiParts); observable.subscribe(new Observer<MessengerRaw>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(MessengerRaw value) { if (getView() != null) { ((MessengerActivity) getView()).resetMessegeView(); ((MessengerActivity) getView()).updateMessageList(); } } @Override public void onError(Throwable e) { getData().remove(0); if (getView() != null) { ((MessengerActivity) getView()).updateMessageList(); } } @Override public void onComplete() { hideProgress(); } }); So how do I unsubscribe/cancel my request? Thank you. A: In RXJava You must use subscriptions for unsubscribe private Subscription mSubscription; /.../ Observable<MessengerRaw> observable = mModel.sendMessage(message, companion, description, multiParts); Subscription subscription = observable.subscribe(new Observer<MessengerRaw>() {/.../}); When you want to unsubscribe you can call if(!subscription.isUnsubscribed()){ subscription.unsubscribe(); } In RXJava 2 observable.subscribe(new Observer<MessengerRaw>() {/.../}); returns Disposable object, you can call dispose(); A: In RxJava2, you can get Disposable object in onSubscribe callback method of oserver, which you can use to dispose subscription.
stackoverflow
{ "language": "en", "length": 208, "provenance": "stackexchange_0000F.jsonl.gz:875368", "question_score": "19", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574428" }
df3d75963c7358025e98906412bd64ebc3237799
Stackoverflow Stackexchange Q: Querying by current time (postgres, psycopg2, python) I'm making a Flask application that queries a postgreSQL database using psycopg2. The database has a column timestamps in the format YYYY-MM-DD HH:MI:SS. I want to print ONLY the results that match the current time up to the minute (the moment I query the db). I think what I'm looking for is a dynamic query. For example, here I want to print the number of users CURRENTLY active. def userCount(conn): cur = conn.cursor() cur.execute("SELECT * from user_list WHERE timestamps = ?") print 'Users currently active: ' + str(len(cur.fetchall())) I've tried placing several different things where the question mark is above, including a variable dt defined using python's datetime module. Nothing has worked--I either end up getting a count of all the users in the database, or an error that the column does not exist. To reiterate, I know how to specify date-time parameters but what I need is the CURRENT date-time. What's the proper way to do this? A: intervalInSecs = 30; def userCount(conn): cur = conn.cursor() cur.execute("SELECT * from user_list WHERE timestamps > (current_timestamp - make_interval(secs := %s))", [intervalInSecs]) print 'Users currently active: ' + str(len(cur.fetchall()))
Q: Querying by current time (postgres, psycopg2, python) I'm making a Flask application that queries a postgreSQL database using psycopg2. The database has a column timestamps in the format YYYY-MM-DD HH:MI:SS. I want to print ONLY the results that match the current time up to the minute (the moment I query the db). I think what I'm looking for is a dynamic query. For example, here I want to print the number of users CURRENTLY active. def userCount(conn): cur = conn.cursor() cur.execute("SELECT * from user_list WHERE timestamps = ?") print 'Users currently active: ' + str(len(cur.fetchall())) I've tried placing several different things where the question mark is above, including a variable dt defined using python's datetime module. Nothing has worked--I either end up getting a count of all the users in the database, or an error that the column does not exist. To reiterate, I know how to specify date-time parameters but what I need is the CURRENT date-time. What's the proper way to do this? A: intervalInSecs = 30; def userCount(conn): cur = conn.cursor() cur.execute("SELECT * from user_list WHERE timestamps > (current_timestamp - make_interval(secs := %s))", [intervalInSecs]) print 'Users currently active: ' + str(len(cur.fetchall())) A: Can you use the database date? WHERE timestamps = current_date Or, if the value is stored as a string: WHERE timestamps = TO_CHAR(current_date, 'YYYY-MM-DD')
stackoverflow
{ "language": "en", "length": 220, "provenance": "stackexchange_0000F.jsonl.gz:875380", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574471" }
48caa46c5573b34e90628a305cd2749e1cf5e699
Stackoverflow Stackexchange Q: Filling in a Bezier Curve SVG acknowledgement: reference [SVG] How to close the path (between the 1st and the last point) and fill the area accordingly: It's not a single path, so i can't close it with 'Z' at the end A: It's not a single path, so I can't close it with 'Z' at the end Join the paths first. E.g. the sample from your link is originally <path xmlns="http://www.w3.org/2000/svg" fill="none" stroke="blue" stroke-width="8" d="M 60 60 C 111.55555555555557 160 163.11111111111114 260 220 300"/> <path xmlns="http://www.w3.org/2000/svg" fill="none" stroke="red" stroke-width="8" d="M 220 300 C 276.88888888888886 340 339.11111111111114 320 420 300"/> But if you append the dstring of the second to the first and replace the second M (Move) with L (LineTo), you get this: <path xmlns="http://www.w3.org/2000/svg" fill="cyan" stroke="red" stroke-width="8" d="M 60 60 C 111.55555555555557 160 163.11111111111114 260 220 300 L 220 300 C 276.88888888888886 340 339.11111111111114 320 420 300 Z"/> I have also set fill=cyan. Some of these drawn things are from the linked site and not in the code in my answer.
Q: Filling in a Bezier Curve SVG acknowledgement: reference [SVG] How to close the path (between the 1st and the last point) and fill the area accordingly: It's not a single path, so i can't close it with 'Z' at the end A: It's not a single path, so I can't close it with 'Z' at the end Join the paths first. E.g. the sample from your link is originally <path xmlns="http://www.w3.org/2000/svg" fill="none" stroke="blue" stroke-width="8" d="M 60 60 C 111.55555555555557 160 163.11111111111114 260 220 300"/> <path xmlns="http://www.w3.org/2000/svg" fill="none" stroke="red" stroke-width="8" d="M 220 300 C 276.88888888888886 340 339.11111111111114 320 420 300"/> But if you append the dstring of the second to the first and replace the second M (Move) with L (LineTo), you get this: <path xmlns="http://www.w3.org/2000/svg" fill="cyan" stroke="red" stroke-width="8" d="M 60 60 C 111.55555555555557 160 163.11111111111114 260 220 300 L 220 300 C 276.88888888888886 340 339.11111111111114 320 420 300 Z"/> I have also set fill=cyan. Some of these drawn things are from the linked site and not in the code in my answer.
stackoverflow
{ "language": "en", "length": 173, "provenance": "stackexchange_0000F.jsonl.gz:875391", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574508" }
f66c41e008135fd8006cab74a852531936ec82a0
Stackoverflow Stackexchange Q: Referential and structural equality in Kotlin What is the difference between referential equality and structural equality in Kotlin? val a = File("/myfile.txt") val b = File("/myfile.txt") val sameRef = a === b and: val a = File("/myfile.txt") val b = File("/myfile.txt") val both= a == b A: * *Referential equality === (also called identity) means that the pointers for two objects are the same. That is to say the objects are contained in the same memory location which leads us to the fact that pointers reference to the same object. identity: determines whether two objects share the same memory address *Structural equality ==, in its turn, means that two objects have equivalent content. You should specify when two objects should be considered equal by overriding the equals() method. equality: determines if two object contain the same state. As well as in Java, in Kotlin there're no specific equals() and hashCode() generated by default (not considering data classes). Thus, until you've overriden these methods for your class, both == and === perform identity comparison.
Q: Referential and structural equality in Kotlin What is the difference between referential equality and structural equality in Kotlin? val a = File("/myfile.txt") val b = File("/myfile.txt") val sameRef = a === b and: val a = File("/myfile.txt") val b = File("/myfile.txt") val both= a == b A: * *Referential equality === (also called identity) means that the pointers for two objects are the same. That is to say the objects are contained in the same memory location which leads us to the fact that pointers reference to the same object. identity: determines whether two objects share the same memory address *Structural equality ==, in its turn, means that two objects have equivalent content. You should specify when two objects should be considered equal by overriding the equals() method. equality: determines if two object contain the same state. As well as in Java, in Kotlin there're no specific equals() and hashCode() generated by default (not considering data classes). Thus, until you've overriden these methods for your class, both == and === perform identity comparison.
stackoverflow
{ "language": "en", "length": 174, "provenance": "stackexchange_0000F.jsonl.gz:875399", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574526" }
df85e5957d81b1b23e1465002e340566df9293a6
Stackoverflow Stackexchange Q: Boto3 S3, sort bucket by last modified I need to fetch a list of items from S3 using Boto3, but instead of returning default sort order (descending) I want it to return it via reverse order. I know you can do it via awscli: aws s3api list-objects --bucket mybucketfoo --query "reverse(sort_by(Contents,&LastModified))" and its doable via the UI console (not sure if this is done client side or server side) I cant seem to see how to do this in Boto3. I am currently fetching all the files, and then sorting...but that seems overkill, especially if I only care about the 10 or so most recent files. The filter system seems to only accept the Prefix for s3, nothing else. A: I did a small variation of what @helloV posted below. its not 100% optimum, but it gets the job done with the limitations boto3 has as of this time. s3 = boto3.resource('s3') my_bucket = s3.Bucket('myBucket') unsorted = [] for file in my_bucket.objects.filter(): unsorted.append(file) files = [obj.key for obj in sorted(unsorted, key=get_last_modified, reverse=True)][0:9]
Q: Boto3 S3, sort bucket by last modified I need to fetch a list of items from S3 using Boto3, but instead of returning default sort order (descending) I want it to return it via reverse order. I know you can do it via awscli: aws s3api list-objects --bucket mybucketfoo --query "reverse(sort_by(Contents,&LastModified))" and its doable via the UI console (not sure if this is done client side or server side) I cant seem to see how to do this in Boto3. I am currently fetching all the files, and then sorting...but that seems overkill, especially if I only care about the 10 or so most recent files. The filter system seems to only accept the Prefix for s3, nothing else. A: I did a small variation of what @helloV posted below. its not 100% optimum, but it gets the job done with the limitations boto3 has as of this time. s3 = boto3.resource('s3') my_bucket = s3.Bucket('myBucket') unsorted = [] for file in my_bucket.objects.filter(): unsorted.append(file) files = [obj.key for obj in sorted(unsorted, key=get_last_modified, reverse=True)][0:9] A: it seems that is no way to do the sort by using boto3. According to the documentation, boto3 only supports these methods for Collections: all(), filter(**kwargs), page_size(**kwargs), limit(**kwargs) Hope this help in some way. https://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.ServiceResource.buckets A: If there are not many objects in the bucket, you can use Python to sort it to your needs. Define a lambda to get the last modified time: get_last_modified = lambda obj: int(obj['LastModified'].strftime('%s')) Get all objects and sort them by last modified time. s3 = boto3.client('s3') objs = s3.list_objects_v2(Bucket='my_bucket')['Contents'] [obj['Key'] for obj in sorted(objs, key=get_last_modified)] If you want to reverse the sort: [obj['Key'] for obj in sorted(objs, key=get_last_modified, reverse=True)] A: A simpler approach, using the python3 sorted() function: import boto3 s3 = boto3.resource('s3') myBucket = s3.Bucket('name') def obj_last_modified(myobj): return myobj.last_modified sortedObjects = sorted(myBucket.objects.all(), key=obj_last_modified, reverse=True) you now have a reverse sorted list, sorted by the 'last_modified' attribute of each Object. A: To get the last modified files in a folder in S3: import boto3 s3 = boto3.resource('s3') my_bucket = s3.Bucket('bucket_name') files = my_bucket.objects.filter(Prefix='folder_name/subfolder_name/') files = [obj.key for obj in sorted(files, key=lambda x: x.last_modified, reverse=True)][0:2] print(files) To get the two files which are last modified: files = [obj.key for obj in sorted(files, key=lambda x: x.last_modified, reverse=True)][0:2] A: s3 = boto3.client('s3') get_last_modified = lambda obj: int(obj['LastModified'].strftime('%Y%m%d%H%M%S')) def sortFindLatest(bucket_name): resp = s3.list_objects(Bucket=bucket_name) if 'Contents' in resp: objs = resp['Contents'] files = sorted(objs, key=get_last_modified) for key in files: file = key['Key'] cx = s3.get_object(Bucket=bucket_name, Key=file) This works for me to sort by date and time. I am using Python3 AWS lambda. Your mileage may vary. It can be optimized, I purposely made it discrete. As mentioned in an earlier post, 'reverse=True' can be added to change the sort order. A: Slight improvement of above: import boto3 s3 = boto3.resource('s3') my_bucket = s3.Bucket('myBucket') files = my_bucket.objects.filter() files = [obj.key for obj in sorted(files, key=lambda x: x.last_modified, reverse=True)] A: keys = [] kwargs = {'Bucket': 'my_bucket'} while True: resp = s3.list_objects_v2(**kwargs) for obj in resp['Contents']: keys.append(obj['Key']) try: kwargs['ContinuationToken'] = resp['NextContinuationToken'] except KeyError: break this will get you all the keys in a sorted order A: So my answer can be used for last modified, but I thought that if you've come to this page, there is a chance that'd you like to be able to sort your files in some other manner. So to kill 2 birds with one stone: In this thread you can find the built-in method sorted. If you read the docs or this article, you will see that you can create your own function to give priority to how objects should be sorted. So for example in my case. I had a bunch of files that had some number in front of them and potentially a letter. It looked like this: 1.svg 10.svg 100a.svg 11.svg 110.svg ... 2.svg 20b.svg 200.svg ... 10011b.svg ... etc I wanted it to be sorted by the number up front - I didn't care about the letter behind the number, so I wrote this function: def my_sort(x): try: # this will take the file name, split over the file type and take just the name, cast it to an int, and return it return int(x.split(".")[0]) # if it couldn't do that except ValueError: # it will take the file name, split it over the extension, and take the name n = x.split(".")[0] s = "" # then for each character for e in n: # check to see if it is a digit and append it to a string if it is if e.isdigit(): s += e # if its not a digit, it hit the character at the end of the name, so return it else: return int(s) Which means now I can do this: import boto3 s3r = boto3.resource('s3') bucket = s3r.Bucket('my_bucket') os = bucket.objects.filter(Prefix="my_prefix/") os = [o.key.split("/")[-1] for o in os] os = sorted(os, key=my_sort) # do whatever with the sorted data which will sort my files by the numerical suffix in their name.
stackoverflow
{ "language": "en", "length": 830, "provenance": "stackexchange_0000F.jsonl.gz:875406", "question_score": "31", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574548" }
4c962fe11cd387d6dd7deacba1d6c610bb0b3a4e
Stackoverflow Stackexchange Q: 64 bit integers and older C++ compilers I want to use 64 bit integers in my C++ code. I understand I can either #include <cstdint> and then declare a uint64_t or use unsigned long long (or the equivalent for signed versions). However, it appears that support for this was not added until C++11 and I would like my code to be compatible with compilers that don't have full C++11 support. What is a good portable way to support 64 bit integers in C++? A: uint64_t is: Optional: These typedefs are not defined if no types with such characteristics exist. as you can read in the ref. From Should I use long long or int64_t for portable code?: The types long long and unsigned long long are standard C and standard C++ types each with at least 64 bits. All compilers I'm aware of provide these types, except possibly when in a -pedantic mode but in this case int64_t or uint64_t won't be available with pre-C++ 2011 compilers, either. " What date did g++/clang support long long/int64_t from? Since GCC 4.3 (aka March 5, 2008). As David Álvarez mentioned.
Q: 64 bit integers and older C++ compilers I want to use 64 bit integers in my C++ code. I understand I can either #include <cstdint> and then declare a uint64_t or use unsigned long long (or the equivalent for signed versions). However, it appears that support for this was not added until C++11 and I would like my code to be compatible with compilers that don't have full C++11 support. What is a good portable way to support 64 bit integers in C++? A: uint64_t is: Optional: These typedefs are not defined if no types with such characteristics exist. as you can read in the ref. From Should I use long long or int64_t for portable code?: The types long long and unsigned long long are standard C and standard C++ types each with at least 64 bits. All compilers I'm aware of provide these types, except possibly when in a -pedantic mode but in this case int64_t or uint64_t won't be available with pre-C++ 2011 compilers, either. " What date did g++/clang support long long/int64_t from? Since GCC 4.3 (aka March 5, 2008). As David Álvarez mentioned.
stackoverflow
{ "language": "en", "length": 189, "provenance": "stackexchange_0000F.jsonl.gz:875462", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574682" }
0fdd142a98c2f2bd63d1510159735a19dfdd2be8
Stackoverflow Stackexchange Q: Automatic library version update for Gradle projects is currently unsupported. Please update your build.gradle manually I have this in my building.gradle buildscript { ext.kotlin_version = '1.1.2-4' ext.kotlin_version = '1.1.2' repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.3.3' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } and always show me this Outdated Kotlin Runtime Your version of Kotlin runtime in 'kotlin-stdlib-1.1.2' library is 1.1.2, while plugin version is 1.1.2-release-Studio2.3-5. Runtime library should be updated to avoid compatibility problems. A: Update the Kotlin version to 1.1.2-5: buildscript { ext.kotlin_version = '1.1.2-5' repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.3.3' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" }
Q: Automatic library version update for Gradle projects is currently unsupported. Please update your build.gradle manually I have this in my building.gradle buildscript { ext.kotlin_version = '1.1.2-4' ext.kotlin_version = '1.1.2' repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.3.3' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } and always show me this Outdated Kotlin Runtime Your version of Kotlin runtime in 'kotlin-stdlib-1.1.2' library is 1.1.2, while plugin version is 1.1.2-release-Studio2.3-5. Runtime library should be updated to avoid compatibility problems. A: Update the Kotlin version to 1.1.2-5: buildscript { ext.kotlin_version = '1.1.2-5' repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.3.3' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } A: Consider using this gradle plugin https://github.com/ben-manes/gradle-versions-plugin It will tell you which libraries have updates available.
stackoverflow
{ "language": "en", "length": 112, "provenance": "stackexchange_0000F.jsonl.gz:875484", "question_score": "14", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574740" }
9f6a8423b5cf5113a9920c2e18e43ac950d65dda
Stackoverflow Stackexchange Q: Raw Query works on phpmyadmin but not in laravel I have written a raw Query in phpmyadmin which provide me exact answer.but same query when i tried to execute in Laravel..I got Error: Raw Query: SELECT customers.customer_name, customers.voucher_number , services.name, customers.status,sum(carts.amount) FROM services JOIN customers on services.id = customers.service_id JOIN carts on customers.id = carts.customer_id GROUP BY customers.id in Laravel : $status_report = DB::select("SELECT customers.customer_name, customers.voucher_number , services.name, customers.status,sum(carts.amount) FROM services JOIN customers on services.id = customers.service_id JOIN carts on customers.id = carts.customer_id GROUP BY customers.id"); What could be the possible Error? I got the following Error : SQLSTATE[42000]: Syntax error or access violation: 1055 'maitree.customers.customer_name' isn't in GROUP BY (SQL: SELECT customers.customer_name, customers.voucher_number , services.name, customers.status,sum(carts.amount) FROM services JOIN customers on services.id = customers.service_id JOIN carts on customers.id = carts.customer_id GROUP BY services.id) A: It might be a with SQL_MODE, Please makes changes into connection "config/database.php" : strict => false Hope this will help you.
Q: Raw Query works on phpmyadmin but not in laravel I have written a raw Query in phpmyadmin which provide me exact answer.but same query when i tried to execute in Laravel..I got Error: Raw Query: SELECT customers.customer_name, customers.voucher_number , services.name, customers.status,sum(carts.amount) FROM services JOIN customers on services.id = customers.service_id JOIN carts on customers.id = carts.customer_id GROUP BY customers.id in Laravel : $status_report = DB::select("SELECT customers.customer_name, customers.voucher_number , services.name, customers.status,sum(carts.amount) FROM services JOIN customers on services.id = customers.service_id JOIN carts on customers.id = carts.customer_id GROUP BY customers.id"); What could be the possible Error? I got the following Error : SQLSTATE[42000]: Syntax error or access violation: 1055 'maitree.customers.customer_name' isn't in GROUP BY (SQL: SELECT customers.customer_name, customers.voucher_number , services.name, customers.status,sum(carts.amount) FROM services JOIN customers on services.id = customers.service_id JOIN carts on customers.id = carts.customer_id GROUP BY services.id) A: It might be a with SQL_MODE, Please makes changes into connection "config/database.php" : strict => false Hope this will help you. A: You need to use DB::raw to wrap your raw SQL. $status_report = DB::select(DB::raw("SELECT customers.customer_name, customers.voucher_number , services.name, customers.status,sum(carts.amount) FROM services JOIN customers on services.id = customers.service_id JOIN carts on customers.id = carts.customer_id GROUP BY customers.id"));
stackoverflow
{ "language": "en", "length": 193, "provenance": "stackexchange_0000F.jsonl.gz:875497", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574788" }
e6d30dcc1e9668e92d90d5d1bab1396e64ba81f7
Stackoverflow Stackexchange Q: Firefox laggs on transition effect I have kept the main of what my page contain: http://boxfly.free.fr/test/transition So, we can choose to the top right the number of boxes which will be displayed, and unfortunately from only 2 boxes Firefox lags when we click on "Click Here to move the div" CSS: #DivWraper { transition: margin-left 0.5s ease-in; /* 0.5 second transition effect to slide in the sidenav */ } #DivWraper.openSidebar { margin-left: 250px; } JS: $("#LinkChange").click(function() { if($("#DivWraper").hasClass("openSidebar")) { $("#DivWraper").removeClass("openSidebar"); } else { $("#DivWraper").addClass("openSidebar"); } }); With Chrome the transition effect is all the time fluid, even with 50 boxes displayed. How can I optimize this effect to make it fluid with Firefox too? A: You can use translate on movable div to give it some hardware boost. `transform: translateZ(0);`
Q: Firefox laggs on transition effect I have kept the main of what my page contain: http://boxfly.free.fr/test/transition So, we can choose to the top right the number of boxes which will be displayed, and unfortunately from only 2 boxes Firefox lags when we click on "Click Here to move the div" CSS: #DivWraper { transition: margin-left 0.5s ease-in; /* 0.5 second transition effect to slide in the sidenav */ } #DivWraper.openSidebar { margin-left: 250px; } JS: $("#LinkChange").click(function() { if($("#DivWraper").hasClass("openSidebar")) { $("#DivWraper").removeClass("openSidebar"); } else { $("#DivWraper").addClass("openSidebar"); } }); With Chrome the transition effect is all the time fluid, even with 50 boxes displayed. How can I optimize this effect to make it fluid with Firefox too? A: You can use translate on movable div to give it some hardware boost. `transform: translateZ(0);` A: Someone from the Mozilla foundation has opened a bug ticket: https://bugzilla.mozilla.org/show_bug.cgi?id=1373394 It's due to the activation of the multiprocess (e10s). To check the difference, desactivate e10s by: about:config browser.tabs.remote.autostart=false browser.tabs.remote.autostart.2=false
stackoverflow
{ "language": "en", "length": 162, "provenance": "stackexchange_0000F.jsonl.gz:875499", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574797" }
f11aee178f686cdeffafba6d1ad0e9481631c714
Stackoverflow Stackexchange Q: How to change color on JFoenix's progress bar I am trying to change the color of the progress-bar found on the JFoenix's library (http://www.jfoenix.com). I'm using Java and JavaFX, here is my sample css: .progress-bar { -fx-accent: #4059a9;} It should work, but instead it disables the color. With css enabled: With css disabled (default color showing): A: It seems that your problem is caused by the background insets. Add this to your stylesheet: .jfx-progress-bar > .track, .jfx-progress-bar > .bar { -fx-background-radius: 0; -fx-background-insets: 0; } Now the styling works: .jfx-progress-bar > .bar { -fx-background-color: red; } The background color may be messed up after doing this, you can fix it with this: .jfx-progress-bar > .track { -fx-background-color: #E0E0E0; }
Q: How to change color on JFoenix's progress bar I am trying to change the color of the progress-bar found on the JFoenix's library (http://www.jfoenix.com). I'm using Java and JavaFX, here is my sample css: .progress-bar { -fx-accent: #4059a9;} It should work, but instead it disables the color. With css enabled: With css disabled (default color showing): A: It seems that your problem is caused by the background insets. Add this to your stylesheet: .jfx-progress-bar > .track, .jfx-progress-bar > .bar { -fx-background-radius: 0; -fx-background-insets: 0; } Now the styling works: .jfx-progress-bar > .bar { -fx-background-color: red; } The background color may be messed up after doing this, you can fix it with this: .jfx-progress-bar > .track { -fx-background-color: #E0E0E0; }
stackoverflow
{ "language": "en", "length": 120, "provenance": "stackexchange_0000F.jsonl.gz:875523", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574869" }
37838b64a343d0701918fac578371350cb1c5647
Stackoverflow Stackexchange Q: Cannon JS Collision detect amount of force I have two Cannon.js Objects, and have attached the "collide" event listener to both. carBody.addEventListener("collide",function(e){ }); I want to be able to react differently depending on how much force the collision has is there a way to do this? A: You can get the relative velocity in the contact point to determine the amount of energy in the collision. Example: carBody.addEventListener("collide",function(e){ var relativeVelocity = e.contact.getImpactVelocityAlongNormal(); if(Math.abs(relativeVelocity) > 10){ // More energy } else { // Less energy } });
Q: Cannon JS Collision detect amount of force I have two Cannon.js Objects, and have attached the "collide" event listener to both. carBody.addEventListener("collide",function(e){ }); I want to be able to react differently depending on how much force the collision has is there a way to do this? A: You can get the relative velocity in the contact point to determine the amount of energy in the collision. Example: carBody.addEventListener("collide",function(e){ var relativeVelocity = e.contact.getImpactVelocityAlongNormal(); if(Math.abs(relativeVelocity) > 10){ // More energy } else { // Less energy } });
stackoverflow
{ "language": "en", "length": 87, "provenance": "stackexchange_0000F.jsonl.gz:875525", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574885" }
c214cb794e7ed145105cd68f3a8d93aaea689fc8
Stackoverflow Stackexchange Q: How to start script in HTML without A: What you can do is put it inside an HTML event attribute. <body onload="/*your JS here*/"> </body> If that does not work, try attaching onload to another HTML element or try one of the other event handlers (though I believe that they should have taken this into account as well)
Q: How to start script in HTML without A: What you can do is put it inside an HTML event attribute. <body onload="/*your JS here*/"> </body> If that does not work, try attaching onload to another HTML element or try one of the other event handlers (though I believe that they should have taken this into account as well) A: How about this : <body onload="javascript:(function(){ // you can place your code here it should run alert('ok') })()"> </body> A: In Avatao's Senior Web Security Career Path, there is a hacking task, where you need to insert malicious javascript code - but the <script> is tag filtered (other tags aren't). Aenadon's answer gived me one solution: <body onload="your JS here"> </body> After submitting that, I checked the official solution, and I found that: <img src="x" onerror=alert('xss')>
stackoverflow
{ "language": "en", "length": 136, "provenance": "stackexchange_0000F.jsonl.gz:875526", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574894" }
42510e68e592234cd32c759ebe53410a573bc83d
Stackoverflow Stackexchange Q: Restify GET request body I am building a rest api using restify and I need to allow post body in get requests. I am using bodyparser but it gives only a string. I want it to be an object like in the normal post endpoints. How can I turn it in to an object? Here is my code: const server = restify.createServer(); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.get('/endpoint', function (req, res, next) { console.log(typeof req.body); console.log(req.body && req.body.asd); res.send(200); }); A: The bodyParser in restify doesn’t default to parsing valid JSON (which I assume you are using) for the body of requests that are using the GET method. You have to supply a configuration object to the initialization of bodyParser with the requestBodyOnGet key set to true: server.use(restify.bodyParser({ requestBodyOnGet: true })); To ensure that the body of the request will be JSON, I would also recommend you to check the content-type in your endpoint handler; e.g: const server = restify.createServer(); server.use(restify.queryParser()); server.use(restify.bodyParser({ requestBodyOnGet: true })); server.get('/endpoint', function (req, res, next) { // Ensures that the body of the request is of content-type JSON. if (!req.is('json')) { return next(new restify.errors.UnsupportedMediaTypeError('content-type: application/json required')); } console.log(typeof req.body); console.log(req.body && req.body.asd); res.send(200); });
Q: Restify GET request body I am building a rest api using restify and I need to allow post body in get requests. I am using bodyparser but it gives only a string. I want it to be an object like in the normal post endpoints. How can I turn it in to an object? Here is my code: const server = restify.createServer(); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.get('/endpoint', function (req, res, next) { console.log(typeof req.body); console.log(req.body && req.body.asd); res.send(200); }); A: The bodyParser in restify doesn’t default to parsing valid JSON (which I assume you are using) for the body of requests that are using the GET method. You have to supply a configuration object to the initialization of bodyParser with the requestBodyOnGet key set to true: server.use(restify.bodyParser({ requestBodyOnGet: true })); To ensure that the body of the request will be JSON, I would also recommend you to check the content-type in your endpoint handler; e.g: const server = restify.createServer(); server.use(restify.queryParser()); server.use(restify.bodyParser({ requestBodyOnGet: true })); server.get('/endpoint', function (req, res, next) { // Ensures that the body of the request is of content-type JSON. if (!req.is('json')) { return next(new restify.errors.UnsupportedMediaTypeError('content-type: application/json required')); } console.log(typeof req.body); console.log(req.body && req.body.asd); res.send(200); });
stackoverflow
{ "language": "en", "length": 197, "provenance": "stackexchange_0000F.jsonl.gz:875529", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574906" }
93a708467d124e11bbf59252224c8dd7d5fe7995
Stackoverflow Stackexchange Q: BottomSheet does not collapse when I press the Back Button My bottomSheet behaves correctly except in this situation. When I return to the activity via 'back button', I want the bottomSheet to collapse and I thought the code below would do the trick, but it doesn't work. What could be the cause ? (I confirmed with debugger that it reaches the statement) @Override public void onBackPressed() { mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } the same line works fine when it returns via finish(): if (resultCode == Activity.RESULT_OK) { mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } A: If your dialog has setCancelable(true), back button will not trigger the onbackpressed(), you can try this I have a class call BottomSheetFragmentDialog which is extend from BottomSheetDialogFragment and I have setCanceledOnTouchOutside(false) inside the onCreateDialog Method also overrdie the onCancel() override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) dialog.setCanceledOnTouchOutside(false) return dialog } override fun onCancel(dialog: DialogInterface) { super.onCancel(dialog) Toast.makeText(context, "Break Point Here", Toast.LENGTH_SHORT).show() }
Q: BottomSheet does not collapse when I press the Back Button My bottomSheet behaves correctly except in this situation. When I return to the activity via 'back button', I want the bottomSheet to collapse and I thought the code below would do the trick, but it doesn't work. What could be the cause ? (I confirmed with debugger that it reaches the statement) @Override public void onBackPressed() { mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } the same line works fine when it returns via finish(): if (resultCode == Activity.RESULT_OK) { mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } A: If your dialog has setCancelable(true), back button will not trigger the onbackpressed(), you can try this I have a class call BottomSheetFragmentDialog which is extend from BottomSheetDialogFragment and I have setCanceledOnTouchOutside(false) inside the onCreateDialog Method also overrdie the onCancel() override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) dialog.setCanceledOnTouchOutside(false) return dialog } override fun onCancel(dialog: DialogInterface) { super.onCancel(dialog) Toast.makeText(context, "Break Point Here", Toast.LENGTH_SHORT).show() } A: you can use this code onBackPressed() methode behavior.setState(BottomSheetBehavior.STATE_HIDDEN); A: Simpler solution. Don't have to override onBackPressed method, just have to remove setCancelable(true) and add bottomSheetDialog.setCanceledOnTouchOutside(false) when you initialise the bottomSheetDialog.
stackoverflow
{ "language": "en", "length": 184, "provenance": "stackexchange_0000F.jsonl.gz:875533", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574911" }
3953ab9c40af95a714bff5f0be254e6e1c36f429
Stackoverflow Stackexchange Q: Display HTML content in a Custom notification Is it possible to build a custom notification that display HTML content ? I saw that it's possible to build custom notification using RemoteViews, will it be possible to have WebView embedded in a RemoteViews, and pass it as a custom view to the notification ? A: No, sadly this is impossible :( Custom notifications can only contain RemoteViews which only can hold a certain subset of all views like Buttons, TextViews, etc.
Q: Display HTML content in a Custom notification Is it possible to build a custom notification that display HTML content ? I saw that it's possible to build custom notification using RemoteViews, will it be possible to have WebView embedded in a RemoteViews, and pass it as a custom view to the notification ? A: No, sadly this is impossible :( Custom notifications can only contain RemoteViews which only can hold a certain subset of all views like Buttons, TextViews, etc. A: Not sure if this is what you are asking for, but you should be able to style your notification with HTML tags, or add link to it. Here is the nice article on how to style notification with HTML: https://itnext.io/android-notification-styling-cc6b0bb86021 In short you should be able to do something like this: val styleNotificationWithHtml = Html.fromHtml(yourNotification, FROM_HTML_MODE_LEGACY)
stackoverflow
{ "language": "en", "length": 138, "provenance": "stackexchange_0000F.jsonl.gz:875547", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574951" }
80bcac1986327149f4e6854f242c48f6e8c9eb6f
Stackoverflow Stackexchange Q: How to check the array key matches specific string in php $array = array( "[ci_id]" => '144309', "[NEW flag]" => 'No', "[[*PRODUCT_IMAGE_ANCHOR1*]]" => , "[[*PRODUCT_IMAGE2*]]" => '154154154' ); I need to get the elements which have pattern like '[['. I have tried by using array_key_exists():- if (array_key_exists('[*PRODUCT_IMAGE2*]', $array)) But i want to match only with '[' Can any one help me on this A: Use preg_grep() with array_keys() like below:- $matches = preg_grep ('/[.*?]/i', array_keys($array)); print_r($matches); Output:- https://eval.in/817299 Or can do it using strpos() also:- foreach($array as $key=>$val){ if(strpos($key,'[')!== false){ echo $key ."is matched with [*] pattern"; echo PHP_EOL; } } Output:- https://eval.in/817297
Q: How to check the array key matches specific string in php $array = array( "[ci_id]" => '144309', "[NEW flag]" => 'No', "[[*PRODUCT_IMAGE_ANCHOR1*]]" => , "[[*PRODUCT_IMAGE2*]]" => '154154154' ); I need to get the elements which have pattern like '[['. I have tried by using array_key_exists():- if (array_key_exists('[*PRODUCT_IMAGE2*]', $array)) But i want to match only with '[' Can any one help me on this A: Use preg_grep() with array_keys() like below:- $matches = preg_grep ('/[.*?]/i', array_keys($array)); print_r($matches); Output:- https://eval.in/817299 Or can do it using strpos() also:- foreach($array as $key=>$val){ if(strpos($key,'[')!== false){ echo $key ."is matched with [*] pattern"; echo PHP_EOL; } } Output:- https://eval.in/817297 A: The following code will give the true for the key with double [[ in if you know the element index value $test = array("a"=>'a',"[a]"=>'a',"[[a]]"=>'a',"b"=>'b',"c"=>'c'); var_dump(array_key_exists("[[a]]", $test)); If you can checking the keys to determine if [[ even exist then the following code should work $test = array("a"=>'a',"[a]"=>'a','[[a]]'=>'a',"b"=>'b',"c"=>'c'); $values = array(); foreach ($test as $key=>$value) { if (stripos('[[', substr($key, 0, 2)) !== false) { array_push($values, $value); } }
stackoverflow
{ "language": "en", "length": 172, "provenance": "stackexchange_0000F.jsonl.gz:875550", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574955" }
bb29e9fe9f6bab0d7fe61e0bd084aa822918f575
Stackoverflow Stackexchange Q: Status of React Navigation drawer? (open or closed) I'm building a drawer with React Navigation and want to perform some logic if the user closes the drawer. I don't see anything obvious in the documentation that will allow me to do this. Is anyone aware of a way to do this? A: According to @ufxmeng import { StatusBar, } from "react-native"; const MyDrawerNavigator = DrawerNavigator({ //... }); const defaultGetStateForAction = MyDrawerNavigator.router.getStateForAction; MyDrawerNavigator.router.getStateForAction = (action, state) => { if(state && action.type === 'Navigation/NAVIGATE' && action.routeName === 'DrawerClose') { StatusBar.setHidden(false); } if(state && action.type === 'Navigation/NAVIGATE' && action.routeName === 'DrawerOpen') { StatusBar.setHidden(true); } return defaultGetStateForAction(action, state); }; See here https://github.com/react-community/react-navigation/blob/673b9d2877d7e84fbfbe2928305ead7e51b04835/docs/api/routers/Routers.md and here https://github.com/aksonov/react-native-router-flux/issues/699
Q: Status of React Navigation drawer? (open or closed) I'm building a drawer with React Navigation and want to perform some logic if the user closes the drawer. I don't see anything obvious in the documentation that will allow me to do this. Is anyone aware of a way to do this? A: According to @ufxmeng import { StatusBar, } from "react-native"; const MyDrawerNavigator = DrawerNavigator({ //... }); const defaultGetStateForAction = MyDrawerNavigator.router.getStateForAction; MyDrawerNavigator.router.getStateForAction = (action, state) => { if(state && action.type === 'Navigation/NAVIGATE' && action.routeName === 'DrawerClose') { StatusBar.setHidden(false); } if(state && action.type === 'Navigation/NAVIGATE' && action.routeName === 'DrawerOpen') { StatusBar.setHidden(true); } return defaultGetStateForAction(action, state); }; See here https://github.com/react-community/react-navigation/blob/673b9d2877d7e84fbfbe2928305ead7e51b04835/docs/api/routers/Routers.md and here https://github.com/aksonov/react-native-router-flux/issues/699 A: This is for anyone using the v2.0+ version of react-navigation. There are now drawer actions you can track. { OPEN_DRAWER: 'Navigation/OPEN_DRAWER', CLOSE_DRAWER: 'Navigation/CLOSE_DRAWER', TOGGLE_DRAWER: 'Navigation/TOGGLE_DRAWER', DRAWER_OPENED: 'Navigation/DRAWER_OPENED', DRAWER_CLOSED: 'Navigation/DRAWER_CLOSED' } react-navigation.js line 825 However, it seems that implied drawer navigations from say swiping don't fire the OPEN_/CLOSE_ actions, since you didn't manually toggle it. The _OPENED/_CLOSED actions do fire afterwards, though. const MyDrawerNavigator = createDrawerNavigator(...); const defaultGetStateForAction = MyDrawerNavigator.router.getStateForAction; MyDrawerNavigator.router.getStateForAction = (action, state) => { switch (action.type) { case 'Navigation/OPEN_DRAWER': case 'Navigation/DRAWER_OPENED': StatusBar.setHidden(true, 'slide'); break; case 'Navigation/CLOSE_DRAWER': case 'Navigation/DRAWER_CLOSED': StatusBar.setHidden(false, 'slide'); break; } return defaultGetStateForAction(action, state); }; A: Working with "react-navigation": "^3.5.1" const defaultGetStateForAction = DrawerNav.router.getStateForAction; DrawerNav.router.getStateForAction = (action, state) => { if(action){ if(action.type == 'Navigation/MARK_DRAWER_SETTLING' && action.willShow){ StatusBar.setHidden(true); } else if(action.type == 'Navigation/MARK_DRAWER_SETTLING' && !action.willShow) { StatusBar.setHidden(false); } } return defaultGetStateForAction(action, state); }; A: For anyone looking to wire it up such that the drawer events are available in one of your Screens or Components instead of the top level app, I was able to wire that up by using screenProps as described in this post. You first set up the screenProps on your app and pass in the router and whatever else you need. You can pull screenProps off the props and use it your screen or component (I wired it up in the constructor in this example), use getStateForAction to setState in your component driven off the router events. Here is an example (some code removed for clarity) App.js import React from 'react'; import { AppLoading } from 'expo'; import { createDrawerNavigator, createAppContainer, createStackNavigator, } from 'react-navigation'; import { HomeScreen } from './src/screens/HomeScreen.android'; import { LanguageSelectScreen } from './src/screens/LanguageSelectScreen'; export default class App extends React.Component { state = { isLoadingComplete: false, isTilted: false, }; constructor() { super(); } render() { if (!this.state.isLoadingComplete && !this.props.skipLoadingScreen) { return ( <AppLoading /> ); } else { return ( <MyApp screenProps={MyAppNavigator.router} /> ); } } } const MyAppNavigator = createDrawerNavigator( { Home: { screen: HomeScreen, }, PlayerNameScreen: { screen: PlayerNameScreen, }, }, { unmountInactiveRoutes: true, initialRouteName: 'PlayerNameScreen', }, ); const RootStack = createStackNavigator( { Main: { screen: MyAppNavigator, }, MyModal: { screen: LanguageSelectScreen, }, }, { mode: 'modal', headerMode: 'none', }, ); export const MyApp = createAppContainer(RootStack); HomeScreen.android.js import React from 'react'; import {Icon} from 'react-native-elements'; export class HomeScreen extends React.Component { static navigationOptions = { drawerLabel: () => 'Home', drawerIcon: ({ tintColor }) => ( <Icon name="checkerboard" type="material-community" size={25} color={tintColor} /> ), }; constructor(props) { super(props); const router = props.screenProps; const defaultGetStateForAction = router.getStateForAction; router.getStateForAction = (action, state) => { switch (action.type) { case 'Navigation/MARK_DRAWER_SETTLING': if (action.willShow == false) { console.log('CLOSED'); this.setState({ isTilted: false }); } else if (action.willShow == true) { this.setState({ isTilted: true }); console.log('OPEN'); } break; } return defaultGetStateForAction(action, state); }; this.state = { isTilted: false, }; } render() { const { isTilted } = this.state; // ... render using isTilted } } A: Now in react navigation 5 you can directly access the status of your drawer using this approach : useIsDrawerOpen() is a Hook to detect if the drawer is open in a parent navigator. For exemple in your view you can test if your drawer is open or not directly using this approach : import { useIsDrawerOpen } from '@react-navigation/drawer'; const MainContainer = () => { return ( <View style={(useIsDrawerOpen()) ? styles.conatinerOpenStyle : styles.containerClosedStyle}> <Text>{console.log("Test drawer "+useIsDrawerOpen())}</Text> </View> );} A: You need to custom navigation actions to capture the DrawerClose event: const MyDrawerNavigator = DrawerNavigator({ //... }); const defaultGetStateForAction = MyDrawerNavigator.router.getStateForAction; MyDrawerNavigator.router.getStateForAction = (action, state) => { //use 'DrawerOpen' to capture drawer open event if (state && action.type === 'Navigation/NAVIGATE' && action.routeName === 'DrawerClose') { console.log('DrawerClose'); //write the code you want to deal with 'DrawerClose' event } return defaultGetStateForAction(action, state); }; A: I found something similar to asdfghjklm. Here's my code which is working perfectly, even when you use a swipe to open - and then use a button to close it: openCloseDrawer = (props) => { if (props.navigation.state.index == 1) { props.navigation.navigate('DrawerClose'); } else { props.navigation.navigate('DrawerOpen'); } } I execute this function when the user taps on the "Open/Close Drawer" button. A: Based on Brad Bumbalough, fredrivett (thank you mans) solution I find a more fast response solution (the other solution delays secons in some uses). const defaultGetStateForAction = StackLogadoDrawer.router.getStateForAction; StackLogadoDrawer.router.getStateForAction = (action, state) => { switch (action.type) { case 'Navigation/MARK_DRAWER_SETTLING': if (action.willShow == false) { console.log('CERRADO'); } else if (action.willShow == true) { console.log('ABIERTO'); } break; } return defaultGetStateForAction(action, state); }; This is fired just immediately actions occurs (or very near). It works on gestures or calling openDrawer() Anyway I think this is a "must have" easy and direct way in the API A: Hmm not really seeing much. One way would be to control the opening/closing of the drawer manually using: this.props.navigation.navigate('DrawerOpen'); // open drawer this.props.navigation.navigate('DrawerClose'); // close drawer That way you can wrap your close/open events in a function where you can do whatever you want before opening/closing. The only other possible solution I saw in their docs was using a custom contentComponent. You can pass a function to the onItemPress(route) event, so maybe you can try hooking into that. A: This is working fine in React-Native, not sure about React. For my case I had to change the StatusBar so I did not need to know wether the Drawer is closed fully or not, So below code worked for me... props.navigation.state.drawerMovementDirection === 'closing' ? //it is closing not fully closed : (props.navigation.state.drawerMovementDirection === 'opening' || props.navigation.state.isDrawerOpen) && ( //fully opened or opening ) If you don't need to know immediate then you can use below code, and this will work fine and will give you accurate answer whether the Drawer is Open or Not! Note: This will be delayed answer, in my case it was taking 1 sec. props.navigation.state.isDrawerOpen? //open : //close; If the solution does't work I am very sorry, but above all answer did not worked! So this is the version which is working for me:)) A: useEffect(() => { const _unsubscribe = props.navigation.addListener('state', (data) => { var array = data.data.state.routes[0].state.history; const mydata = array.some(item => item.hasOwnProperty('status')) console.log('data--->', mydata) if (mydata) { console.log('daawer close ') } else { console.log('daawer open ') } }); return _unsubscribe; }, []) A: Without Redux integration can be used onNavigationStateChange on router component. Just intercept drawer actions: DrawerOpen and DrawerClose. Example: handleNavigationState = (previous, next, action) => { if (action.routeName === 'DrawerOpen') { this.props.setDrawerState(true); } else if (action.routeName === 'DrawerClose') { this.props.setDrawerState(false); } } render() { return ( <Router onNavigationStateChange={this.handleNavigationState} /> ); } A: I know this is late, but for anyone who is looking for an answer: The logic for the drawer being open/closed is in: this.props.navigation.state.routes[0].index It's 0 for closed, 1 for open. You can also toggle the Drawers with this.props.navigation.navigate('DrawerToggle') instead of this.props.navigation.navigate('DrawerOpen'); or this.props.navigation.navigate('DrawerClose'); It seems to be more convenient for me and I have not happened upon any problems yet. Although it's nice to know whether they are toggled or not in order to invoke other actions. I truly believe React-Navigation has one of the worst documentation that I have ever seen. There are commands that nobody knows about. I could not find the DrawerToggle action in the documents, and I only happened upon it through using console.log(this.props.navigation);
stackoverflow
{ "language": "en", "length": 1314, "provenance": "stackexchange_0000F.jsonl.gz:875556", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44574976" }
a695b74b0e61be2e0fa9c4db90e8115ee9e4552a
Stackoverflow Stackexchange Q: Undefined method #sanitize for ActiveRecord::Base I just upgraded to Rails 5.1.1 and am receiving this error. NoMethodError (undefined method `sanitize' for ActiveRecord::Base:Class): The stack traces back to this code like_search_term = ActiveRecord::Base::sanitize("%#{escaped_search_term}%") Has this method been removed or changed in the new Rails upgrade? A: Yes, indeed, it appears to be removed. Sanitize was never part of the public API of the framework. As we didn't need it in the framework anymore, we removed. The recommended ways to sanitize raw SQL for use in execute statements were the public API for that http://api.rubyonrails.org/classes/ActiveRecord/Sanitization/ClassMethods.html
Q: Undefined method #sanitize for ActiveRecord::Base I just upgraded to Rails 5.1.1 and am receiving this error. NoMethodError (undefined method `sanitize' for ActiveRecord::Base:Class): The stack traces back to this code like_search_term = ActiveRecord::Base::sanitize("%#{escaped_search_term}%") Has this method been removed or changed in the new Rails upgrade? A: Yes, indeed, it appears to be removed. Sanitize was never part of the public API of the framework. As we didn't need it in the framework anymore, we removed. The recommended ways to sanitize raw SQL for use in execute statements were the public API for that http://api.rubyonrails.org/classes/ActiveRecord/Sanitization/ClassMethods.html A: You can still use the sanitization methods if you use them within context of the model. For example, you can add this to your model: def self.where_ilike(search_terms) where('search_tokens ILIKE ?', "%#{sanitize_sql_like(search_terms)}%") end
stackoverflow
{ "language": "en", "length": 127, "provenance": "stackexchange_0000F.jsonl.gz:875586", "question_score": "13", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44575106" }
e25ab015cf40af5fbba7bf083b6cfba48f09fa42
Stackoverflow Stackexchange Q: for loop for creating multiple data frames and assigning values I would like to create multiple data frames and assign them based on years. I have seen other posts but I couldn't duplicate it for my case. For example, a <- c(1,2,3,4) b <- c('kk','km','ll','k3') time <- (2001,2001,2002,2003) df <- data.frame(a,b,time) myvalues <- c(2001,2002,2003) for (i in 1:3) { y[[i]]<- df[df$time=myvalues[[i]],} I would like to create three dataframes y1, y2, y3 for years 2001, 2002 and 2003. Any suggestions how do using a for loop? A: The assign() function is made for this. See ?assign() for syntax. a <- c(1,2,3,4) b <- c("kk","km","ll","k3") time <- c(2001,2001,2002,2003) df <- data.frame(a,b,time) myvalues <- c(2001,2002,2003) for (i in 1:3) { assign(paste0("y",i), df[df$time==myvalues[i],]) } See here for more ways to achieve this.
Q: for loop for creating multiple data frames and assigning values I would like to create multiple data frames and assign them based on years. I have seen other posts but I couldn't duplicate it for my case. For example, a <- c(1,2,3,4) b <- c('kk','km','ll','k3') time <- (2001,2001,2002,2003) df <- data.frame(a,b,time) myvalues <- c(2001,2002,2003) for (i in 1:3) { y[[i]]<- df[df$time=myvalues[[i]],} I would like to create three dataframes y1, y2, y3 for years 2001, 2002 and 2003. Any suggestions how do using a for loop? A: The assign() function is made for this. See ?assign() for syntax. a <- c(1,2,3,4) b <- c("kk","km","ll","k3") time <- c(2001,2001,2002,2003) df <- data.frame(a,b,time) myvalues <- c(2001,2002,2003) for (i in 1:3) { assign(paste0("y",i), df[df$time==myvalues[i],]) } See here for more ways to achieve this.
stackoverflow
{ "language": "en", "length": 129, "provenance": "stackexchange_0000F.jsonl.gz:875588", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44575110" }
3c1745be51ddfccf8c9ae39a3d3e628d4f7b7b09
Stackoverflow Stackexchange Q: What does Docker run --storage-opt size=XYZ means? Docker run cli command has an option --storage-opt used like this: docker run --storage-opt size=XYZ ....nginx Does the "XYZ" size specified above refer to the CoW layer or the total size of base image and CoW layer as discussed in this link ? A: From: https://docs.docker.com/engine/reference/commandline/run/#set-storage-driver-options-per-container docker run -it --storage-opt size=120G fedora /bin/bash This (size) will allow to set the container rootfs size to 120G at creation time. This option is only available for the devicemapper, btrfs, overlay2, windowsfilter and zfs graph drivers. For the devicemapper, btrfs, windowsfilter and zfs graph drivers, user cannot pass a size less than the Default BaseFS Size. For the overlay2 storage driver, the size option is only available if the backing fs is xfs and mounted with the pquota mount option. Under these conditions, user can pass any size less then the backing fs size.
Q: What does Docker run --storage-opt size=XYZ means? Docker run cli command has an option --storage-opt used like this: docker run --storage-opt size=XYZ ....nginx Does the "XYZ" size specified above refer to the CoW layer or the total size of base image and CoW layer as discussed in this link ? A: From: https://docs.docker.com/engine/reference/commandline/run/#set-storage-driver-options-per-container docker run -it --storage-opt size=120G fedora /bin/bash This (size) will allow to set the container rootfs size to 120G at creation time. This option is only available for the devicemapper, btrfs, overlay2, windowsfilter and zfs graph drivers. For the devicemapper, btrfs, windowsfilter and zfs graph drivers, user cannot pass a size less than the Default BaseFS Size. For the overlay2 storage driver, the size option is only available if the backing fs is xfs and mounted with the pquota mount option. Under these conditions, user can pass any size less then the backing fs size.
stackoverflow
{ "language": "en", "length": 149, "provenance": "stackexchange_0000F.jsonl.gz:875622", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44575197" }
8d447b45542d246c95f38926f67c4d86b08d4c28
Stackoverflow Stackexchange Q: reading multiple files contained in a zip file with pandas I have multiple zip files containing different types of txt files. Like below: zip1 - file1.txt - file2.txt - file3.txt How can I use pandas to read in each of those files without extracting them? I know if they were 1 file per zip I could use the compression method with read_csv like below: df = pd.read_csv(textfile.zip, compression='zip') Any help on how to do this would be great. A: The most simplest way to handle this (if you have multiple parts of one big csv file compressed to a one zip file). import pandas as pd from zipfile import ZipFile df = pd.concat( [pd.read_csv(ZipFile('some.zip').open(i)) for i in ZipFile('some.zip').namelist()], ignore_index=True )
Q: reading multiple files contained in a zip file with pandas I have multiple zip files containing different types of txt files. Like below: zip1 - file1.txt - file2.txt - file3.txt How can I use pandas to read in each of those files without extracting them? I know if they were 1 file per zip I could use the compression method with read_csv like below: df = pd.read_csv(textfile.zip, compression='zip') Any help on how to do this would be great. A: The most simplest way to handle this (if you have multiple parts of one big csv file compressed to a one zip file). import pandas as pd from zipfile import ZipFile df = pd.concat( [pd.read_csv(ZipFile('some.zip').open(i)) for i in ZipFile('some.zip').namelist()], ignore_index=True ) A: You can pass ZipFile.open() to pandas.read_csv() to construct a pandas.DataFrame from a csv-file packed into a multi-file zip. Code: pd.read_csv(zip_file.open('file3.txt')) Example to read all .csv into a dict: from zipfile import ZipFile zip_file = ZipFile('textfile.zip') dfs = {text_file.filename: pd.read_csv(zip_file.open(text_file.filename)) for text_file in zip_file.infolist() if text_file.filename.endswith('.csv')} A: I had a similar problem with XML files awhile ago. The zipfile module can get you there. from zipfile import ZipFile z = ZipFile(yourfile) text_files = z.infolist() for text_file in text_files: z.read(text_file.filename) If you want to concatenate them into a pandas object then it might get a bit more complex, but that should get you started. Note that the read method returns bytes, so you may have to handle that as well.
stackoverflow
{ "language": "en", "length": 240, "provenance": "stackexchange_0000F.jsonl.gz:875641", "question_score": "35", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44575251" }
37a0a90566940b33a91d70f48e553ca5d8aea01e
Stackoverflow Stackexchange Q: Pass node command line options to npm executable? Does anyone know if it is possible to pass node command line options (e.g. --expose-gc) directly into an npm executable. I Have a node module that builds an executable (See here). I want that executable to have access to global.gc(). In order to do this, you need to start your node process with the --expose-gc flag. I could force users to wrap my executable around a node command but then why do i even need an executable. Thoughts? A: Assume your executable file is called ex. First, make sure it's executable by doing chmod a+x ex at the command line. Next, make sure the ex file begins with a line like: #! /usr/bin/env node --expose-gc env(1) will find the node executable on your path, and run it with the given arguments, passing the contents of ex into stdin of that process because of the #! "scratchbang" at the beginning of the line. Run your program with just ex, or ./bin/ex (e.g.), rather than node ex.
Q: Pass node command line options to npm executable? Does anyone know if it is possible to pass node command line options (e.g. --expose-gc) directly into an npm executable. I Have a node module that builds an executable (See here). I want that executable to have access to global.gc(). In order to do this, you need to start your node process with the --expose-gc flag. I could force users to wrap my executable around a node command but then why do i even need an executable. Thoughts? A: Assume your executable file is called ex. First, make sure it's executable by doing chmod a+x ex at the command line. Next, make sure the ex file begins with a line like: #! /usr/bin/env node --expose-gc env(1) will find the node executable on your path, and run it with the given arguments, passing the contents of ex into stdin of that process because of the #! "scratchbang" at the beginning of the line. Run your program with just ex, or ./bin/ex (e.g.), rather than node ex.
stackoverflow
{ "language": "en", "length": 174, "provenance": "stackexchange_0000F.jsonl.gz:875710", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44575445" }
6e8074191338fc3b16cbe7272e688c978c4a0097
Stackoverflow Stackexchange Q: Single instance dotnetcore cli app on linux I am interested in how to inforce a single instance policy for dotnetcore console apps. To my surprise it seems like there isn't much out there on the topic. I found this one stacko, How to restrict a program to a single instance, but it doesnt seem to work for me on dotnetcore with ubuntu. Anyone here do this before? A: Variation of @MusuNaji's solution at: How to restrict a program to a single instance private static bool AlreadyRunning() { Process[] processes = Process.GetProcesses(); Process currentProc = Process.GetCurrentProcess(); logger.LogDebug("Current proccess: {0}", currentProc.ProcessName); foreach (Process process in processes) { if (currentProc.ProcessName == process.ProcessName && currentProc.Id != process.Id) { logger.LogInformation("Another instance of this process is already running: {pid}", process.Id); return true; } } return false; }
Q: Single instance dotnetcore cli app on linux I am interested in how to inforce a single instance policy for dotnetcore console apps. To my surprise it seems like there isn't much out there on the topic. I found this one stacko, How to restrict a program to a single instance, but it doesnt seem to work for me on dotnetcore with ubuntu. Anyone here do this before? A: Variation of @MusuNaji's solution at: How to restrict a program to a single instance private static bool AlreadyRunning() { Process[] processes = Process.GetProcesses(); Process currentProc = Process.GetCurrentProcess(); logger.LogDebug("Current proccess: {0}", currentProc.ProcessName); foreach (Process process in processes) { if (currentProc.ProcessName == process.ProcessName && currentProc.Id != process.Id) { logger.LogInformation("Another instance of this process is already running: {pid}", process.Id); return true; } } return false; } A: This is a little more difficult on .NET core than it should be, due to the problem of mutex checking on Linux/MacOS (as reported above). Also Theyouthis's solution isn't helpful as all .NET core apps are run via the CLI which has a process name of 'dotnet' which if you are running multiple .NET core apps on the same machine the duplicate instance check will trigger incorrectly. A simple way to do this that is also multi-platform robust is to open a file for write when the application starts, and close it at the end. If the file fails to open it is due to another instance running concurrently and you can handle that in the try/catch. Using FileStream to open the file will also create it if it doesn't first exist. try { lockFile = File.OpenWrite("SingleInstance.lck"); } catch (Exception) { Console.WriteLine("ERROR - Server is already running. End that instance before re-running. Exiting in 5 seconds..."); System.Threading.Thread.Sleep(5000); return; } A: Here is my implementation using Named pipes. It supports passing arguments from the second instance. Note: I did not test on Linux or Mac but it should work in theory. Usage public static int Main(string[] args) { instanceManager = new SingleInstanceManager("8A3B7DE2-6AB4-4983-BBC0-DF985AB56703"); if (!instanceManager.Start()) { return 0; // exit, if same app is running } instanceManager.SecondInstanceLaunched += InstanceManager_SecondInstanceLaunched; // Initialize app. Below is an example in WPF. app = new App(); app.InitializeComponent(); return app.Run(); } private static void InstanceManager_SecondInstanceLaunched(object sender, SecondInstanceLaunchedEventArgs e) { app.Dispatcher.Invoke(() => new MainWindow().Show()); } Your Copy-and-paste code public class SingleInstanceManager { private readonly string applicationId; public SingleInstanceManager(string applicationId) { this.applicationId = applicationId; } /// <summary> /// Detect if this is the first instance. If it is, start a named pipe server to listen for subsequent instances. Otherwise, send <see cref="Environment.GetCommandLineArgs()"/> to the first instance. /// </summary> /// <returns>True if this is tthe first instance. Otherwise, false.</returns> public bool Start() { using var client = new NamedPipeClientStream(applicationId); try { client.Connect(0); } catch (TimeoutException) { Task.Run(() => StartListeningServer()); return true; } var args = Environment.GetCommandLineArgs(); using (var writer = new BinaryWriter(client, Encoding.UTF8)) { writer.Write(args.Length); for (int i = 0; i < args.Length; i++) { writer.Write(args[i]); } } return false; } private void StartListeningServer() { var server = new NamedPipeServerStream(applicationId); server.WaitForConnection(); using (var reader = new BinaryReader(server, Encoding.UTF8)) { var argc = reader.ReadInt32(); var args = new string[argc]; for (int i = 0; i < argc; i++) { args[i] = reader.ReadString(); } SecondInstanceLaunched?.Invoke(this, new SecondInstanceLaunchedEventArgs { Arguments = args }); } StartListeningServer(); } public event EventHandler<SecondInstanceLaunchedEventArgs> SecondInstanceLaunched; } public class SecondInstanceLaunchedEventArgs { public string[] Arguments { get; set; } } Unit test [TestClass] public class SingleInstanceManagerTests { [TestMethod] public void SingleInstanceManagerTest() { var id = Guid.NewGuid().ToString(); var manager = new SingleInstanceManager(id); string[] receivedArguments = null; var correctArgCount = Environment.GetCommandLineArgs().Length; manager.SecondInstanceLaunched += (sender, e) => receivedArguments = e.Arguments; var instance1 = manager.Start(); Thread.Sleep(200); var manager2 = new SingleInstanceManager(id); Assert.IsFalse(manager2.Start()); Thread.Sleep(200); Assert.IsTrue(instance1); Assert.IsNotNull(receivedArguments); Assert.AreEqual(correctArgCount, receivedArguments.Length); var receivedArguments2 = receivedArguments; var manager3 = new SingleInstanceManager(id); Thread.Sleep(200); Assert.IsFalse(manager3.Start()); Assert.AreNotSame(receivedArguments, receivedArguments2); Assert.AreEqual(correctArgCount, receivedArguments.Length); } } A: The downside of deandob's solution is that one can launch the application from another path. So you may prefer some static path or a tmp path for all users. Here is my attempt: //second instance launch guard var tempPath = Environment.GetEnvironmentVariable("TEMP", EnvironmentVariableTarget.Machine) ?? Path.GetTempPath(); var lockPath = Path.Combine(tempPath, "SingleInstance.lock"); await using var lockFile = File.OpenWrite(lockPath); here I'm trying to get TEMP system variable at the scope of machine (not the user TEMP) and if its empty - fallback to the user's temp folder on windows or shared /tmp on some linuxes.
stackoverflow
{ "language": "en", "length": 725, "provenance": "stackexchange_0000F.jsonl.gz:875720", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44575472" }
6f8370b7d8273e77c21c6a14486fdaf461e88270
Stackoverflow Stackexchange Q: How can i check if two SKSpriteNodes are near each other? How can i check if two SKSpriteNodes are near each other? like in a radius of 100. i am using the gamescene.swift and gamescene.sks. A: SKSpriteNode has a position property with the (x, y). Distance between two positions is sqrt((x1-x2)^2 + (y1-y2)^2) So: let dist = sqrt(pow(sk1.position.x - sk2.position.x, 2.0) + pow(sk1.position.y - sk2.position.y, 2.0)) if dist < 100 { // they are close } This is center to center. Based on @MartinR's comment, you could also let dist = hypot(sk1.position.x - sk2.position.x, sk1.position.y - sk2.position.y) Which does the distance function for you.
Q: How can i check if two SKSpriteNodes are near each other? How can i check if two SKSpriteNodes are near each other? like in a radius of 100. i am using the gamescene.swift and gamescene.sks. A: SKSpriteNode has a position property with the (x, y). Distance between two positions is sqrt((x1-x2)^2 + (y1-y2)^2) So: let dist = sqrt(pow(sk1.position.x - sk2.position.x, 2.0) + pow(sk1.position.y - sk2.position.y, 2.0)) if dist < 100 { // they are close } This is center to center. Based on @MartinR's comment, you could also let dist = hypot(sk1.position.x - sk2.position.x, sk1.position.y - sk2.position.y) Which does the distance function for you. A: If you want to use built in SKPhysicsBody, then just set the body to a circle with radius of 100, then you can use the didBeginContact method when a contact occurs: func setup() { let physicsBody1 = SKPhysicsBody(circleOfRadius:100.0) physicsBody1.categoryBitMask = 1 physicsBody1.collisionBitMask = 0 physicsBody1.contactTestBitMask = 2 sprite1.physicsBody = physicsBody1 let physicsBody2 = SKPhysicsBody(circleOfRadius:100.0) physicsBody2.categoryBitMask = 2 physicsBody2.collisionBitMask = 0 physicsBody2.contactTestBitMask = 1 sprite2.physicsBody = physicsBody2 } func didBeginContact(contact:SKPhysicsContact) { //find some tutorials to your liking, and do your contact code here }
stackoverflow
{ "language": "en", "length": 189, "provenance": "stackexchange_0000F.jsonl.gz:875723", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44575483" }
a8c63a5928dd3873dbb8d8f2de91104c1b4cc87d
Stackoverflow Stackexchange Q: C# Microsoft.Office.Interop.Excel will not open Excel Window I have a main method here that is simply trying to open an excel workbook. This same script works on other machines, but I can't get it to work on this machine. It starts a background EXCEL.exe process, but does not open an excel window. If I end that process in the task manager, and then open excel, it shows the workbook in the mySheet string variable in the document recovery pane. So something opened. I just couldn't see it. What am I missing here? Using a Console Application in Visual Studio 2017. Excel 2016 64 bit. using Excel = Microsoft.Office.Interop.Excel; static void Main(string[] args) { try { string mySheet = @"C:\\Users\\dwh002\\Documents\\ZIP_COUNTY_032017.xlsx"; var excelApplication = new Excel.Application(); excelApplication.Visible = true; var workbooks = excelApplication.Workbooks; var workbook = workbooks.Open(mySheet); } catch (Exception) { throw; } A: The moving the Visible = true line below the workbooks.Open line worked. I'm not sure why this machine is the only one having trouble with the code in this order, but I'm glad it worked.
Q: C# Microsoft.Office.Interop.Excel will not open Excel Window I have a main method here that is simply trying to open an excel workbook. This same script works on other machines, but I can't get it to work on this machine. It starts a background EXCEL.exe process, but does not open an excel window. If I end that process in the task manager, and then open excel, it shows the workbook in the mySheet string variable in the document recovery pane. So something opened. I just couldn't see it. What am I missing here? Using a Console Application in Visual Studio 2017. Excel 2016 64 bit. using Excel = Microsoft.Office.Interop.Excel; static void Main(string[] args) { try { string mySheet = @"C:\\Users\\dwh002\\Documents\\ZIP_COUNTY_032017.xlsx"; var excelApplication = new Excel.Application(); excelApplication.Visible = true; var workbooks = excelApplication.Workbooks; var workbook = workbooks.Open(mySheet); } catch (Exception) { throw; } A: The moving the Visible = true line below the workbooks.Open line worked. I'm not sure why this machine is the only one having trouble with the code in this order, but I'm glad it worked.
stackoverflow
{ "language": "en", "length": 178, "provenance": "stackexchange_0000F.jsonl.gz:875729", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44575499" }
750bd2eb9c768611d2859160313c69495d5a50c8
Stackoverflow Stackexchange Q: Java - Token flow OAuth 2 E2E with code I'm New to security & JAVA and I need to implement token follow of OAuth2, this is the exact flow which I need to implement (if there is some library which can help it's great ) http://tutorials.jenkov.com/oauth2/authorization-code-request-response.html How can I achieve it with JAVA, I want to use some library that provide this functionality. the token flow should be against the UAA but any other similar example will be very helpful. i've found this example but not sure how to use/test it E2E with UAA Postman will be very helpful to simulate it... https://developers.google.com/api-client-library/java/google-oauth-java-client/oauth2 UAA context https://github.com/cloudfoundry/uaa A: I would suggest you Spring as the most popular framework for building web apps in Java. It has Spring Security module that can facilitate developing OAuth 2.0 clients as well as resource servers, as shown here or here.
Q: Java - Token flow OAuth 2 E2E with code I'm New to security & JAVA and I need to implement token follow of OAuth2, this is the exact flow which I need to implement (if there is some library which can help it's great ) http://tutorials.jenkov.com/oauth2/authorization-code-request-response.html How can I achieve it with JAVA, I want to use some library that provide this functionality. the token flow should be against the UAA but any other similar example will be very helpful. i've found this example but not sure how to use/test it E2E with UAA Postman will be very helpful to simulate it... https://developers.google.com/api-client-library/java/google-oauth-java-client/oauth2 UAA context https://github.com/cloudfoundry/uaa A: I would suggest you Spring as the most popular framework for building web apps in Java. It has Spring Security module that can facilitate developing OAuth 2.0 clients as well as resource servers, as shown here or here. A: For a detailed explanation of the OAuth 2.0 flow, visit RFC 6749 Specification. Regarding a step by step solution, you ought to see some tutorials such as this article explaining how to create a Spring REST API using OAuth 2.0. This article goes through code as well as creating Postman requests. With regards to mocking/tests, I've previously created a test suite for the OAuth 2.0 using TestNG and Mockito. The more you develop and research, the more you shall find ways of improving or rather change the way you design your code. That said if you really want to abide by the OAuth 2.0 flow, you should properly understand the flow (which can be relatively vague at times) in the RFC 6749 link. A: Here is the Google API clinet library sample. Try this if it helps public class ServletSample extends AbstractAuthorizationCodeServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // do stuff } @Override protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException { GenericUrl url = new GenericUrl(req.getRequestURL().toString()); url.setRawPath("/oauth2callback"); return url.build(); } @Override protected AuthorizationCodeFlow initializeFlow() throws IOException { return new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), new NetHttpTransport(), new JacksonFactory(), new GenericUrl("https://server.example.com/token"), new BasicAuthentication("s6BhdRkqt3", "7Fjfp0ZBr1KtDRbnfVdmIw"), "s6BhdRkqt3", "https://server.example.com/authorize").setCredentialDataStore( StoredCredential.getDefaultDataStore( new FileDataStoreFactory(new File("datastoredir")))) .build(); } @Override protected String getUserId(HttpServletRequest req) throws ServletException, IOException { // return user ID } } public class ServletCallbackSample extends AbstractAuthorizationCodeCallbackServlet { @Override protected void onSuccess(HttpServletRequest req, HttpServletResponse resp, Credential credential) throws ServletException, IOException { resp.sendRedirect("/"); } @Override protected void onError( HttpServletRequest req, HttpServletResponse resp, AuthorizationCodeResponseUrl errorResponse) throws ServletException, IOException { // handle error } @Override protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException { GenericUrl url = new GenericUrl(req.getRequestURL().toString()); url.setRawPath("/oauth2callback"); return url.build(); } @Override protected AuthorizationCodeFlow initializeFlow() throws IOException { return new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), new NetHttpTransport(), new JacksonFactory(), new GenericUrl("https://server.example.com/token"), new BasicAuthentication("s6BhdRkqt3", "7Fjfp0ZBr1KtDRbnfVdmIw"), "s6BhdRkqt3", "https://server.example.com/authorize").setCredentialDataStore( StoredCredential.getDefaultDataStore( new FileDataStoreFactory(new File("datastoredir")))) .build(); } @Override protected String getUserId(HttpServletRequest req) throws ServletException, IOException { // return user ID } } A: https://github.com/spring-projects/spring-security-oauth/tree/master/samples/oauth2 contains sample code for performing oauth2 using Spring Security.
stackoverflow
{ "language": "en", "length": 474, "provenance": "stackexchange_0000F.jsonl.gz:875746", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44575555" }
88eacb8d716f1e2dff1d70fd270c3c3589a4f637
Stackoverflow Stackexchange Q: I need to include all my function in eventloop? If i have a event loop and async function: # asyncio_coroutine_forever.py import asyncio async def hello_world(): print('Hello World') await good_evening() async def good_evening(): print('Good Evening') loop = asyncio.get_event_loop() try: loop.run_until_complete(hello_world()) loop.run_forever() finally: print('closing event loop') loop.close() The function hellp_world, is called by eventloop. The second function good_evening, is in the same eventloop or not? Do I have to include the second function in the loop or just the first one? If i use the example, the second use loop and switch the context? A: * *Yes, run_until_complete will execute your hello_world future until it returns or fails (it will also block your thread in the process). *You don't have to include the second function unless you want to schedule it by itself. run_until_complete will run a future until it's finished but, it will also cause the event loop to run so if you schedule a future it will run before the function passed to run_util_complete.
Q: I need to include all my function in eventloop? If i have a event loop and async function: # asyncio_coroutine_forever.py import asyncio async def hello_world(): print('Hello World') await good_evening() async def good_evening(): print('Good Evening') loop = asyncio.get_event_loop() try: loop.run_until_complete(hello_world()) loop.run_forever() finally: print('closing event loop') loop.close() The function hellp_world, is called by eventloop. The second function good_evening, is in the same eventloop or not? Do I have to include the second function in the loop or just the first one? If i use the example, the second use loop and switch the context? A: * *Yes, run_until_complete will execute your hello_world future until it returns or fails (it will also block your thread in the process). *You don't have to include the second function unless you want to schedule it by itself. run_until_complete will run a future until it's finished but, it will also cause the event loop to run so if you schedule a future it will run before the function passed to run_util_complete.
stackoverflow
{ "language": "en", "length": 165, "provenance": "stackexchange_0000F.jsonl.gz:875750", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44575563" }
a558549dade8f425bdc644db7dfda95217a07de1
Stackoverflow Stackexchange Q: How do I encircle different data sets in scatter plot? How do I encircle different data sets in scatter plot? What I'm looking for is something like this: Also, how do I thereafter fill in the circle with a (shaded) colour? A: You may get the path that incoporates all points via a convex hull scipy.spatial.ConvexHull. import matplotlib.pyplot as plt import numpy as np; np.random.seed(1) from scipy.spatial import ConvexHull x1, y1 = np.random.normal(loc=5, scale=2, size=(2,15)) x2, y2 = np.random.normal(loc=8, scale=2.5, size=(2,13)) plt.scatter(x1, y1) plt.scatter(x2, y2) def encircle(x,y, ax=None, **kw): if not ax: ax=plt.gca() p = np.c_[x,y] hull = ConvexHull(p) poly = plt.Polygon(p[hull.vertices,:], **kw) ax.add_patch(poly) encircle(x1, y1, ec="k", fc="gold", alpha=0.2) encircle(x2, y2, ec="orange", fc="none") plt.show() Another option is to draw a circle around the mean of the point cloud. import matplotlib.pyplot as plt import numpy as np; np.random.seed(1) from scipy.spatial import ConvexHull x1, y1 = np.random.normal(loc=5, scale=2, size=(2,15)) x2, y2 = np.random.normal(loc=8, scale=2.5, size=(2,13)) plt.scatter(x1, y1) plt.scatter(x2, y2) def encircle2(x,y, ax=None, **kw): if not ax: ax=plt.gca() p = np.c_[x,y] mean = np.mean(p, axis=0) d = p-mean r = np.max(np.sqrt(d[:,0]**2+d[:,1]**2 )) circ = plt.Circle(mean, radius=1.05*r,**kw) ax.add_patch(circ) encircle2(x1, y1, ec="k", fc="gold", alpha=0.2) encircle2(x2, y2, ec="orange", fc="none") plt.gca().relim() plt.gca().autoscale_view() plt.show()
Q: How do I encircle different data sets in scatter plot? How do I encircle different data sets in scatter plot? What I'm looking for is something like this: Also, how do I thereafter fill in the circle with a (shaded) colour? A: You may get the path that incoporates all points via a convex hull scipy.spatial.ConvexHull. import matplotlib.pyplot as plt import numpy as np; np.random.seed(1) from scipy.spatial import ConvexHull x1, y1 = np.random.normal(loc=5, scale=2, size=(2,15)) x2, y2 = np.random.normal(loc=8, scale=2.5, size=(2,13)) plt.scatter(x1, y1) plt.scatter(x2, y2) def encircle(x,y, ax=None, **kw): if not ax: ax=plt.gca() p = np.c_[x,y] hull = ConvexHull(p) poly = plt.Polygon(p[hull.vertices,:], **kw) ax.add_patch(poly) encircle(x1, y1, ec="k", fc="gold", alpha=0.2) encircle(x2, y2, ec="orange", fc="none") plt.show() Another option is to draw a circle around the mean of the point cloud. import matplotlib.pyplot as plt import numpy as np; np.random.seed(1) from scipy.spatial import ConvexHull x1, y1 = np.random.normal(loc=5, scale=2, size=(2,15)) x2, y2 = np.random.normal(loc=8, scale=2.5, size=(2,13)) plt.scatter(x1, y1) plt.scatter(x2, y2) def encircle2(x,y, ax=None, **kw): if not ax: ax=plt.gca() p = np.c_[x,y] mean = np.mean(p, axis=0) d = p-mean r = np.max(np.sqrt(d[:,0]**2+d[:,1]**2 )) circ = plt.Circle(mean, radius=1.05*r,**kw) ax.add_patch(circ) encircle2(x1, y1, ec="k", fc="gold", alpha=0.2) encircle2(x2, y2, ec="orange", fc="none") plt.gca().relim() plt.gca().autoscale_view() plt.show()
stackoverflow
{ "language": "en", "length": 197, "provenance": "stackexchange_0000F.jsonl.gz:875782", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44575681" }
7b7ef125bbf6a39669a0a85a6f14226e496f4f3d
Stackoverflow Stackexchange Q: React JS toggle/ adding a class on hover I'm using the animate.css library with React and trying to set up a element (button) to pulse when hovered over. Tried to look through the docs and here but can't find a way to achieve this simple task. If anyone has achieved this or found a reference would greatly be appreciated. class App extends Component { constructor(props) { super(props); this.handleHover = this.handleHover.bind(this); } handleHover(){ this.setState({ isHovered: !this.state.isHovered }); } render() { const btnClass = this.state.isHovered ? "pulse animated" : ""; return ( <div> <button className={btnClass} onMouseEnter={this.state.handleHover} onMouseLeave={this.state.handleHover}>Test</button> </div> ); } } export default App; A: You can use the onMouseEnter and onMouseLeave events on the component and toggle the class accordingly. constructor(){ super(); this.state = { isHovered: false }; this.handleHover = this.handleHover.bind(this); } handleHover(){ this.setState(prevState => ({ isHovered: !prevState.isHovered })); } render(){ const btnClass = this.state.isHovered ? "pulse animated" : ""; return <button className={btnClass} onMouseEnter={this.handleHover} onMouseLeave={this.handleHover}></button> } Update 05/07/19: Hooks import React, { useState } from 'react'; export default function Component () { const [hovered, setHovered] = useState(false); const toggleHover = () => setHovered(!hovered); return ( <button className={hovered ? 'pulse animated' : ''} onMouseEnter={toggleHover} onMouseLeave={toggleHover} > </button> ) }
Q: React JS toggle/ adding a class on hover I'm using the animate.css library with React and trying to set up a element (button) to pulse when hovered over. Tried to look through the docs and here but can't find a way to achieve this simple task. If anyone has achieved this or found a reference would greatly be appreciated. class App extends Component { constructor(props) { super(props); this.handleHover = this.handleHover.bind(this); } handleHover(){ this.setState({ isHovered: !this.state.isHovered }); } render() { const btnClass = this.state.isHovered ? "pulse animated" : ""; return ( <div> <button className={btnClass} onMouseEnter={this.state.handleHover} onMouseLeave={this.state.handleHover}>Test</button> </div> ); } } export default App; A: You can use the onMouseEnter and onMouseLeave events on the component and toggle the class accordingly. constructor(){ super(); this.state = { isHovered: false }; this.handleHover = this.handleHover.bind(this); } handleHover(){ this.setState(prevState => ({ isHovered: !prevState.isHovered })); } render(){ const btnClass = this.state.isHovered ? "pulse animated" : ""; return <button className={btnClass} onMouseEnter={this.handleHover} onMouseLeave={this.handleHover}></button> } Update 05/07/19: Hooks import React, { useState } from 'react'; export default function Component () { const [hovered, setHovered] = useState(false); const toggleHover = () => setHovered(!hovered); return ( <button className={hovered ? 'pulse animated' : ''} onMouseEnter={toggleHover} onMouseLeave={toggleHover} > </button> ) } A: What about using the css :hover property? This worked way better for me by changing my hover class section in the css file to use :hover instead of react. I tried using the above suggestions but react didn't seem fast enough to get it so the state would become wrong if the mouse moved slowly over the button.
stackoverflow
{ "language": "en", "length": 257, "provenance": "stackexchange_0000F.jsonl.gz:875797", "question_score": "18", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44575727" }
bb1a67ea25f9b93d173b700de00a06fbc8cd8eb6
Stackoverflow Stackexchange Q: default timeout for JAX-WS client We are calling web service for which using cxf-codegen-plugin for code generation from WSDL and have configured JAX-WS client in Spring xml as follows: <jaxws:client id="abcApiInterface" serviceClass="abc.api.AbcApi" address="${xyz.abcApi.endpoint}" /> And we have our webservice interface generated by Apache CXF 3.0.3. We are seeing timed-out when calling that service, we have not specified any timeout on client side so just want to know what's the default value for timeout for JAX-WS client? A: Default value is 30 seconds for connection timeout and 60 seconds for receive timeout. See: http://cxf.apache.org/docs/client-http-transport-including-ssl-support.html#ClientHTTPTransport(includingSSLsupport)-Theclientelement
Q: default timeout for JAX-WS client We are calling web service for which using cxf-codegen-plugin for code generation from WSDL and have configured JAX-WS client in Spring xml as follows: <jaxws:client id="abcApiInterface" serviceClass="abc.api.AbcApi" address="${xyz.abcApi.endpoint}" /> And we have our webservice interface generated by Apache CXF 3.0.3. We are seeing timed-out when calling that service, we have not specified any timeout on client side so just want to know what's the default value for timeout for JAX-WS client? A: Default value is 30 seconds for connection timeout and 60 seconds for receive timeout. See: http://cxf.apache.org/docs/client-http-transport-including-ssl-support.html#ClientHTTPTransport(includingSSLsupport)-Theclientelement
stackoverflow
{ "language": "en", "length": 94, "provenance": "stackexchange_0000F.jsonl.gz:875810", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44575772" }
0df05092f69563758fd0ab1430f37f4c6688b3c8
Stackoverflow Stackexchange Q: Jmeter JDBC Connection Configuration Parametrization of Database URL for accessing MySQL Database How to parametrize Database URL under JDBC Connection Configuration? Normal parametrization is not working here. This doesn't work: Database URL: jdbc:mysql://${mysql_hostname}:${mysql_port}/${mysql_database} JDBC Driver Class: com.mysql.jdbc.Driver Username: ${mysql_username} Password: ${mysql_username} A: The point is that JDBC Connection Configuration test element is being initialized before JMeter Variables so if you want to parameterize it you should be doing it a little bit differently to wit: * *Use __P() function where required like: Database URL: jdbc:mysql://${__P(mysql_hostname,)}:${__P(mysql_port,)}/${__P(mysql_database,)} JDBC Driver Class: com.mysql.jdbc.Driver Username: ${__P(mysql_username,)} Password: ${__P(mysql_password,)} The relevant JMeter Properties can be set either in user.properties file like: mysql_hostname=localhost mysql_port=3306 mysql_database=test mysql_username=johndoe mysql_passowrd=secret Or via -J command-line argument like: jmeter -Jmysql_hostname=localhost -Jmysql_port=3306 -Jmysql_database=test -Jmysql_usename=johndoe -Jmysql_password=secret See Apache JMeter Properties Customization Guide for more information on JMeter Properties and ways of setting and overriding them
Q: Jmeter JDBC Connection Configuration Parametrization of Database URL for accessing MySQL Database How to parametrize Database URL under JDBC Connection Configuration? Normal parametrization is not working here. This doesn't work: Database URL: jdbc:mysql://${mysql_hostname}:${mysql_port}/${mysql_database} JDBC Driver Class: com.mysql.jdbc.Driver Username: ${mysql_username} Password: ${mysql_username} A: The point is that JDBC Connection Configuration test element is being initialized before JMeter Variables so if you want to parameterize it you should be doing it a little bit differently to wit: * *Use __P() function where required like: Database URL: jdbc:mysql://${__P(mysql_hostname,)}:${__P(mysql_port,)}/${__P(mysql_database,)} JDBC Driver Class: com.mysql.jdbc.Driver Username: ${__P(mysql_username,)} Password: ${__P(mysql_password,)} The relevant JMeter Properties can be set either in user.properties file like: mysql_hostname=localhost mysql_port=3306 mysql_database=test mysql_username=johndoe mysql_passowrd=secret Or via -J command-line argument like: jmeter -Jmysql_hostname=localhost -Jmysql_port=3306 -Jmysql_database=test -Jmysql_usename=johndoe -Jmysql_password=secret See Apache JMeter Properties Customization Guide for more information on JMeter Properties and ways of setting and overriding them A: in Jmeter (5.1.1) you can use 'User Defined Variables'. Add-> Config Element -> User Defined Variables. A: It really would be nice to be able to have the DB Connection initialize AFTER the JMeter variables. I have a JMeter JMX that calls a DB stored proc. I call the JMX through Jenkins automation. I do the same call on multiple DBs. It would be soooo much easier to call the JMX once from Jenkins and use a CSV file to have it run against the multiple DBs than it would be to have to make the call multiple times in the Jenkins file and pass in a different DB name for each call. Also, when I need to run this against yet another DB, it it a lot easier to add the new DB to a CSV file than it is to add yet another call to the Jenkins file. There are possible workarounds in the Jenkins file, but none work as good or are as simple as being able to set the JDBC connection setting from a CSV file in the JMeter JMX itself.
stackoverflow
{ "language": "en", "length": 328, "provenance": "stackexchange_0000F.jsonl.gz:875816", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44575820" }
162a6239ca6be45cc02a6dc825d4264a5d8d48c7
Stackoverflow Stackexchange Q: Unable to git add env/bin directory after creating virtualenv I am really new to Python and the virtualenv needed to set up a project. I dont know whether the directories generated by virtualenv should be gitignored or staged and committed. I narrowed it down to the myproject/env/bin directory that doesn't seem to want to be staged. After running git add env/bin once I get. [1] 16599 killed git add env/bin And then after running the same git add env/bin again I get. Another git process seems to be running in this repository, e.g. an editor opened by 'git commit'.... There are no other git process running. Thanks for your help! A: After looking through a few other Python/Django repositories on Github, I see that most have add the env/bin, env/include and env/lib directories (generated by virtualenv) to their .gitignore file. I'll take this at face value and move on til I have a better understanding of virtualenv. Thanks!
Q: Unable to git add env/bin directory after creating virtualenv I am really new to Python and the virtualenv needed to set up a project. I dont know whether the directories generated by virtualenv should be gitignored or staged and committed. I narrowed it down to the myproject/env/bin directory that doesn't seem to want to be staged. After running git add env/bin once I get. [1] 16599 killed git add env/bin And then after running the same git add env/bin again I get. Another git process seems to be running in this repository, e.g. an editor opened by 'git commit'.... There are no other git process running. Thanks for your help! A: After looking through a few other Python/Django repositories on Github, I see that most have add the env/bin, env/include and env/lib directories (generated by virtualenv) to their .gitignore file. I'll take this at face value and move on til I have a better understanding of virtualenv. Thanks!
stackoverflow
{ "language": "en", "length": 159, "provenance": "stackexchange_0000F.jsonl.gz:875829", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44575860" }
40904d1c9884f370abcdf9df6a57572122339773
Stackoverflow Stackexchange Q: What is the difference betwee "nuget install" , "Install-Package" and "choco install"? And more specific questions. Do I understand right that: * *"nuget install" installs always to the directory you run it from? *"choco install" installs to special choco's directory and than runs the scripts to spread it in the system? *"nuget install" is just a wrapper for the Install-Package? A: NuGet is a packaging framework that provides packaging for NuGet, PowerShell Modules (PowerShell Gallery), and Chocolatey. PackageManagement (aka OneGet) is a Package Manager Manager (yes, really) that implements Install-Package to work with package managers (called providers) like NuGet, PowerShell Get, and Chocolatey. * *NuGet (the tool, not the framework) is used for development purposes and typically packages software libraries (dlls). *Chocolatey is for Software Deployment and Management and typically packages software, tools, and applications. *Install-Package is an interface to either of those (and more) through providers. NOTE: If you want to interface with Chocolatey in PackageManagement (through Install-Package), use ChocolateyGet for now and wait until the official provider Chocolatey is available. The current is a prototype. If you want more details, please see https://github.com/chocolatey/chocolatey-oneget/issues/5#issuecomment-275404099.
Q: What is the difference betwee "nuget install" , "Install-Package" and "choco install"? And more specific questions. Do I understand right that: * *"nuget install" installs always to the directory you run it from? *"choco install" installs to special choco's directory and than runs the scripts to spread it in the system? *"nuget install" is just a wrapper for the Install-Package? A: NuGet is a packaging framework that provides packaging for NuGet, PowerShell Modules (PowerShell Gallery), and Chocolatey. PackageManagement (aka OneGet) is a Package Manager Manager (yes, really) that implements Install-Package to work with package managers (called providers) like NuGet, PowerShell Get, and Chocolatey. * *NuGet (the tool, not the framework) is used for development purposes and typically packages software libraries (dlls). *Chocolatey is for Software Deployment and Management and typically packages software, tools, and applications. *Install-Package is an interface to either of those (and more) through providers. NOTE: If you want to interface with Chocolatey in PackageManagement (through Install-Package), use ChocolateyGet for now and wait until the official provider Chocolatey is available. The current is a prototype. If you want more details, please see https://github.com/chocolatey/chocolatey-oneget/issues/5#issuecomment-275404099. A: I believe Install-package may act as a wrapper for nuget (basically), but there can be other package providers (and there are), so it can not only call nuget. C:\> get-packageprovider Name Version ---- ------- msi 3.0.0.0 msu 3.0.0.0 NuGet 2.8.5.207 PowerShellGet 1.0.0.1 Programs 3.0.0.0 Choco is just another package provider. you could use it standalone or using the install-package. you can install choco with something like install-packageprovider chocolatey
stackoverflow
{ "language": "en", "length": 255, "provenance": "stackexchange_0000F.jsonl.gz:875851", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44575919" }
00a9517adf2286d145d6f3b961230fa6f7c7c620
Stackoverflow Stackexchange Q: WebSocket connection failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED I am new to WebRTC and WebSockets and was following this tutorial to create a WebRTC demo project, but I am unable to create a WebSocket connection. I have followed the same steps as mentioned in the project. His project is running on port 8080 and he mentioned ws://localhost:9090. My project is running on port 8081, but I copied his URL ws://localhost:9090 because I didn't know the significance of 9090 and I received this error and my server is node.js. i changed local host to 8081 as well but then i am getting hand shake error. WebSocket connection to 'ws://localhost:9090/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED. A: Chrome doesn't allow unsecure websocket (ws) connections to localhost (only wss, so you should setup a TLS certificate for your local web/websocket server). However the same should work fine with Firefox.
Q: WebSocket connection failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED I am new to WebRTC and WebSockets and was following this tutorial to create a WebRTC demo project, but I am unable to create a WebSocket connection. I have followed the same steps as mentioned in the project. His project is running on port 8080 and he mentioned ws://localhost:9090. My project is running on port 8081, but I copied his URL ws://localhost:9090 because I didn't know the significance of 9090 and I received this error and my server is node.js. i changed local host to 8081 as well but then i am getting hand shake error. WebSocket connection to 'ws://localhost:9090/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED. A: Chrome doesn't allow unsecure websocket (ws) connections to localhost (only wss, so you should setup a TLS certificate for your local web/websocket server). However the same should work fine with Firefox. A: Usually WebRTC requires a secure connection (that is https). The error you have got is due to TLS/SSL certificates occupied, may be they are not properly configured in your project. Provide a valid TLS/SSL certificate and also configure it correctly in project, then it will work without the above error. A: try to change the port to 8080 const ws = new WebSocket('ws://localhost:8080/chat') A: I guess this is a generic websocket issue. Change the url to a dynamic name using the built-in location.host variable and change the protocol to secure websocket wss if you have set-up the TLS: const ws = new WebSocket("wss://" + location.host + "/") A: Port 9090 is used by reactotron. Probably you are using it in your project and your app cannot connect with reactotron because it is closed. Just open reactotron and the error will disappear. A: also you could easily change the mappings of IP addresses to host names, on windows go to C:\Windows\System32\drivers\etc\hosts and uncomment this line 127.0.0.1 localhost save and restart. A: You need to use ws://yourIp:9090/, where yourIP is like 192.168.?.?. A: WebSocket connection to 'ws://localhost:8080/' failed Must ensure server file is running I git this above problem A: maybe you forgot to start websocket server, check it again, with configuration in my project, run: php artisan websocket:init
stackoverflow
{ "language": "en", "length": 365, "provenance": "stackexchange_0000F.jsonl.gz:875866", "question_score": "41", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44575978" }
7d2a3fb2bc98fcb2ff250b6fd12f78b206b7ac48
Stackoverflow Stackexchange Q: Send empty body in POST request in Retrofit My api expects an empty json body ({ }) when making post requests. How do I set this up in Retrofit and Jackson? I tried passing null, and empty string, and "{}" but could not get this to work. @POST(my/url) Call<MyResponse> createPostRequest(@Body Object empty); How can I set an empty JSON body? A: An empty Object does it for Kotlin: interface ApiService { @POST("your.url") fun createPostRequest(@Body body: Any = Object()): Call<YourResponseType> }
Q: Send empty body in POST request in Retrofit My api expects an empty json body ({ }) when making post requests. How do I set this up in Retrofit and Jackson? I tried passing null, and empty string, and "{}" but could not get this to work. @POST(my/url) Call<MyResponse> createPostRequest(@Body Object empty); How can I set an empty JSON body? A: An empty Object does it for Kotlin: interface ApiService { @POST("your.url") fun createPostRequest(@Body body: Any = Object()): Call<YourResponseType> } A: try this . It worked for me now. @POST(my/url) Call<MyResponse> createPostRequest(@Body Hashmap ); while using this method pass new HasMap as paremater apiservice.createPostRequest(new HashMap()) A: Empty class will do the trick: class EmptyRequest { public static final EmptyRequest INSTANCE = new EmptyRequest(); } interface My Service { @POST("my/url") Call<MyResponse> createPostRequest(@Body EmptyRequest request); } myService.createPostRequest(EmptyRequest.INSTANCE); A: Old question, but I found a more suitable solution by using a okhttp3.Interceptor that adds an empty body if no body is present. This solution does not require you to add an extra parameter for an empty @Body. Example: Interceptor interceptor = chain -> { Request oldRequest = chain.request(); Request.Builder newRequest = chain.request().newBuilder(); if ("POST".equals(oldRequest.method()) && (oldRequest.body() == null || oldRequest.body().contentLength() <= 0)) { newRequest.post(RequestBody.create(MediaType.parse("application/json"), "{}")); } return chain.proceed(newRequest.build()); }; You can then create an instance of your service like so: OkHttpClient.Builder client = new OkHttpClient.Builder(); client.addInterceptor(interceptor); Retrofit retrofit = new Retrofit.Builder() .baseUrl("YourURL") .client(client.build()) .build(); MyService service = retrofit.create(MyService.class); A: use: @POST("something") Call<MyResponse> createPostRequest(@Body Object o); then call: createPostRequest(new Object()) A: Heres the answer in Kotlin: @POST("CountriesList") fun getCountriesNew(@Body body: HashMap<String, String>) : Call<CountryModel> val call = RetrofitClient.apiInterface.getCountriesNew(HashMap())
stackoverflow
{ "language": "en", "length": 265, "provenance": "stackexchange_0000F.jsonl.gz:875891", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44576046" }
7c994c19ab0bc058875b982ebbc08551a506ef0f
Stackoverflow Stackexchange Q: Force child class to override parent's methods Suppose I have a base class with unimplemented methods as follows: class Polygon(): def __init__(self): pass def perimeter(self): pass def area(self): pass Now, let's say one of my colleagues uses the Polygon class to create a subclass as follows: import math class Circle(Polygon): def __init__(self, radius): self.radius = radius def perimeter(self): return 2 * math.pi * self.radius (H/Sh)e has forgotten to implement the area() method. How can I force the subclass to implement the parent's area() method? A: You can raise NotImplementedError exception in base class method. class Polygon: def area(self): raise NotImplementedError Also you can use @abc.abstractmethod, but then you need to declare metaclass to be abc.ABCMeta, which would make your class abstract. More about abc module
Q: Force child class to override parent's methods Suppose I have a base class with unimplemented methods as follows: class Polygon(): def __init__(self): pass def perimeter(self): pass def area(self): pass Now, let's say one of my colleagues uses the Polygon class to create a subclass as follows: import math class Circle(Polygon): def __init__(self, radius): self.radius = radius def perimeter(self): return 2 * math.pi * self.radius (H/Sh)e has forgotten to implement the area() method. How can I force the subclass to implement the parent's area() method? A: You can raise NotImplementedError exception in base class method. class Polygon: def area(self): raise NotImplementedError Also you can use @abc.abstractmethod, but then you need to declare metaclass to be abc.ABCMeta, which would make your class abstract. More about abc module A: That's exactly what NotImplementedError are used for :) In your base class def area(self): raise NotImplementedError("Hey, Don't forget to implement the area!") A: this could be your parent class: class Polygon(): def __init__(self): raise NotImplementedError def perimeter(self): raise NotImplementedError def area(self): raise NotImplementedError although the problem will be spotted at runtime only, when one of the instances of the child classes tries to call one of these methods. a different version is to use abc.abstractmethod. from abc import ABC, abstractmethod import math class Polygon(ABC): @abstractmethod def __init__(self): pass @abstractmethod def perimeter(self): pass @abstractmethod def area(self): pass class Circle(Polygon): def __init__(self, radius): self.radius = radius def perimeter(self): return 2 * math.pi * self.radius # def area(self): # return math.pi * self.radius**2 c = Circle(9.0) # TypeError: Can't instantiate abstract class Circle # with abstract methods area you will not be able to instantiate a Circle without it having all the methods implemented. this is the python 3 syntax; in python 2 you'd need to class Polygon(object): __metaclass__ = ABCMeta also note that for the binary special functions __eq__(), __lt__(), __add__(), ... it is better to return NotImplemented instead of raising NotImplementedError.
stackoverflow
{ "language": "en", "length": 317, "provenance": "stackexchange_0000F.jsonl.gz:875926", "question_score": "83", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44576167" }
bfa2f1b3a084dfb982920dd693f3b662bc747be2
Stackoverflow Stackexchange Q: Yocto: : does bitbake cleanall ,cleans dependencies as well bitbake cleanall Removes all output files, shared state cache, and downloaded source files for a target It is not clear or documented if it cleans all build time dependencies as well A: Please read the mega-manual section do_cleanall . do_cleanall removes: * *all output files *shared state (sstate) cache *and downloaded source files for a target (i.e. the contents of DL_DIR). You can run this task using BitBake as follows: $ bitbake -c cleanall <recipe-name> If recipe name is not passed to cleanall task it does not work.
Q: Yocto: : does bitbake cleanall ,cleans dependencies as well bitbake cleanall Removes all output files, shared state cache, and downloaded source files for a target It is not clear or documented if it cleans all build time dependencies as well A: Please read the mega-manual section do_cleanall . do_cleanall removes: * *all output files *shared state (sstate) cache *and downloaded source files for a target (i.e. the contents of DL_DIR). You can run this task using BitBake as follows: $ bitbake -c cleanall <recipe-name> If recipe name is not passed to cleanall task it does not work. A: Removes all output files, shared state (sstate) cache, and downloaded source files for a target (i.e. the contents of DL_DIR). Essentially, the do_cleanall task is identical to the do_cleansstate task with the added removal of downloaded source files. You can run this task using BitBake as follows: $ bitbake -c cleanall recipe Typically, you would not normally use the cleanall task. Do so only if you want to start fresh with the do_fetch task. A: If you want to clean everything do, bitbake world -c cleanall --continue The --continue will ignore any dependency errors while cleaning. Continue as much as possible after an error. A: No, cleanall does not clean dependencies. eg bitbake -c cleanall core-image-minimal only removes the output of that named recipe. What i usually do to clean "everything" is running cleanall on the receipe "world": bitbake -c cleanall world If that fails because of unresolvable packages like that: ERROR: Nothing PROVIDES 'sg3-utils' (but /home/blubb/meta-freescale/recipes-devtools/utp-com/utp-com_git.bb DEPENDS on or otherwise requires it). I just add the packages temporary to the ASSUME_PROVIDED variable like this : bitbake -c cleanall world --ignore-deps=python-nativedtc-native --ignore-deps=sg3-utils If nothing provides this packages it is unlikely that they where ever build. A: Other folks have already answered that bitbake does not automatically clean dependencies, but you can create an Inter-task dependency (https://www.yoctoproject.org/docs/3.1/bitbake-user-manual/bitbake-user-manual.html#inter-task-dependencies) to clean your dependencies if needed by adding a command to the recipe: do_task[depends] = "recipe:task" We've extended bitbake to build native recipes and automatically run unit tests during a build. In that case we need to clean the native recipe when cleaning the target so you could add: do_clean[depends] = "${PN}-native:do_clean" do_cleanall[depends] = "${PN}-native:do_cleanall" do_cleansstate[depends] = "${PN}-native:do_cleansstate" That solution falls a bit short because the native recipes will attempt to clean ${PN}-native-native, so you'll need a conditional to not apply if it's already native: do_clean[depends] += "${@'' if bb.data.inherits_class('native', d) else '${PN}-native:do_clean'}" do_cleanall[depends] += "${@'' if bb.data.inherits_class('native', d) else '${PN}-native:do_cleanall'}" do_cleansstate[depends] += "${@'' if bb.data.inherits_class('native', d) else '${PN}-native:do_cleansstate'}"
stackoverflow
{ "language": "en", "length": 424, "provenance": "stackexchange_0000F.jsonl.gz:875932", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44576185" }
f117a1379cc4991f7287f62bdcf2e23eef7b2b34
Stackoverflow Stackexchange Q: Rails geocoder - Google Geocoding API error: over query limit - PRODUCTION ONLY geocoder gem has stopped working solely in the production environment. It works perfect and as expected in development. I am on Ubuntu 16.04 using ruby 2.3.1 and rails 4.2.6 When I run ModelName.near("zip_code", "radius") in development from the rails console, I am returned the associated rows as expected. When I run the same command in the server, it returns Google Geocoding API error: over query limit. UPDATE lat and long are not being saved in the production environment, but are being saved in development. A: I had a similar problem. Adding my google api key to config/initializers/geocoder.rb resolved my issue.
Q: Rails geocoder - Google Geocoding API error: over query limit - PRODUCTION ONLY geocoder gem has stopped working solely in the production environment. It works perfect and as expected in development. I am on Ubuntu 16.04 using ruby 2.3.1 and rails 4.2.6 When I run ModelName.near("zip_code", "radius") in development from the rails console, I am returned the associated rows as expected. When I run the same command in the server, it returns Google Geocoding API error: over query limit. UPDATE lat and long are not being saved in the production environment, but are being saved in development. A: I had a similar problem. Adding my google api key to config/initializers/geocoder.rb resolved my issue. A: Adding a key for GeoCoder resolves this issue: Create a file config/initializers/geocoder.rb and paste below code: Geocoder.configure( api_key: 'YOUR_API_KEY' ) You need to replace "YOUR_API_KEY" with a valid Google Geocoder API key. Status codes are available at https://developers.google.com/maps/documentation/geocoding/intro#StatusCodes
stackoverflow
{ "language": "en", "length": 153, "provenance": "stackexchange_0000F.jsonl.gz:876002", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44576403" }
205db53e96ca03ce70095912320a5fd4dcd8a6f8
Stackoverflow Stackexchange Q: Is Weissman score for compression valid? Is there is really something like weissmann score given as per the efficiency to compress something as shown in "Silicon Valley" TV Series? A: The show sparked the creation of an official score for lossless compression called the Weissman Score which was developed by a professor at Stanford as well as a graduate student. Here is some more reading that can be done on it. See: https://en.wikipedia.org/wiki/Weissman_score and http://spectrum.ieee.org/view-from-the-valley/computing/software/a-madefortv-compression-metric-moves-to-the-real-world
Q: Is Weissman score for compression valid? Is there is really something like weissmann score given as per the efficiency to compress something as shown in "Silicon Valley" TV Series? A: The show sparked the creation of an official score for lossless compression called the Weissman Score which was developed by a professor at Stanford as well as a graduate student. Here is some more reading that can be done on it. See: https://en.wikipedia.org/wiki/Weissman_score and http://spectrum.ieee.org/view-from-the-valley/computing/software/a-madefortv-compression-metric-moves-to-the-real-world
stackoverflow
{ "language": "en", "length": 76, "provenance": "stackexchange_0000F.jsonl.gz:876003", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44576404" }
2629c3f93ba0833dfabf9921af311129fb91e057
Stackoverflow Stackexchange Q: How to get file attachments from nested emails using EWS API I am trying to get all the attachments from a email message that has email messages as attachments. I need to somehow recurse through the attachments to find all the fileAttachments. For example I have an email that has 2 attachments. First attachment is a file. Second is another email. This second email also has 2 attachments. First attachment is a file. Second is third email. This third email only has one attachment which is a file. So i need to wind up with 3 file Attachments but cant figure out how to loop through this. Doug A: Here is a recursive solution: Private Function GetFileAttachments(aItem As Item) As IEnumerable(Of FileAttachment) Dim result = New List(Of FileAttachment) For Each att In aItem.Attachments If TypeOf att Is ItemAttachment Then Dim itemAttachment = CType(att, ItemAttachment) itemAttachment.Load() result.AddRange(GetFileAttachments(itemAttachment.Item)) Else result.Add(att) End If Next Return result End Function
Q: How to get file attachments from nested emails using EWS API I am trying to get all the attachments from a email message that has email messages as attachments. I need to somehow recurse through the attachments to find all the fileAttachments. For example I have an email that has 2 attachments. First attachment is a file. Second is another email. This second email also has 2 attachments. First attachment is a file. Second is third email. This third email only has one attachment which is a file. So i need to wind up with 3 file Attachments but cant figure out how to loop through this. Doug A: Here is a recursive solution: Private Function GetFileAttachments(aItem As Item) As IEnumerable(Of FileAttachment) Dim result = New List(Of FileAttachment) For Each att In aItem.Attachments If TypeOf att Is ItemAttachment Then Dim itemAttachment = CType(att, ItemAttachment) itemAttachment.Load() result.AddRange(GetFileAttachments(itemAttachment.Item)) Else result.Add(att) End If Next Return result End Function
stackoverflow
{ "language": "en", "length": 156, "provenance": "stackexchange_0000F.jsonl.gz:876008", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44576415" }
ef89f7d69dced0927c0f46ecd06dca33dcb0de37
Stackoverflow Stackexchange Q: Define functions at the top or at the bottom of a script? In Python all functions must be defined before they can be accessed. This leaves two choices for writing a script: * *Define the functions at the top: def f1(): # something def f2(): # something # Call f1 f1() # Call f2 f2() *Define the functions at the bottom: def main(): # Call f1 f1() # Call f2 f2() def f1(): # something def f2(): # something # Call main() at the bottom, after all the functions have been defined. if __name__ == '__main__': main() Coming from Fortran, I was used to defined functions at the bottom, but I've seen numerous Python scripts where defining them at the top seems to be prefered. Is one of these options more Pythonic/recommended than the other? If so, why? (I am not asking for an "opinion", I'm asking for a well-argumented reason as to why either one of these is preferred, or if they are both considered equally valid.)
Q: Define functions at the top or at the bottom of a script? In Python all functions must be defined before they can be accessed. This leaves two choices for writing a script: * *Define the functions at the top: def f1(): # something def f2(): # something # Call f1 f1() # Call f2 f2() *Define the functions at the bottom: def main(): # Call f1 f1() # Call f2 f2() def f1(): # something def f2(): # something # Call main() at the bottom, after all the functions have been defined. if __name__ == '__main__': main() Coming from Fortran, I was used to defined functions at the bottom, but I've seen numerous Python scripts where defining them at the top seems to be prefered. Is one of these options more Pythonic/recommended than the other? If so, why? (I am not asking for an "opinion", I'm asking for a well-argumented reason as to why either one of these is preferred, or if they are both considered equally valid.)
stackoverflow
{ "language": "en", "length": 169, "provenance": "stackexchange_0000F.jsonl.gz:876045", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44576539" }