id
stringlengths
40
40
text
stringlengths
29
2.03k
original_text
stringlengths
3
154k
subdomain
stringclasses
20 values
metadata
dict
65f5ccc90929f07f9134185f7f644b5badbfd60f
Stackoverflow Stackexchange Q: Federated Identity Management: ADFS vs OpenID I'm new to Federated Identity Management. I'm trying to understand the differences between the authentication protocols and concepts. I understood the difference/relationship between OpenID and OAuth. However, I'm still confused about the differences between ADFS, OpenID, IDaaS and Claim-based authentication concept. I'm looking for high level explanation. Any help is highly appreciated. A: Just to expand. When you said, OpenID did you mean that or did you mean OpenID Connect? They are two different protocols and OpenID is very rarely used these days. ADFS 4.0 (Server 2016) is the only ADFS that has full OpenID Connect / OAuth support (i.e. all four profiles). Only ADFS 4.0 can use LDAP v3.0 and above for authentication. On earlier versions you have to use AD. Also SAML and WS-Fed normally use SAML tokens not JWT ones. Just to point out, ADFS also supports WS-Federation.
Q: Federated Identity Management: ADFS vs OpenID I'm new to Federated Identity Management. I'm trying to understand the differences between the authentication protocols and concepts. I understood the difference/relationship between OpenID and OAuth. However, I'm still confused about the differences between ADFS, OpenID, IDaaS and Claim-based authentication concept. I'm looking for high level explanation. Any help is highly appreciated. A: Just to expand. When you said, OpenID did you mean that or did you mean OpenID Connect? They are two different protocols and OpenID is very rarely used these days. ADFS 4.0 (Server 2016) is the only ADFS that has full OpenID Connect / OAuth support (i.e. all four profiles). Only ADFS 4.0 can use LDAP v3.0 and above for authentication. On earlier versions you have to use AD. Also SAML and WS-Fed normally use SAML tokens not JWT ones. Just to point out, ADFS also supports WS-Federation. A: Well, let me try to explain this: * *OAuth 2 - Protocol for delegated authorization; *OpenID Connect (OIDC) - Protocol built over OAuth2 that allows delegated authentication; Instead of my App implementing the authentication, the authentication is realized by a third party. *Active Directory Federation Services (ADFS) is not a protocol or framework. Instead, it is a software developed by Microsoft that enables single sign-on and Federation for Windows networks. *Claim-based is the foundation of SAML and OIDC JWT tokens. These tokens have assertions about the subject (entity authenticated) and are usually signed. Summarizing: * *OIDC and OAuth 2.0 are protocols. They don't dictate which or how your Federation will work. OAuth2 takes place at the authorization stage and OpenID Connect at the authentication and federation phases. With the public key exposed by the OpenID Connect Provider, any company can validate the ID Token and, therefore, be part of the Federation. *ADFS is a product that allows Federation based on SAML protocol (secure but heavier than OIDC) *Claim-based is used both in OIDC and SAML protocols. The tokens have information that the issuers claim to be correct about some entity. If you rely on a token issued by a third party, you become a relying party.
stackoverflow
{ "language": "en", "length": 355, "provenance": "stackexchange_0000F.jsonl.gz:883324", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44599450" }
cb6d3044c8fe7c66fe9a725218335dffefc0748e
Stackoverflow Stackexchange Q: Eloquent Count nested relationships with nested eager loading You must have seen the following feature (on facebook), a post with some comments, each comment has a like counter. https://img4.hostingpics.net/pics/67853820170616003640LaravelNewsAccueil.png In laravel it would be something like * *Post hasMany Comment *Comment belongsTo Post *CommentLike belongsTo User *CommentLike belongsTo Comment *Comment hasMany CommentLike So, now I want to get 10 posts with their comments, with the like counter per comment. Post::with('comments')->withCount('comments.likes')->take(10)->get(); This does not work at all. Post::with('comments')->withCount('comments')->take(10)->get(); This counts all comments for each post, I want to count all likes per comment on each post. A: Try this Post::with(['comments' => function($query){ $query->withCount('likes'); }])->take(10)->get();
Q: Eloquent Count nested relationships with nested eager loading You must have seen the following feature (on facebook), a post with some comments, each comment has a like counter. https://img4.hostingpics.net/pics/67853820170616003640LaravelNewsAccueil.png In laravel it would be something like * *Post hasMany Comment *Comment belongsTo Post *CommentLike belongsTo User *CommentLike belongsTo Comment *Comment hasMany CommentLike So, now I want to get 10 posts with their comments, with the like counter per comment. Post::with('comments')->withCount('comments.likes')->take(10)->get(); This does not work at all. Post::with('comments')->withCount('comments')->take(10)->get(); This counts all comments for each post, I want to count all likes per comment on each post. A: Try this Post::with(['comments' => function($query){ $query->withCount('likes'); }])->take(10)->get(); A: I'm making an assumption CommentLike represents a comment_likes table Post::with('comments' => function($query){ $query->select('comment_likes.*') ->join('comments', 'comments.id', '=', 'comment_likes.comment_id') ->groupBy('comments.id') ->havingRaw('sum(comment_likes.id) as likes') }])->take(10)->get();
stackoverflow
{ "language": "en", "length": 127, "provenance": "stackexchange_0000F.jsonl.gz:883350", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44599550" }
26e3e89daa62f6a2e9c0995564726a42a623fa54
Stackoverflow Stackexchange Q: Laravel eloquent model query for `not null` I've been using Laravel for a project and using the Eloquent models to grab the model instances I need. However, it doesn't look like there's a way to query for not null values. https://laravel.com/docs/5.4/eloquent#retrieving-models Is there a way to do something like this, where I want to get all Flight models where the ticket_id is not null? $flight = App\Flight::where('ticket_id', '!=', null); A: Try this $flight = App\Flight::whereNotNull('ticket_id')->get();
Q: Laravel eloquent model query for `not null` I've been using Laravel for a project and using the Eloquent models to grab the model instances I need. However, it doesn't look like there's a way to query for not null values. https://laravel.com/docs/5.4/eloquent#retrieving-models Is there a way to do something like this, where I want to get all Flight models where the ticket_id is not null? $flight = App\Flight::where('ticket_id', '!=', null); A: Try this $flight = App\Flight::whereNotNull('ticket_id')->get();
stackoverflow
{ "language": "en", "length": 76, "provenance": "stackexchange_0000F.jsonl.gz:883361", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44599594" }
50a5abce7d3794059ad219543e5ed28bf8a91691
Stackoverflow Stackexchange Q: What does '?' after href do? What does ? after href do? Often time you will see something like this href='?page=1' Does anybody knows? Thanks in advance to all for the help. A: That means it is a link to the current webpage with a query-string parameter. In this case the page number. This is usually if you have a dynamic page listing contents and limiting the number per page.
Q: What does '?' after href do? What does ? after href do? Often time you will see something like this href='?page=1' Does anybody knows? Thanks in advance to all for the help. A: That means it is a link to the current webpage with a query-string parameter. In this case the page number. This is usually if you have a dynamic page listing contents and limiting the number per page. A: The "?" mark is very useful and important in many ways. for example, and uses to identify a particular usage for specific reasons, one of these reason is that when you have a website with three languages exists but it has the same pages. check the following links below. http://example.com/news?language=EN The language of example website is in English http://example.com/news?language=RU The language of example website is in Russian http://example.com/news?language=DE The language of example website is in Germany Other reason is when you have a dynamic page that contains only one page with many contents thats stored in website's database. before it was static pages like the following links below http://example.com/page1.html http://example.com/page2.html http://example.com/page3.html As you can see we have three pages. how about that we can have many pages but in the same one page. the only thing is different is to change the parameter of the page itself. Let's say you own an e-library. you don't waste your life creating thousands of pages working on book details, you can simply create a book page with isbn parameter as it shown below https://example.com/books?isbn=0132947048 It also used to track online campaigns and identify which source that users coming from... http://example.com/?source=StackOverFlow&medium=Banner Hope I answered your question clearly :)
stackoverflow
{ "language": "en", "length": 276, "provenance": "stackexchange_0000F.jsonl.gz:883367", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44599613" }
e31feff985b27c59e817a712c8c48d63fda406cc
Stackoverflow Stackexchange Q: Moment.js: Uncaught TypeError: Cannot read property 'defineLocale' of undefined at moment.js:13 When running the small html file below I see the following console log error: moment.js:13 Uncaught TypeError: Cannot read property 'defineLocale' of undefined at moment.js:13 at moment.js:9 at moment.js:10 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> <script src="../scripts/libraries/moment.js"></script> </head> <body> <script> var now = moment() console.log(now); </script> </body> </html> I have also tried replacing the reference to the local library with this CDN link: https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/locale/af.js Anyone know what this error is? A: This error also occurs when you include locale js prior to moment js. For instance following gives error: <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/locale/tr.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script> To correct, just put moment js above to locale js.
Q: Moment.js: Uncaught TypeError: Cannot read property 'defineLocale' of undefined at moment.js:13 When running the small html file below I see the following console log error: moment.js:13 Uncaught TypeError: Cannot read property 'defineLocale' of undefined at moment.js:13 at moment.js:9 at moment.js:10 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> <script src="../scripts/libraries/moment.js"></script> </head> <body> <script> var now = moment() console.log(now); </script> </body> </html> I have also tried replacing the reference to the local library with this CDN link: https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/locale/af.js Anyone know what this error is? A: This error also occurs when you include locale js prior to moment js. For instance following gives error: <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/locale/tr.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script> To correct, just put moment js above to locale js. A: It seems to be a problem with your version of moment.js. The script that you have is only for locale, you need to include the moment.js script: https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script> </head> <body> <script> var now = moment() console.log(typeof moment.defineLocale) </script> </body> </html>
stackoverflow
{ "language": "en", "length": 176, "provenance": "stackexchange_0000F.jsonl.gz:883401", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44599730" }
17e439750fe6cd02daf62dc3cc32b601f9cbfa5f
Stackoverflow Stackexchange Q: Performance of ternary operator vs if-else statement Note: It's true that this question has been answered for many other languages. However, I could not find an answer for Python, so do not mark as duplicate. Is there a difference in performance between the if-else statement and the ternary operator in Python? A: I doubt there is a performance difference. They compile to equivalent sequences of bytecodes: >>> def f(): ... return a if b else c ... >>> dis.dis(f) 2 0 LOAD_GLOBAL 0 (b) 2 POP_JUMP_IF_FALSE 8 4 LOAD_GLOBAL 1 (a) 6 RETURN_VALUE >> 8 LOAD_GLOBAL 2 (c) 10 RETURN_VALUE >>> def g(): ... if b: ... return a ... else: ... return c ... >>> dis.dis(g) 2 0 LOAD_GLOBAL 0 (b) 2 POP_JUMP_IF_FALSE 8 3 4 LOAD_GLOBAL 1 (a) 6 RETURN_VALUE 5 >> 8 LOAD_GLOBAL 2 (c) 10 RETURN_VALUE 12 LOAD_CONST 0 (None) 14 RETURN_VALUE As with most performance questions, the answer is to measure.
Q: Performance of ternary operator vs if-else statement Note: It's true that this question has been answered for many other languages. However, I could not find an answer for Python, so do not mark as duplicate. Is there a difference in performance between the if-else statement and the ternary operator in Python? A: I doubt there is a performance difference. They compile to equivalent sequences of bytecodes: >>> def f(): ... return a if b else c ... >>> dis.dis(f) 2 0 LOAD_GLOBAL 0 (b) 2 POP_JUMP_IF_FALSE 8 4 LOAD_GLOBAL 1 (a) 6 RETURN_VALUE >> 8 LOAD_GLOBAL 2 (c) 10 RETURN_VALUE >>> def g(): ... if b: ... return a ... else: ... return c ... >>> dis.dis(g) 2 0 LOAD_GLOBAL 0 (b) 2 POP_JUMP_IF_FALSE 8 3 4 LOAD_GLOBAL 1 (a) 6 RETURN_VALUE 5 >> 8 LOAD_GLOBAL 2 (c) 10 RETURN_VALUE 12 LOAD_CONST 0 (None) 14 RETURN_VALUE As with most performance questions, the answer is to measure. A: From some testing on Python 3.6.1, it seems like the full statement is faster. My Results: >>> timeit.timeit("""3 if True else 8""") 0.012174860001323395 >>> timeit.timeit("""3 if False else 8""") 0.019092951000857283 >>> timeit.timeit("""if True: ... 3 ... else: ... 8""") 0.009110345999943092 >>> timeit.timeit("""if False: ... 3 ... else: ... 8""") 0.00877297099941643 A: Here're my tests in IPython 7.2.0 (which has %timeit, a built-in timing method that makes it extremely easy to measure executions. By default it makes 7 runs and 100 million loops each, so the results should usually be valid) used by PyCharm 2018.3.4 Community Edition x64, running CPython 3.7.2 x64. The OS is Window$ 10.0.17134 Enterprise x64: ##The 1st 2 are without quoting the statement to see how it affects the test. %timeit 3 if True else 8 14.7 ns ± 0.319 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each) %timeit 3 if False else 8 18.1 ns ± 0.211 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each) ##---------------------------------------------------------------------------- %timeit 'if True:\n 3\nelse:\n 8' 8.67 ns ± 0.314 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each) %timeit 'if False:\n 3\nelse:\n 8' 8.4 ns ± 0.0598 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each) ##---------------------------------------------------------------------------- ##The last 2 are with quoting the statement. %timeit '3 if True else 8' 8.73 ns ± 0.256 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each) %timeit '3 if False else 8' 9.37 ns ± 0.215 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each) I think the numbers speak for the statements. A shame really, cuz I love the ternary op. However, the ternary op's still absolutely useful, especially in the cases where covering all the possibilities in function call params would create a massive repeating of code, which I absolutely hate.
stackoverflow
{ "language": "en", "length": 475, "provenance": "stackexchange_0000F.jsonl.gz:883440", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44599860" }
6e48da64e4b204f0ac124b830af7e98a682d5314
Stackoverflow Stackexchange Q: Alternatives for WordUtils.capitalize? I'm trying to capitalize every word in a string using WordUtils.capitalize(String) because it does exactly what I wanted. However it is now deprecated. What method should I use instead? Or do I have to write my own method? A: The implementation in commons-lang3 is deprecated. However, the same method is implemented in commons-text. Therefore, you may use essentially the same method, but will need to add a new .jar file and adjust the import statement. From the javadoc of org.apache.commons.lang3.text.WordUtils: as of 3.6, use commons-text WordUtils instead If using Maven (or similar), add the following: <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> <version>1.1</version> </dependency> The reference for Commons Text: Apache Commons Text is a library focused on algorithms working on strings.
Q: Alternatives for WordUtils.capitalize? I'm trying to capitalize every word in a string using WordUtils.capitalize(String) because it does exactly what I wanted. However it is now deprecated. What method should I use instead? Or do I have to write my own method? A: The implementation in commons-lang3 is deprecated. However, the same method is implemented in commons-text. Therefore, you may use essentially the same method, but will need to add a new .jar file and adjust the import statement. From the javadoc of org.apache.commons.lang3.text.WordUtils: as of 3.6, use commons-text WordUtils instead If using Maven (or similar), add the following: <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> <version>1.1</version> </dependency> The reference for Commons Text: Apache Commons Text is a library focused on algorithms working on strings. A: You can use apache.commons's StringUtils.capitalise(): public static String capitalize(String str) Capitalizes a String changing the first character to title case as per Character.toTitleCase(int). No other characters are changed. Instead of WordUtils class use StringUtils from the same package, so you don't have to change your project configuration by adding extra jars. Alternative: Or you can implement it yourself, you can try something like this: String str = "john"; String newStr = str.substring(0, 1).toUpperCase() + str.substring(1); Will print John.
stackoverflow
{ "language": "en", "length": 200, "provenance": "stackexchange_0000F.jsonl.gz:883462", "question_score": "18", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44599940" }
7aeded290dc249b5c14aed513577ea4c389775dc
Stackoverflow Stackexchange Q: AuthenticationContext does not contain the definition AcquireToken? Im trying to play with the Microsoft Power BI REST API but didn't get much far since im not very experienced with the API's as i understand the Authentication Context is part of the Identity model active directory, which i triple check if it was referenced to the project (the rest of the methods run property) but there are no methods called AcquireToken or AcquireTokenSilent, i just have other ones called AcquireTokenAsync ans AcquireTokenAsyncSilent idk if they are the some or not. if someone can provide any light on the matter it will be much appreciated. Thanks A: You could be using V3 of ADAL.NET which appears to no longer have AcquireToken(). But it still has AcquireTokenAsync(). Note however that the parameters have slightly changed in the methods for v2 and v3. ADAL.NET v3 has this AuthenticationContext ADAL.NET v2 has this AuthenticationContext
Q: AuthenticationContext does not contain the definition AcquireToken? Im trying to play with the Microsoft Power BI REST API but didn't get much far since im not very experienced with the API's as i understand the Authentication Context is part of the Identity model active directory, which i triple check if it was referenced to the project (the rest of the methods run property) but there are no methods called AcquireToken or AcquireTokenSilent, i just have other ones called AcquireTokenAsync ans AcquireTokenAsyncSilent idk if they are the some or not. if someone can provide any light on the matter it will be much appreciated. Thanks A: You could be using V3 of ADAL.NET which appears to no longer have AcquireToken(). But it still has AcquireTokenAsync(). Note however that the parameters have slightly changed in the methods for v2 and v3. ADAL.NET v3 has this AuthenticationContext ADAL.NET v2 has this AuthenticationContext A: I had the same issue. When you are using Microsoft.IdentityModel.Clients.ActiveDirectory you need to install the correct version. I tried with the latest version but did not work. But after installing Microsoft.IdentityModel.Clients.ActiveDirectory version 2.22.302111727 error was solved. If you are using the latest version, AcquireToken was removed in v3 of the Microsoft.IdentityModel.Clients.ActiveDirectory library. You now have to use AcquireTokenAsync. Reference - https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/443 A: IF you're using the wrappers, ensure to have the correct version-Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612. Once referenced, you can run this below. For alternatives, see this blog: https://samtran.me/2018/11/11/power-bi-rest-api/
stackoverflow
{ "language": "en", "length": 239, "provenance": "stackexchange_0000F.jsonl.gz:883468", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44599967" }
12a681d01e04874c28e970fbc30d74de7ed93978
Stackoverflow Stackexchange Q: Where to put nginx configuration file? I understand that i should put this code in order to make HTML5 History fallback: location / { try_files $uri $uri/ /index.html; } https://router.vuejs.org/en/essentials/history-mode.html but to which file? tried search google, nothing works, put above code in /etc/nginx/nginx.conf will make nginx not working. im using vagrant Homestead for laravel. please help. A: Put configuration in /etc/nginx/nginx.conf server { location / { try_files $uri $uri/ /index.html; } }
Q: Where to put nginx configuration file? I understand that i should put this code in order to make HTML5 History fallback: location / { try_files $uri $uri/ /index.html; } https://router.vuejs.org/en/essentials/history-mode.html but to which file? tried search google, nothing works, put above code in /etc/nginx/nginx.conf will make nginx not working. im using vagrant Homestead for laravel. please help. A: Put configuration in /etc/nginx/nginx.conf server { location / { try_files $uri $uri/ /index.html; } } A: If you were looking for the location of the NGINX config file: * *The main config file is /etc/nginx/nginx.conf. *The default version of this file loads all files matching /etc/nginx/conf.d/*.conf into its http block. *So if you want to specify a server block, you can overwrite /etc/nginx/conf.d/default.conf or add your own .conf file there. A: Finally, i get nginx work with html5 fallback. open /etc/nginx/site-available/homestead.app, or any domain your specified in your homestead.yaml file. put/replace "location" section with location / { try_files $uri $uri/ /index.php; } then save, and open laravel web.php (router). put this code: Route::get('/{vue?}/{vue2?}/{vue3?}', function () { // return view('welcome'); if ( ! request()->ajax() ) { return view('index'); } }); above code prevent laravel to returning error 404. now vue html5 history fallback works without # sign. thanks everyone for trying to help, without you guys i may not have any idea to resolve this issue. A: That is an entry for the nginx.conf file, located at /etc/nginx/nginx.conf Add this to config: location / { try_files $uri /index.html; }
stackoverflow
{ "language": "en", "length": 247, "provenance": "stackexchange_0000F.jsonl.gz:883472", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44599979" }
7bce40409c09412dc654aa8c2c2a71e5fa650f62
Stackoverflow Stackexchange Q: Is var str: String mutable or immutable? I have declared a String variable in Kotlin as like. var str: String The Kotlin document contradict for mutability concept. As per document... var is mutable. But for String it define as immutable. So please clarify contradiction... A: I don't like way the documentation is written either but there is no contradiction in reality. They are using the word mutable in a way that invites a comparison between program symbols and objects that is not very helpful. A variable declared by the var keyword is reassignable whereas one declared with the val keyword is not. A string is an immutable object type, once created it cannot be changed. Whether a variable is reassignable and whether the object it points to is immutable are two different things. Here's an example: class Person(var name: String) val fred = Person("Fred") fred.name = "Barry" // fred is not immutable fred = Person("Barry") // ERROR Val cannot be reassigned So to use mutable in the way the documentation does, just because a symbol is declared a val does not make the object it points to immutable.
Q: Is var str: String mutable or immutable? I have declared a String variable in Kotlin as like. var str: String The Kotlin document contradict for mutability concept. As per document... var is mutable. But for String it define as immutable. So please clarify contradiction... A: I don't like way the documentation is written either but there is no contradiction in reality. They are using the word mutable in a way that invites a comparison between program symbols and objects that is not very helpful. A variable declared by the var keyword is reassignable whereas one declared with the val keyword is not. A string is an immutable object type, once created it cannot be changed. Whether a variable is reassignable and whether the object it points to is immutable are two different things. Here's an example: class Person(var name: String) val fred = Person("Fred") fred.name = "Barry" // fred is not immutable fred = Person("Barry") // ERROR Val cannot be reassigned So to use mutable in the way the documentation does, just because a symbol is declared a val does not make the object it points to immutable. A: An excellent example by @Frank. It makes me more clear, what the documentation said. The first part of the documentation says: Classes in Kotlin can have properties. These can be declared as mutable, using the var keyword or read-only using the val keyword. Now, the second part says: Strings are represented by the type String. Strings are immutable. These both are true in my opinion. Based on the Frank's example, let's take another example. data class User(var name: String, var email:String) var user1 = User("Foo","foo@bar.com") // user1 is mutable and object properties as well val user2 = User("Bar","bar@foo.com") // user2 is immutable but object's properties are mutable Now, consider property user1. It is mutable as it is declared with keyword var. And also the User object assign to it. But the user2 property is immutable. You can not change the assigned object to it. But the Object itself has mutable properties. So the properties can be changes by user2.name = "Foo". Now changing the example a bit and making user properties immutable. data class User(val name: String, val email:String) var user1 = User("Foo","foo@bar.com") // user1 is mutable and object properties are not val user2 = User("Bar","bar@foo.com") // user2 is immutable and object's properties are also immutable Here, User's properties are immutable. So, user1 is mutable, you can assign another object to it. But the properties are immutable. So user1 = User("New Foo","newfoo@bar.com") will work. But after assigning an object User, you can not change it's properties, as they are immutable. Now, let's take an example with String type. var str1 = "Bar" // Here str1 (property) is mutable. So you can assign a different string to it. // But you can not modify the String object directly. str1 = "Foo" // This will work str1[0] = 'B' // This will NOT work as The string object assigned to str1 is immutable val str2 = "Foo" // Here both str2 and the assigned object are immutable. (Just like Java final) And as the Frank said, just because a symbol is declared a val does not make the object it points to immutable. My final cents: String object is immutable, as it can not be changed. But that immutable String object can be assigned to a mutable property, which can be re-assigned with the different String Object. That is what var keyword does. Making the property mutable. But the object it points to can be mutable or immutable. A: What's the contradiction? A string is read-only. Just as Java, you cannot set a[i] = 'x', any string replacement methods return new strings, etc. Therefore, not mutable. This point is made to clarify the functionality of a var String type The difference between var and val can be associated with a final variable in Java. You can make a final String constant, or you can have a regular String object A: Actually, String variable is mutable, but String Value is Immutable. Appreciate with @cricket_007 Let me Describe deeply what happened behind When you declare variable. val string1 = "abcd" val string2 = "abcd" As Shown above image and Declaration. -String pool is a special storage area in The Heap Memory. -When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference. -If string is not immutable, changing the string with one reference will lead to the wrong value for the other references. -Now with above our example Value Assign to Variable String1 now we can use this variable. also we can change the value string1.renameTo("Hi This Is Test") So What happen at behind in memory ? ->yes, if "Hi This Is Test" this string available it will return a reference to "string1" else it Create new space and give reference To "string1" Actually, that's Why String called immutable. Reference - Link A: Personally, I find it easier to think about the difference between val and var in terms of Java. val would correspond to a variable with the final modifier, which means it can only be assigned once and var is just with that modifier absent and therefore reassignable. The object themselves can still be either mutable or immutable. Mutability here refers to the variable itself. A: In Kotlin/Java an object's behaviour does not depend on the kind of reference you use to access it. Everything is (potentially) in the heap, so any property is just a reference (a.k.a. link) to the object. val str = "Hello" val a = str var b = str In the snippet above there is only one immutable string str, and both a and b reference it. You can't change the string, no matter what reference you use, mutable or immutable. But you can change the mutable reference itself to point to another (immutable) string: b = "World"
stackoverflow
{ "language": "en", "length": 1003, "provenance": "stackexchange_0000F.jsonl.gz:883485", "question_score": "14", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44600017" }
8446382643c70b59c4e3f56c615b2fd5c1600c44
Stackoverflow Stackexchange Q: Does keep_files support wildcards? Is there a way to specify wildcards in the keep_files config? The following does not seem to work: keep_files: [workbox-sw*]
Q: Does keep_files support wildcards? Is there a way to specify wildcards in the keep_files config? The following does not seem to work: keep_files: [workbox-sw*]
stackoverflow
{ "language": "en", "length": 25, "provenance": "stackexchange_0000F.jsonl.gz:883501", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44600074" }
b925ecf3f0df081d7cdd4ac6e880adfedb03529e
Stackoverflow Stackexchange Q: android studio no longer run/debug (install) RenderScript app to mobile device anymore This issue started after I updated Android Studio from 2.1.2 to 2.3.3, with an existing RenderScript project. The error message I get is: Error:Execution failed for task ':app:mergeDebugResources'. Error: java.io.FileNotFoundException: C:\< project location > \app\build\generated\res\rs\debug\raw\bc64 (Access is denied) The project is from Android Studio 2.1.2 and later opened by 2.3.3. There is no prompt of an incorrect version number, so it should work fine. But now I cannot Run/Debug app to a mobile device. When I tried creating a new blank screen project with RenderScript enabled, it was able to run/debug. How to solve? A: Has same problem, added to Graddle configuration: android{ ... defaultConfig{ ... renderscriptTargetApi 21 } }
Q: android studio no longer run/debug (install) RenderScript app to mobile device anymore This issue started after I updated Android Studio from 2.1.2 to 2.3.3, with an existing RenderScript project. The error message I get is: Error:Execution failed for task ':app:mergeDebugResources'. Error: java.io.FileNotFoundException: C:\< project location > \app\build\generated\res\rs\debug\raw\bc64 (Access is denied) The project is from Android Studio 2.1.2 and later opened by 2.3.3. There is no prompt of an incorrect version number, so it should work fine. But now I cannot Run/Debug app to a mobile device. When I tried creating a new blank screen project with RenderScript enabled, it was able to run/debug. How to solve? A: Has same problem, added to Graddle configuration: android{ ... defaultConfig{ ... renderscriptTargetApi 21 } } A: This issue can also happen when installing between different Android OS versions. Doing Build -> Clean may not resolve the problem. So just manually delete the folder 'bc64' at the path specified in the error message, then press Run. That should work, and it will regenerate the folder and files. This will also fix the following similar issue: Error: java.io.FileNotFoundException: /Users/username/AndroidApp/app/build/generated/res/rs/debug/raw/bc64 (Is a directory) There are 2 ways you can delete the folder from within Android Studio: * *View -> Tool Windows -> Terminal -> rm -rf app/build/generated/res/rs/debug/raw/bc64 *View -> Tool Windows -> Project -> navigate to the bc64 folder -> right-click -> delete A: I was facing the same issue. File -> Invalidate Cache and Restart fixed the issue for me. It does the same thing as mentioned by Mr. IDE but it's a lot convenient to do this way instead of locating the folder and deleting it.
stackoverflow
{ "language": "en", "length": 273, "provenance": "stackexchange_0000F.jsonl.gz:883578", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44600304" }
183cd6b6e1447a20edc38b629d332d1e16dec3a6
Stackoverflow Stackexchange Q: how to install python 3.x version in /usr/bin/? I downloaded python 3.6 installation file (tgz file). I installed it the following way: $ ./configure $ make $ su root Password: $ make install Then, python installed in /usr/local/bin but I want to install python in /usr/bin. How can I do that? A: You can change the location using the --prefix option in configure (which defaults to usr/local). Python will be installed under /bin, so if you want it in /usr/bin, you can write: ./configure --prefix=/usr --enable-optimizations make make install
Q: how to install python 3.x version in /usr/bin/? I downloaded python 3.6 installation file (tgz file). I installed it the following way: $ ./configure $ make $ su root Password: $ make install Then, python installed in /usr/local/bin but I want to install python in /usr/bin. How can I do that? A: You can change the location using the --prefix option in configure (which defaults to usr/local). Python will be installed under /bin, so if you want it in /usr/bin, you can write: ./configure --prefix=/usr --enable-optimizations make make install A: This following commands worked for me : ./configure --prefix=/usr make make install A: There should be an option '--prefix' so that > ./configure --prefix=/usr > make > sudo make install should do the job. Otherwise, search for 'usr/local/bin' in the configuration script and replace accordingly. A: Building Python with optimizations can take some time. If this has already been done and you wish to avoid repeating it, you might consider the following: sudo make install prefix=/usr I don't know whether going rerunning ./configure will force a rebuild.
stackoverflow
{ "language": "en", "length": 178, "provenance": "stackexchange_0000F.jsonl.gz:883616", "question_score": "17", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44600424" }
9af664916a17bafb02ff8a5d02781637d013aa20
Stackoverflow Stackexchange Q: How to add an extra field in the registration form generated by devise? I'm learning Ruby, OOP and Rails. My app uses the Devise gem for registering users. It only offers the fields email, password, and password confirmation, but I need an extra field, phone number. What is the correct way to add it? (Not just in the html file) A: 1) You need to add the extra fields to your User Model... rails g migration AddPhoneNumberToUser phone_number:string 2) Configure Strong Parameters in ApplicationController class ApplicationController < ActionController::Base before_action :configure_permitted_parameters, if: :devise_controller? protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:phone_number]) end end NOTE: if you already have custom controllers, you just need to uncomment (overhide) RegistrationsController#sign_up_params method 3) Generate devise views (if you didn't it yet) rails generate devise:views 4) Add extra fields to form in app/views/devise/registrations/new.html.erb
Q: How to add an extra field in the registration form generated by devise? I'm learning Ruby, OOP and Rails. My app uses the Devise gem for registering users. It only offers the fields email, password, and password confirmation, but I need an extra field, phone number. What is the correct way to add it? (Not just in the html file) A: 1) You need to add the extra fields to your User Model... rails g migration AddPhoneNumberToUser phone_number:string 2) Configure Strong Parameters in ApplicationController class ApplicationController < ActionController::Base before_action :configure_permitted_parameters, if: :devise_controller? protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:phone_number]) end end NOTE: if you already have custom controllers, you just need to uncomment (overhide) RegistrationsController#sign_up_params method 3) Generate devise views (if you didn't it yet) rails generate devise:views 4) Add extra fields to form in app/views/devise/registrations/new.html.erb
stackoverflow
{ "language": "en", "length": 136, "provenance": "stackexchange_0000F.jsonl.gz:883621", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44600435" }
260ef7f6efc73d87e3356ddbff91c0a0fb44236d
Stackoverflow Stackexchange Q: Using an array for autofilter criteria I have the below code which will delete rows based on criteria in column I: Sub Strip() Dim rng As Range With ActiveSheet .Columns("I").AutoFilter Field:=1, Criteria1:="=70-79%", VisibleDropDown:=False Set rng = .AutoFilter.Range End With If rng.Columns("I").SpecialCells(xlCellTypeVisible).Count - 1 > 0 Then Application.DisplayAlerts = False rng.Offset(1, 0).SpecialCells(xlCellTypeVisible).Delete Application.DisplayAlerts = True End If rng.AutoFilter End Sub I have about 100 different criteria that I want to act on in this way. I'd rather not have to repeat this code 100 times, and so can anyone tell me how to code this in the form of an array? I've tried various methods but can't seem to get it to work. A: Use .Columns("I").AutoFilter Field:=1, Criteria1:=MyArray, Operator:=xlFilterValues Where MyArray is a string Array Example Dim MyArray(1 To 4) As String MyArray(1) = "This" MyArray(2) = "is" MyArray(3) = "an" MyArray(4) = "array" ' '~~> Rest of code ' .Columns("I").AutoFilter Field:=1, Criteria1:=MyArray, Operator:=xlFilterValues ' '~~> Rest of code ' Screenshot
Q: Using an array for autofilter criteria I have the below code which will delete rows based on criteria in column I: Sub Strip() Dim rng As Range With ActiveSheet .Columns("I").AutoFilter Field:=1, Criteria1:="=70-79%", VisibleDropDown:=False Set rng = .AutoFilter.Range End With If rng.Columns("I").SpecialCells(xlCellTypeVisible).Count - 1 > 0 Then Application.DisplayAlerts = False rng.Offset(1, 0).SpecialCells(xlCellTypeVisible).Delete Application.DisplayAlerts = True End If rng.AutoFilter End Sub I have about 100 different criteria that I want to act on in this way. I'd rather not have to repeat this code 100 times, and so can anyone tell me how to code this in the form of an array? I've tried various methods but can't seem to get it to work. A: Use .Columns("I").AutoFilter Field:=1, Criteria1:=MyArray, Operator:=xlFilterValues Where MyArray is a string Array Example Dim MyArray(1 To 4) As String MyArray(1) = "This" MyArray(2) = "is" MyArray(3) = "an" MyArray(4) = "array" ' '~~> Rest of code ' .Columns("I").AutoFilter Field:=1, Criteria1:=MyArray, Operator:=xlFilterValues ' '~~> Rest of code ' Screenshot
stackoverflow
{ "language": "en", "length": 161, "provenance": "stackexchange_0000F.jsonl.gz:883625", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44600448" }
9327ef104f46ac1e8eefbdc31c4c10a2e5eb24bb
Stackoverflow Stackexchange Q: How To Update row in custom wordpress table Ive Tried And Tried Looking Up How To Approach Editing/Updating Rows In Custom Wordpress Tables I Have It Set To Grab Current logged in user's username which then compares to a custom wp_ table With UserNAme As The Primary Key Which Then I Would Like To Edit A Particular Column/Field On That Particular Row By Passing The Value Of A Variable Over After It Confirms Current Logged In User Matches The Primary Key UserName In My Custom Table"wp_customers" What Am I Doing Wrong With This Line Of Code Or Do You Have A Better Solution $current_user = wp_get_current_user(); $johnny = $current_user->user_login; $subs = 'illinois'; global $wpdb; $wpdb->query( " UPDATE $wpdb->wp_Customers SET BuyersAddress = $subs WHERE UserName = $johnny "); A: Try this code A simple WordPress Update query WP Update $current_user = wp_get_current_user(); $johnny = array('UserName' => $current_user->user_login); $subs = array('BuyersAddress' => 'illinois'); global $wpdb; $table_name = $wpdb->prefix."Customers"; $wpdb->update($table_name, $subs, $johnny); Hope this will help you
Q: How To Update row in custom wordpress table Ive Tried And Tried Looking Up How To Approach Editing/Updating Rows In Custom Wordpress Tables I Have It Set To Grab Current logged in user's username which then compares to a custom wp_ table With UserNAme As The Primary Key Which Then I Would Like To Edit A Particular Column/Field On That Particular Row By Passing The Value Of A Variable Over After It Confirms Current Logged In User Matches The Primary Key UserName In My Custom Table"wp_customers" What Am I Doing Wrong With This Line Of Code Or Do You Have A Better Solution $current_user = wp_get_current_user(); $johnny = $current_user->user_login; $subs = 'illinois'; global $wpdb; $wpdb->query( " UPDATE $wpdb->wp_Customers SET BuyersAddress = $subs WHERE UserName = $johnny "); A: Try this code A simple WordPress Update query WP Update $current_user = wp_get_current_user(); $johnny = array('UserName' => $current_user->user_login); $subs = array('BuyersAddress' => 'illinois'); global $wpdb; $table_name = $wpdb->prefix."Customers"; $wpdb->update($table_name, $subs, $johnny); Hope this will help you A: Try this code. $current_user = wp_get_current_user(); $johnny = $current_user->user_login; $subs = 'illinois'; global $wpdb; $table_name = $wpdb->prefix."Customers"; $wpdb->query( $wpdb->prepare("UPDATE $table_name SET BuyersAddress = %s WHERE UserName = %s",$subs, $johnny) ); A: $msg=''; if(isset($_POST['submit']) && $_POST['submit']=='Submit') { $assID =12; //pass your table id $table_name = $wpdb->prefix."assigned_user"; //custom table name $ds = $_POST['driverStatus']; $wpdb->query( $wpdb->prepare("UPDATE $table_name SET driverStatus = '".$ds."' WHERE id ='".$assID."' ") ); $msg = 'Successfully Delivered!'; }
stackoverflow
{ "language": "en", "length": 234, "provenance": "stackexchange_0000F.jsonl.gz:883633", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44600467" }
ef8ee158f03161debab84ab7718548686b4d2b3a
Stackoverflow Stackexchange Q: ARKit - configure video quality This question is about Apple's new ARKit framework introduced with iOS 11: Is there a way to configure the captured video quality while using an ARSession? It seems to default to 1280x720 - which looks pretty bad, especially on an iPad. I'd love to change this to 1080p or 4k. If this isn't possible, is there any way to use ARKit by providing a custom video stream? A: Nope, and nope. ARKit owns and entirely controls its underlying video capture session. It's hard to know why, but there are some likely guesses... to ensure that it gets video samples in a format and rate that works well for the computer vision work it does to provide world tracking. And/or to make sure said work is done efficiently enough to leave headroom for your app to do awesome things with SceneKit, Metal, etc. And/or to make world tracking performance/accuracy consistent across all supported hardware. More capture session flexibility might be a good feature request to send to Apple, though.
Q: ARKit - configure video quality This question is about Apple's new ARKit framework introduced with iOS 11: Is there a way to configure the captured video quality while using an ARSession? It seems to default to 1280x720 - which looks pretty bad, especially on an iPad. I'd love to change this to 1080p or 4k. If this isn't possible, is there any way to use ARKit by providing a custom video stream? A: Nope, and nope. ARKit owns and entirely controls its underlying video capture session. It's hard to know why, but there are some likely guesses... to ensure that it gets video samples in a format and rate that works well for the computer vision work it does to provide world tracking. And/or to make sure said work is done efficiently enough to leave headroom for your app to do awesome things with SceneKit, Metal, etc. And/or to make world tracking performance/accuracy consistent across all supported hardware. More capture session flexibility might be a good feature request to send to Apple, though.
stackoverflow
{ "language": "en", "length": 174, "provenance": "stackexchange_0000F.jsonl.gz:883644", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44600490" }
aebba727a1623ccdc8a68c98fa3b3f57d6d87c9b
Stackoverflow Stackexchange Q: Datetime in pandas dataframe will not subtract from each other I am trying to find the difference in times between two columns in a pandas dataframe both in datetime format. Below is some of the data in my dataframe and the code I have been using. I have triple checked that these two columns dtypes are datetime64. My data: date_updated date_scored 2016-03-30 08:00:00.000 2016-03-30 08:00:57.416 2016-04-07 23:50:00.000 2016-04-07 23:50:12.036 My code: data['date_updated'] = pd.to_datetime(data['date_updated'], format='%Y-%m-%d %H:%M:%S') data['date_scored'] = pd.to_datetime(data['date_scored'], format='%Y-%m-%d %H:%M:%S') data['Diff'] = data['date_updated'] - data['date_scored'] The error message I receive: TypeError: data type "datetime" not understood Any help would be appreciated, thanks! My work around solution: for i in raw_data[:10]: scored = i.date_scored scored_date = pd.to_datetime(scored, format='%Y-%m-%d %H:%M:%S') if type(scored_date) == "NoneType": pass elif scored_date.year >= 2016: extracted = i.date_extracted extracted = pd.to_datetime(extracted, format='%Y-%m-%d %H:%M:%S') bank = i.bank.name diff = scored - extracted datum = [str(bank), str(extracted), str(scored), str(diff)] data.append(datum) else: pass A: I encountered the same error using the above syntax (worked on another machine though): data['Diff'] = data['date_updated'] - data['date_scored'] It worked on my new machine with: data['Diff'] = data['date_updated'].subtract(data['date_scored'])
Q: Datetime in pandas dataframe will not subtract from each other I am trying to find the difference in times between two columns in a pandas dataframe both in datetime format. Below is some of the data in my dataframe and the code I have been using. I have triple checked that these two columns dtypes are datetime64. My data: date_updated date_scored 2016-03-30 08:00:00.000 2016-03-30 08:00:57.416 2016-04-07 23:50:00.000 2016-04-07 23:50:12.036 My code: data['date_updated'] = pd.to_datetime(data['date_updated'], format='%Y-%m-%d %H:%M:%S') data['date_scored'] = pd.to_datetime(data['date_scored'], format='%Y-%m-%d %H:%M:%S') data['Diff'] = data['date_updated'] - data['date_scored'] The error message I receive: TypeError: data type "datetime" not understood Any help would be appreciated, thanks! My work around solution: for i in raw_data[:10]: scored = i.date_scored scored_date = pd.to_datetime(scored, format='%Y-%m-%d %H:%M:%S') if type(scored_date) == "NoneType": pass elif scored_date.year >= 2016: extracted = i.date_extracted extracted = pd.to_datetime(extracted, format='%Y-%m-%d %H:%M:%S') bank = i.bank.name diff = scored - extracted datum = [str(bank), str(extracted), str(scored), str(diff)] data.append(datum) else: pass A: I encountered the same error using the above syntax (worked on another machine though): data['Diff'] = data['date_updated'] - data['date_scored'] It worked on my new machine with: data['Diff'] = data['date_updated'].subtract(data['date_scored']) A: You need to update pandas. I've just ran into the same issue with an old code that used to run without issues. After updating pandas (0.18.1-np111py35_0) to a newer version (0.20.2-np113py35_0) the issue was resolved. A: It works like a charm. You can even simplify your code since to_datetime is smart enough to guess the format for you. import io import pandas as pd # Paste the text by using of triple-quotes to span String literals on multiple lines zz = """date_updated,date_scored 2016-03-30 08:00:00.000, 2016-03-30 08:00:57.416 2016-04-07 23:50:00.000, 2016-04-07 23:50:12.036""" data = pd.read_table(io.StringIO(zz), delim_whitespace=False, delimiter=',') data['date_updated'] = pd.to_datetime(data['date_updated']) data['date_scored'] = pd.to_datetime(data['date_scored']) data['Diff'] = data['date_updated'] - data['date_scored'] print(data) # date_updated date_scored Diff # 0 2016-03-30 08:00:00 2016-03-30 08:00:57.416 -1 days +23:59:02.584000 # 1 2016-04-07 23:50:00 2016-04-07 23:50:12.036 -1 days +23:59:47.964000
stackoverflow
{ "language": "en", "length": 314, "provenance": "stackexchange_0000F.jsonl.gz:883717", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44600752" }
2d4f17eced2daa8b3cdca32cbf1073cdaa0dcf5d
Stackoverflow Stackexchange Q: Equivalent of BlueBird Promise.props for ES6 Promises? I would like to wait for a map of word to Promise to finish. BlueBird has Promise.props which accomplishes this, but is there a clean way to do this in regular javascript? I think I can make a new object which houses both the word and the Promise, get an array of Promises of those objects, and then call Promise.all and put them in the map, but it seems like overkill. A: An implementation of Bluebird.props that works on plain objects: /** * This function maps `{a: somePromise}` to a promise that * resolves with `{a: resolvedValue}`. * @param {object} obj * @returns {Promise<object>} */ function makePromiseFromObject(obj) { const keys = Object.keys(obj); const values = Object.values(obj); return Promise.all(values) .then(resolved => { const res = {}; for (let i = 0; i < keys.length; i += 1) { res[keys[i]] = resolved[i]; } return res; }) }
Q: Equivalent of BlueBird Promise.props for ES6 Promises? I would like to wait for a map of word to Promise to finish. BlueBird has Promise.props which accomplishes this, but is there a clean way to do this in regular javascript? I think I can make a new object which houses both the word and the Promise, get an array of Promises of those objects, and then call Promise.all and put them in the map, but it seems like overkill. A: An implementation of Bluebird.props that works on plain objects: /** * This function maps `{a: somePromise}` to a promise that * resolves with `{a: resolvedValue}`. * @param {object} obj * @returns {Promise<object>} */ function makePromiseFromObject(obj) { const keys = Object.keys(obj); const values = Object.values(obj); return Promise.all(values) .then(resolved => { const res = {}; for (let i = 0; i < keys.length; i += 1) { res[keys[i]] = resolved[i]; } return res; }) } A: If you are dealing with a Map with values that are promises (or a mix of promises and non-promises) - and you want the final resolved value to be a Map with all values resolved const mapPromise = map => Promise.all(Array.from(map.entries()).map(([key, value]) => Promise.resolve(value).then(value => ({key, value})))) .then(results => { const ret = new Map(); results.forEach(({key, value}) => ret.set(key, value)); return ret; }); Although, I bet someone has a slicker way to do this, some of the new ES2015+ stuff is still new to me :p A: The venerable async.js library has a promisified counterpart: async-q The promisified async-q library supports all the functions in the async library. Specifically async.parallel(). At first glance async.parallel() looks just like Promise.all() in accepting an array of functions (note one difference, an array of functions, not promises) and run them in parallel. What makes async.parallel special is that it also accepts an object: const asyncq = require('async-q'); async function foo () { const results = await asyncq.parallel({ something: asyncFunction, somethingElse: () => anotherAsyncFunction('some argument') }); console.log(results.something); console.log(results.somethingElse); } A: Alternative implementation combining ES6+ Object.entries() and Object.fromEntries(): async function pprops(input) { return Object.fromEntries( await Promise.all( Object.entries(input) .map( ([k, p])=>p.then(v=>[k, v]) ) ) ); }; A: I have two different implementations using ES6 async functions: async function PromiseAllProps(object) { const values = await Promise.all(Object.values(object)); Object.keys(object).forEach((key, i) => object[key] = values[i]); return object; } One line shorter, but less optimized: async function PromiseAllProps(object) { const values = await Promise.all(Object.values(object)); return Object.fromEntries(Object.keys(object).map((prop, i) => ([prop, values[i]]))); } Example const info = await PromiseAllProps({ name: fetch('/name'), phone: fetch('/phone'), text: fetch('/foo'), }); console.log(info); { name: "John Appleseed", phone: "5551234", text: "Hello World" } A: It would be advisable to use a library like bluebird for this. If you really want to do this yourself, the main idea is to: * *Resolve each of the map values and connect the promised value back with the corresponding key *Pass those promises to Promise.all *Convert the final promised array back to a Map I would make use of the second argument of Array.from, and the fact that an array of key/value pairs can be passed to the Map constructor: Promise.allMap = function(map) { return Promise.all( Array.from(map, ([key, promise]) => Promise.resolve(promise).then(value => [key, value]) ) ).then( results => new Map(results)); } // Example data const map = new Map([ ["Planet", Promise.resolve("Earth")], ["Star", Promise.resolve("Sun")], ["Galaxy", Promise.resolve("Milky Way")], ["Galaxy Group", Promise.resolve("Local Group")] ]); // Resolve map values Promise.allMap(map).then( result => console.log([...result]) ); .as-console-wrapper { max-height: 100% !important; top: 0; } A: You can simply write it using Promise.all + reduce const promiseProps = (props) => Promise.all(Object.values(props)).then( (values) => Object.keys(props).reduce((acc, prop, index) => { acc[prop] = values[index]; return acc; }, {}) ); A: And a nice lodash variant for sake of completeness for plain js objects async function makePromiseFromObject(obj: {[key: string]: Promise<any>}) { return _.zipObject(Object.keys(obj), await Promise.all(Object.values(obj))) }
stackoverflow
{ "language": "en", "length": 625, "provenance": "stackexchange_0000F.jsonl.gz:883722", "question_score": "14", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44600771" }
faf4dbc20be109a1ff49db3eb05d55fa499f1839
Stackoverflow Stackexchange Q: Error When Clone/Push Git Repos 443: Bad access, but no proxy used I am having really strange issue when do these operations clone/push with git remote repo. Let's say I'm trying to push my changes to remote repo. git push origin master Then I will get this error. fatal: unable to access '[Remote_Repo]': Failed to connect to github.com port 443: Bad access I checked this issue and everyone saying this related to proxy. But I am quiet sure that I am not using a proxy. A: Here what happened. Kaspersky internet security blocked the connection to the git server and that's why I got that error. So anyone facing the similer kind of issue, try disabling your anti virus first.
Q: Error When Clone/Push Git Repos 443: Bad access, but no proxy used I am having really strange issue when do these operations clone/push with git remote repo. Let's say I'm trying to push my changes to remote repo. git push origin master Then I will get this error. fatal: unable to access '[Remote_Repo]': Failed to connect to github.com port 443: Bad access I checked this issue and everyone saying this related to proxy. But I am quiet sure that I am not using a proxy. A: Here what happened. Kaspersky internet security blocked the connection to the git server and that's why I got that error. So anyone facing the similer kind of issue, try disabling your anti virus first. A: It depends on the nature of the remote server (here github.com) That could simply means an issue on the remote server side (even though there is no recent alert). Locally, it could be a firewall issue or an host of other causes (make sure your Windows is up-to-date with the latest patches As the OP Rukshan Dangalla confirms in the comments, the anti-virus (Kaspersky internet security) was blocking 443. You can see an example of such an interference in this issue, where it seems like the antivirus interferes with connection attempts, leading git to think connections were unsuccessful. Adding git to a whitelist in the AV can be a good workaround. (Do not disable the AV!) Also check from the command-line if you have a credential helper (which might have cached the wrong credentials) git config -l|grep credential See "How to sign out in Git Bash console in Windows?": That is Git for Windows using the latest Microsoft Git Credential Manager for Windows. From the discussion: I tried the cloning in another machine which connected to same network and it worked. Issue is in my machine :( As a last resort, You can also try and use an ssh url (if you have registered a public key on the server side) git remote set-url origin git@github.com:<username>/<reponame> A: In my case it was the TripMode application, since I was allowing specific apps to use the internet bandwidth, so Git and it's related threads could not access to internet. Solution: Stop TripMode or allow Git and it's related threads.
stackoverflow
{ "language": "en", "length": 379, "provenance": "stackexchange_0000F.jsonl.gz:883730", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44600793" }
0bc15482d4598df484df816538336ec9e4b29a01
Stackoverflow Stackexchange Q: fs.readFileSync is not file relative? Node.js Suppose I have a file at the root of my project called file.xml. Suppose I have a test file in tests/ called "test.js" and it has const file = fs.readFileSync("../file.xml"); If I now run node ./tests/test.js from the root of my project it says ../file.xml does not exist. If I run the same command from within the tests directory, then it works. It seems fs.readFileSync is relative to the directory where the script is invoked from, instead of where the script actually is. If I wrote fs.readFileSync("./file.xml") in test.js it would look more confusing and is not consistent with relative paths in a require statement which are file relative. Why is this? How can I avoid having to rewrite the paths in my fs.readFileSync? A: You can resolve the path relative the location of the source file - rather than the current directory - using path.resolve: const path = require("path"); const file = fs.readFileSync(path.resolve(__dirname, "../file.xml"));
Q: fs.readFileSync is not file relative? Node.js Suppose I have a file at the root of my project called file.xml. Suppose I have a test file in tests/ called "test.js" and it has const file = fs.readFileSync("../file.xml"); If I now run node ./tests/test.js from the root of my project it says ../file.xml does not exist. If I run the same command from within the tests directory, then it works. It seems fs.readFileSync is relative to the directory where the script is invoked from, instead of where the script actually is. If I wrote fs.readFileSync("./file.xml") in test.js it would look more confusing and is not consistent with relative paths in a require statement which are file relative. Why is this? How can I avoid having to rewrite the paths in my fs.readFileSync? A: You can resolve the path relative the location of the source file - rather than the current directory - using path.resolve: const path = require("path"); const file = fs.readFileSync(path.resolve(__dirname, "../file.xml")); A: Another alternative if you are using type module is to use process.cwd() package.json { "type": "module", } console.log(process.cwd() + relative_path) // /User/your_user/path_to_folder A: Just to expand on the above, if you are using fs.readFileSync with TypeScript (and of course CommonJS) here's the syntax: import fs from 'fs'; import path from 'path'; const logo = fs.readFileSync(path.resolve(__dirname, './assets/img/logo.svg')); This is because fs.readFileSync() is resolved relative to the current working directory, see the Node.js File System docs for more info. Source: Relative fs.readFileSync paths with Node.js And of course, the CommonJS format: const fs = require('fs'); const path = require('path'); const logo = fs.readFileSync(path.resolve(__dirname, './assets/img/logo.svg'));
stackoverflow
{ "language": "en", "length": 265, "provenance": "stackexchange_0000F.jsonl.gz:883775", "question_score": "185", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44600943" }
dabf5de8fedf788509247faf1f00e55c457decd5
Stackoverflow Stackexchange Q: how to keep values in textfields after submitting a form in laravel 5.2 I have a form to filter data as per the entered from and to date. Everything is working fine but I just want that values should be keep in textfields. I tried as - view - <form action="{{url('user/manage')}}" method="post"> <input type="text" placeholder="From" name="from_date" value="{{old('from_date')}}" id="from_date" class="form-control"> <input type="text" placeholder="To" name="to_date" value="{{old('to_date')}}" id="to_date" class="form-control"> <input type="submit" value="Filter" name="submit" class="btn btn-default"> <input type="text" placeholder="Enter E mail" name="email_search" id="" value="{{old('email_search')}}" class="form-control"> <input type="hidden" name="_token" value="{{{ csrf_token() }}}" /> <input type="submit" value="Show" name="submit" class="btn btn-default"> </form> Controller - $values=[]; $values['from_date']=$from; $values['to_date']=$to; return view('show',['users'=>$users])->withInput($values); Please Help me to solve this. Thanks. A: Input data is stored in the session between requests. Are you redirecting after a request has processed, or are you trying to maintain inputs in the case a request is not validated, i.e. redirected back to the page with error messages? In the first case you can use $request->session()->flash() to keep the data in the session after the request has processed. In the second case, data is flashed automatically and accessible through the old() helper method, as you have in your form example.
Q: how to keep values in textfields after submitting a form in laravel 5.2 I have a form to filter data as per the entered from and to date. Everything is working fine but I just want that values should be keep in textfields. I tried as - view - <form action="{{url('user/manage')}}" method="post"> <input type="text" placeholder="From" name="from_date" value="{{old('from_date')}}" id="from_date" class="form-control"> <input type="text" placeholder="To" name="to_date" value="{{old('to_date')}}" id="to_date" class="form-control"> <input type="submit" value="Filter" name="submit" class="btn btn-default"> <input type="text" placeholder="Enter E mail" name="email_search" id="" value="{{old('email_search')}}" class="form-control"> <input type="hidden" name="_token" value="{{{ csrf_token() }}}" /> <input type="submit" value="Show" name="submit" class="btn btn-default"> </form> Controller - $values=[]; $values['from_date']=$from; $values['to_date']=$to; return view('show',['users'=>$users])->withInput($values); Please Help me to solve this. Thanks. A: Input data is stored in the session between requests. Are you redirecting after a request has processed, or are you trying to maintain inputs in the case a request is not validated, i.e. redirected back to the page with error messages? In the first case you can use $request->session()->flash() to keep the data in the session after the request has processed. In the second case, data is flashed automatically and accessible through the old() helper method, as you have in your form example. A: try this. your form and controller method should be like // form <form action="{{url('user/manage')}}" method="post"> <input type="text" placeholder="From" name="from_date" value="{{$from_date}}" id="from_date" class="form-control"> <input type="text" placeholder="To" name="to_date" value="{{$to_date}}" id="to_date" class="form-control"> <input type="submit" value="Filter" name="submit" class="btn btn-default"> <input type="text" placeholder="Enter E mail" name="email_search" id="" value="{{old('email_search')}}" class="form-control"> <input type="hidden" name="_token" value="{{{ csrf_token() }}}" /> <input type="submit" value="Show" name="submit" class="btn btn-default"> </form> // controller $data = [ 'users'=>$users, 'from_date'=>$from, 'to_date'=>$to; ] return view('show',$data); ]
stackoverflow
{ "language": "en", "length": 265, "provenance": "stackexchange_0000F.jsonl.gz:883799", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601007" }
b5d48e1cb7b7c1bc6c04e7558fe0fc3e4fb662a3
Stackoverflow Stackexchange Q: How to present a landscape only ViewController from portrait bottom of iPhone in swift? I have portrait only app with one screen in landscape only mode. What I did: I created a UINavigationController subclass and overridden the following: import UIKit class LandscapeVCNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .landscape } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { return .landscapeLeft } } Then using this navigationController to present my landscape viewcontroller like this: if let vc = storyboard?.instantiateViewController(withIdentifier: StoryBoardIdentifiers.playerVCStoryboardIdentifier) as? PlayerViewController { let navController = LandscapeVCNavigationController.init(rootViewController: vc) present(navController, animated: true, completion: { }) } This works fine. What I need:I need the landscape VC to be presented from the bottom(home button side) and should dismiss to the bottom(home button side). This is what happens currently. A: You have to add a custom transition animation to change this default behaviour. let transition = CATransition() transition.duration = 0.3 transition.timingFunction = CAMediaTimingFunction(name:kCAMediaTimingFunctionEaseInEaseOut) transition.type = kCATransitionPush transition.subtype = kCATransitionFromLeft self.view!.window!.layer.add(transition, forKey: nil) self.present(navController, animated: false, completion:nil)
Q: How to present a landscape only ViewController from portrait bottom of iPhone in swift? I have portrait only app with one screen in landscape only mode. What I did: I created a UINavigationController subclass and overridden the following: import UIKit class LandscapeVCNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .landscape } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { return .landscapeLeft } } Then using this navigationController to present my landscape viewcontroller like this: if let vc = storyboard?.instantiateViewController(withIdentifier: StoryBoardIdentifiers.playerVCStoryboardIdentifier) as? PlayerViewController { let navController = LandscapeVCNavigationController.init(rootViewController: vc) present(navController, animated: true, completion: { }) } This works fine. What I need:I need the landscape VC to be presented from the bottom(home button side) and should dismiss to the bottom(home button side). This is what happens currently. A: You have to add a custom transition animation to change this default behaviour. let transition = CATransition() transition.duration = 0.3 transition.timingFunction = CAMediaTimingFunction(name:kCAMediaTimingFunctionEaseInEaseOut) transition.type = kCATransitionPush transition.subtype = kCATransitionFromLeft self.view!.window!.layer.add(transition, forKey: nil) self.present(navController, animated: false, completion:nil)
stackoverflow
{ "language": "en", "length": 168, "provenance": "stackexchange_0000F.jsonl.gz:883805", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601029" }
55c5b2c67322187315b410adbfcef360df2f24b1
Stackoverflow Stackexchange Q: Styling components with inline CSS - Ionic2, AngularJS I am trying to append an inline CSS rule for background-image using a dynamic variable set inside the constructor like so: <div style="background-image: url('{{backgroundImage}}');"> ... </div> then in my Component: export class SomeComponent { backgroundImage = ''; constructor(public navCtrl: NavController, public navParams: NavParams) { this.backgroundImage = 'https://unsplash.it/200/300' ; } } However, when the element is rendered to the screen, the inline CSS rule gets omitted. I tried using Angular's ng-style, but it returns "Can't bind to 'ng-style' since it isn't a known property of 'div'". I also tried setting styles inside my @Component declaration as noted in this answer, but this wouldn't fly in my case, as I need the backgroundImage variable to be dynamic. A: Since Ionic2 (or just Ionic) is built on top of Angular (an not AngularJS), you can do that like this: <div [ngStyle]="{ background: 'url(' + backgroundImage + ')' }"></div> or <div [style.background]="'url(' + backgroundImage + ')'"></div>
Q: Styling components with inline CSS - Ionic2, AngularJS I am trying to append an inline CSS rule for background-image using a dynamic variable set inside the constructor like so: <div style="background-image: url('{{backgroundImage}}');"> ... </div> then in my Component: export class SomeComponent { backgroundImage = ''; constructor(public navCtrl: NavController, public navParams: NavParams) { this.backgroundImage = 'https://unsplash.it/200/300' ; } } However, when the element is rendered to the screen, the inline CSS rule gets omitted. I tried using Angular's ng-style, but it returns "Can't bind to 'ng-style' since it isn't a known property of 'div'". I also tried setting styles inside my @Component declaration as noted in this answer, but this wouldn't fly in my case, as I need the backgroundImage variable to be dynamic. A: Since Ionic2 (or just Ionic) is built on top of Angular (an not AngularJS), you can do that like this: <div [ngStyle]="{ background: 'url(' + backgroundImage + ')' }"></div> or <div [style.background]="'url(' + backgroundImage + ')'"></div>
stackoverflow
{ "language": "en", "length": 161, "provenance": "stackexchange_0000F.jsonl.gz:883835", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601123" }
444b7cf65905c4c659e0fcbdeadd197db933f223
Stackoverflow Stackexchange Q: Kubernetes on GCE: Ingress Timeout Configuration I'm running Kubernetes on Google Compute Engine (GCE). I have an Ingress set up. Everything works perfectly except when I upload large files, the L7 HTTPS Load Balancer terminates the connection after 30 seconds. I know that I can bump this up manually in the "Backend Service", but I'm wondering if there is a way to do this from the Ingress spec. I worry that my manual tweak will get changed back to 30s later on. The nginx ingress controller has a number of annotations that can be used to configure nginx. Does the GCE L7 Load Balancer have something similar? A: This can now be configured within GKE, by using a custom resource BackendConfig. apiVersion: cloud.google.com/v1beta1 kind: BackendConfig metadata: name: my-bconfig spec: timeoutSec: 60 And then configuring your Service to use this configuration with an annotation: apiVersion: v1 kind: Service metadata: name: my-service annotations: beta.cloud.google.com/backend-config: '{"ports": {"80":"my-bconfig"}}' spec: ports: - port: 80 .... other fields See Configuring a backend service through Ingress
Q: Kubernetes on GCE: Ingress Timeout Configuration I'm running Kubernetes on Google Compute Engine (GCE). I have an Ingress set up. Everything works perfectly except when I upload large files, the L7 HTTPS Load Balancer terminates the connection after 30 seconds. I know that I can bump this up manually in the "Backend Service", but I'm wondering if there is a way to do this from the Ingress spec. I worry that my manual tweak will get changed back to 30s later on. The nginx ingress controller has a number of annotations that can be used to configure nginx. Does the GCE L7 Load Balancer have something similar? A: This can now be configured within GKE, by using a custom resource BackendConfig. apiVersion: cloud.google.com/v1beta1 kind: BackendConfig metadata: name: my-bconfig spec: timeoutSec: 60 And then configuring your Service to use this configuration with an annotation: apiVersion: v1 kind: Service metadata: name: my-service annotations: beta.cloud.google.com/backend-config: '{"ports": {"80":"my-bconfig"}}' spec: ports: - port: 80 .... other fields See Configuring a backend service through Ingress A: For anyone else looking for the solution to this problem, timeout and other settings (e.g. enable CDN) can only be configured manually at the moment. Follow this kubernetes/ingress-gce issue for the latest updates on a long-term solution.
stackoverflow
{ "language": "en", "length": 208, "provenance": "stackexchange_0000F.jsonl.gz:883859", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601191" }
1dac49382d2c7f5d9a166cbc31d2d22269c1b795
Stackoverflow Stackexchange Q: location.search.match in java script Hi everyone I'm beginner CTF player and I have same lake with javascript and I face following problem I couldn't understand what is the intention of following line location.search.match(/e=(.*)/)[1])) This is complete code if(location.search) { var div = document.currentScript.parentNode.appendChild(document.createElement('div')); div.className = 'alert alert-danger'; div.role = 'alert'; div.appendChild(document.createTextNode(unescape(location.search.match(/e=(.*)/)[1]))); } can u help me to understand it A: location.search basically give you the query string part of the current URL and and match has been used to extract e parameter value from the query string with a regular expression. As an example, if the current URL is like https://www.example.com/?e=someone@example.com then location.search.match(/e=(.*)/)[1] will give you 'someone@example.com'. Rest of the code basically create a div element and set extracted text as a child of it and finally append that div as a child of parent node of the currently running script tag.
Q: location.search.match in java script Hi everyone I'm beginner CTF player and I have same lake with javascript and I face following problem I couldn't understand what is the intention of following line location.search.match(/e=(.*)/)[1])) This is complete code if(location.search) { var div = document.currentScript.parentNode.appendChild(document.createElement('div')); div.className = 'alert alert-danger'; div.role = 'alert'; div.appendChild(document.createTextNode(unescape(location.search.match(/e=(.*)/)[1]))); } can u help me to understand it A: location.search basically give you the query string part of the current URL and and match has been used to extract e parameter value from the query string with a regular expression. As an example, if the current URL is like https://www.example.com/?e=someone@example.com then location.search.match(/e=(.*)/)[1] will give you 'someone@example.com'. Rest of the code basically create a div element and set extracted text as a child of it and finally append that div as a child of parent node of the currently running script tag. A: Here is my working example: This URL have multiple query parameters, such as: config=xxx & zoom=17 & lat=xxx etc... I want to extract each query parameters one by one. http://localhost:10/mapserver1/viewer/?config=viewer_simple1&mapserver_url=https://maps2.dcgis.dc.gov/dcgis/rest/services/Zoning/MapServer&zoom=17&lat=38.917292&long=-77.036420 This is how you do (working code): var ___zoom = location.search.match(/zoom=([^&]*)/i)[1]; var ___lat = location.search.match(/lat=([^&]*)/i)[1]; var ___long = location.search.match(/long=([^&]*)/i)[1]; var ___basemap = location.search.match(/basemap=([^&]*)/i)[1]; var ___type = location.search.match(/type=([^&]*)/i)[1]; var ___url = location.search.match(/url=([^&]*)/i)[1]; var ___title = location.search.match(/title=([^&]*)/i)[1]; var ___opacity = location.search.match(/opacity=([^&]*)/i)[1]; //console.log(location.search.match(/zoom=([^&]*)/i)[0]); // 'zoom=17' //console.log(location.search.match(/zoom=([^&]*)/i)[1]); // '17' console.log(___zoom); console.log(___lat); console.log(___long); console.log(___basemap); console.log(___type); console.log(___url); console.log(___title); console.log(___opacity); A: This is my fully working code: first check if parameter exist, if does, then extract it. var ___zoom; var ___lat; var ___long; var ___basemap; var ___type; var ___url; var ___title; var ___opacity; /* * if (value) { * * } * * will evaluate to true if value is not: null undefined NaN empty string ("") false 0 * * * */ if ( location.search.match(/zoom=([^&]*)/i) ) { ___zoom = location.search.match(/zoom=([^&]*)/i)[1]; } if ( location.search.match(/lat=([^&]*)/i) ) { ___lat = location.search.match(/lat=([^&]*)/i)[1]; } if (location.search.match(/long=([^&]*)/i)) { ___long = location.search.match(/long=([^&]*)/i)[1]; } if (location.search.match(/basemap=([^&]*)/i)) { ___basemap = location.search.match(/basemap=([^&]*)/i)[1]; } if (location.search.match(/type=([^&]*)/i)) { ___type = location.search.match(/type=([^&]*)/i)[1]; } if (location.search.match(/url=([^&]*)/i)) { ___url = location.search.match(/url=([^&]*)/i)[1]; } if (location.search.match(/title=([^&]*)/i)) { ___title = location.search.match(/title=([^&]*)/i)[1]; } if (location.search.match(/opacity=([^&]*)/i)) { ___opacity = location.search.match(/opacity=([^&]*)/i)[1]; } //console.log(location.search.match(/zoom=([^&]*)/i)[0]); // 'zoom=17' //console.log(location.search.match(/zoom=([^&]*)/i)[1]); // '17' console.log(___zoom); console.log(___lat); console.log(___long); console.log(___basemap); console.log(___type); console.log(___url); console.log(___title); console.log(___opacity);
stackoverflow
{ "language": "en", "length": 364, "provenance": "stackexchange_0000F.jsonl.gz:883875", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601229" }
1e5e14daffa276ca83a114f1c5730963504eff9a
Stackoverflow Stackexchange Q: how to merge two nested dictionaries under a same dictionary for example I have a dictionary: dictA={"nest1":{"01feb":[1,2,3,4,5],"02feb":[1,7,8,9,10]}, "nest2":{"01feb":[1,2,3,4,5],"02feb":[6,4,8,10,10]}} the list inside has the same length. I need to merge nest1 and nest2 as one dictionary, and the result should be like this: dictA={"nest":{"01feb":[2,4,6,8,10],"02feb":[7,11,16,19,20]}} A: You can use a dict comprehension, map() and zip() like this example (works with Python 2 and Python 3). dictA = {'nest1': {'01feb': [1, 2, 3, 4, 5], '02feb': [1, 7, 8, 9, 10]}, 'nest2': {'01feb': [1, 2, 3, 4, 5], '02feb': [6, 4, 8, 10, 10]}} a = (v.items() for _, v in map(list, dictA.items())) # You can also use another map(): # final = {'nest': {k: list(map(sum, zip(v,j))) for (k, v), (_, j) in zip(*a)}} final = {'nest': {k: [m+n for m, n in zip(v, j)] for (k, v), (_, j) in zip(*a)}} print(final) Output: {'nest': {'02feb': [7, 11, 16, 19, 20], '01feb': [2, 4, 6, 8, 10]}}
Q: how to merge two nested dictionaries under a same dictionary for example I have a dictionary: dictA={"nest1":{"01feb":[1,2,3,4,5],"02feb":[1,7,8,9,10]}, "nest2":{"01feb":[1,2,3,4,5],"02feb":[6,4,8,10,10]}} the list inside has the same length. I need to merge nest1 and nest2 as one dictionary, and the result should be like this: dictA={"nest":{"01feb":[2,4,6,8,10],"02feb":[7,11,16,19,20]}} A: You can use a dict comprehension, map() and zip() like this example (works with Python 2 and Python 3). dictA = {'nest1': {'01feb': [1, 2, 3, 4, 5], '02feb': [1, 7, 8, 9, 10]}, 'nest2': {'01feb': [1, 2, 3, 4, 5], '02feb': [6, 4, 8, 10, 10]}} a = (v.items() for _, v in map(list, dictA.items())) # You can also use another map(): # final = {'nest': {k: list(map(sum, zip(v,j))) for (k, v), (_, j) in zip(*a)}} final = {'nest': {k: [m+n for m, n in zip(v, j)] for (k, v), (_, j) in zip(*a)}} print(final) Output: {'nest': {'02feb': [7, 11, 16, 19, 20], '01feb': [2, 4, 6, 8, 10]}} A: Plese find the below code for your query. dictA={"nest1":{"01feb":[1,2,3,4,5],"02feb":[1,7,8,9,10]}, "nest2":{"01feb":[1,2,3,4,5],"02feb":[6,4,8,10,10]}} result ={} final_op = {} for k,v in dictA.iteritems(): for nk,nv in v.iteritems(): if result.has_key(nk): i=0 while i < len(result[nk]): result[nk][i] += nv[i] i += 1 else: result[nk] = nv final_op['nest'] = result print final_op Output: {'nest': {'02feb': [7, 11, 16, 19, 20], '01feb': [2, 4, 6, 8, 10]}} A: You have to traverse the dict and update the value in the iteration. dictA={"nest1":{"01feb":[1,2,3,4,5],"02feb":[1,7,8,9,10]}, "nest2":{"01feb":[1,2,3,4,5],"02feb":[6,4,8,10,10]}} def merge(dictA): merge_dict = {} for key in dictA: for sub_key in dictA[key]: if sub_key in merge_dict: # update the nested value merge_dict[sub_key] = [sum(x) for x in zip(*[merge_dict[sub_key], dictA[key][sub_key]])] else: merge_dict[sub_key] = dictA[key][sub_key] return merge_dict merge_dict = merge(dictA) dictA.clear() dictA["nest"] = merge_dict print(dictA) A: Here is a function to do what you're asking for: def merge_nested(dictionary): result = dict() for nested in dictionary.values(): for key in nested.keys(): if key in result: # We've already found it, add our values to it's for i in range(len(result[key])): result[key][i] += nested[key][i] else: result[key] = nested[key] return {"nest":result} With this function you get the following output: >>> print(merge_nested({"nest1":{"01feb":[1,2,3,4,5],"02feb":[1,7,8,9,10]},"nest2":{"01feb":[1,2,3,4,5],"02feb":[6,4,8,10,10]}})) {'nest': {'01feb': [2, 4, 6, 8, 10], '02feb': [7, 11, 16, 19, 20]}} This is a modified version of @Arockia's answer here A: A solution with groupby of itertools: from itertools import chain, groupby import operator dictA={"nest1":{"01feb":[1,2,3,4,5],"02feb":[1,7,8,9,10]}, "nest2":{"01feb":[1,2,3,4,5],"02feb":[6,4,8,10,10]}} A = { "nest": dict( (key, list(map(operator.add, *(v for _, v in group)))) for key, group in groupby( sorted( chain(*(v.iteritems() for v in dictA.values())) # Python 2 # chain(*(v.items() for v in dictA.values())) # Python 3 ), lambda x: x[0], ) ) } print(A) Result: {'nest': {'02feb': [7, 11, 16, 19, 20], '01feb': [2, 4, 6, 8, 10]}}
stackoverflow
{ "language": "en", "length": 432, "provenance": "stackexchange_0000F.jsonl.gz:883881", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601256" }
5fa59680534dc9b9ca7d0ad491b58720d2096056
Stackoverflow Stackexchange Q: groupby column while showing other columns I have a dataset as follows: name | $ | letter adam, 34, c beny, 45, e adam, 55, a beny, 87, t I'd like to extract the max $ donated by each name, with the respective letter. So for Adam, I would get: adam,55,a. If I use: df.groupby('name')[['$']].max() that doesn't give me the respective letter. If I use: df.groupby('name')[['$','letter']].max() I get the max $ and the highest letter in the alphabet. A: Use DataFrameGroupBy.idxmax for indexes of max values and then select by loc: print (df.groupby('name')['$'].idxmax()) name adam 2 beny 3 Name: $, dtype: int64 df = df.loc[df.groupby('name')['$'].idxmax()] print (df) name $ letter 2 adam 55 a 3 beny 87 t Another solution with sort_values first and then use GroupBy.last: df = df.sort_values('$').groupby('name', as_index=False).last() print (df) name $ letter 0 adam 55 a 1 beny 87 t Difference in solutions is idxmax let original indexes, last reset them.
Q: groupby column while showing other columns I have a dataset as follows: name | $ | letter adam, 34, c beny, 45, e adam, 55, a beny, 87, t I'd like to extract the max $ donated by each name, with the respective letter. So for Adam, I would get: adam,55,a. If I use: df.groupby('name')[['$']].max() that doesn't give me the respective letter. If I use: df.groupby('name')[['$','letter']].max() I get the max $ and the highest letter in the alphabet. A: Use DataFrameGroupBy.idxmax for indexes of max values and then select by loc: print (df.groupby('name')['$'].idxmax()) name adam 2 beny 3 Name: $, dtype: int64 df = df.loc[df.groupby('name')['$'].idxmax()] print (df) name $ letter 2 adam 55 a 3 beny 87 t Another solution with sort_values first and then use GroupBy.last: df = df.sort_values('$').groupby('name', as_index=False).last() print (df) name $ letter 0 adam 55 a 1 beny 87 t Difference in solutions is idxmax let original indexes, last reset them.
stackoverflow
{ "language": "en", "length": 156, "provenance": "stackexchange_0000F.jsonl.gz:883893", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601293" }
34068901dff60dcfb8b2215dba413c4faab56cad
Stackoverflow Stackexchange Q: Unable to query projects using Tuleap REST API I am using Tuleap API to query projects using the below API https://alm.test.com/api/projects?query={"shortname":"myproject"} When I call this API, Its not returning results for the project "myproject" rather its returning all projects in Tuleap. I used the same REST API on Tuleap API Explorer it works. Am I missing something ?
Q: Unable to query projects using Tuleap REST API I am using Tuleap API to query projects using the below API https://alm.test.com/api/projects?query={"shortname":"myproject"} When I call this API, Its not returning results for the project "myproject" rather its returning all projects in Tuleap. I used the same REST API on Tuleap API Explorer it works. Am I missing something ?
stackoverflow
{ "language": "en", "length": 59, "provenance": "stackexchange_0000F.jsonl.gz:883894", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601299" }
711840ef159d2f20091fbaf66150dc5c62f1dd41
Stackoverflow Stackexchange Q: Error in adding location service to android custom ROM I wrote a Location Service in android . and in AndroidManifest.xml i defined two intent-filters : <service android:name=".LocationServiceV2" android:exported="true" android:permission="android.permission.ACCESS_COARSE_LOCATION"> <intent-filter> <action android:name="com.android.location.service.v3.NetworkLocationProvider" /> <action android:name="com.android.location.service.v2.NetworkLocationProvider" /> </intent-filter> <meta-data android:name="serviceVersion" android:value="2" /> <meta-data android:name="serviceIsMultiuser" android:value="false" /> </service> but when I run in Nexus 5x in logcat displays this error : com.example.user.nlpservice resolves service com.android.location.service.v3.NetworkLocationProvider , but has wrong signature , ignoring What means by wrong signature and how I can fix this problem? A: For adding a location service in android , you should add package name of location service in following file in AOSP build tree to register it. {AOSP BUILD TREE}/frameworks/base/core/res/res/values/config.xml In above file ,there is a config named config_locationProviderPackageNames add an item and write your location service package name (for example com.example.app1) in it. Build your android os then, the system binds to it and it works.
Q: Error in adding location service to android custom ROM I wrote a Location Service in android . and in AndroidManifest.xml i defined two intent-filters : <service android:name=".LocationServiceV2" android:exported="true" android:permission="android.permission.ACCESS_COARSE_LOCATION"> <intent-filter> <action android:name="com.android.location.service.v3.NetworkLocationProvider" /> <action android:name="com.android.location.service.v2.NetworkLocationProvider" /> </intent-filter> <meta-data android:name="serviceVersion" android:value="2" /> <meta-data android:name="serviceIsMultiuser" android:value="false" /> </service> but when I run in Nexus 5x in logcat displays this error : com.example.user.nlpservice resolves service com.android.location.service.v3.NetworkLocationProvider , but has wrong signature , ignoring What means by wrong signature and how I can fix this problem? A: For adding a location service in android , you should add package name of location service in following file in AOSP build tree to register it. {AOSP BUILD TREE}/frameworks/base/core/res/res/values/config.xml In above file ,there is a config named config_locationProviderPackageNames add an item and write your location service package name (for example com.example.app1) in it. Build your android os then, the system binds to it and it works.
stackoverflow
{ "language": "en", "length": 150, "provenance": "stackexchange_0000F.jsonl.gz:883895", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601305" }
b787775b15bb5515658ece7be098acc9ac1101d6
Stackoverflow Stackexchange Q: Can we have multiple get method in apiview class django rest framework Am using django rest framework with apiviews. I'd like to use multiple get method in the apiview class and seperate with the name of the medthod in the urls file. A: You can use viewsets instead of apiview for this purpose. Here's an example. from rest_framework import viewsets from rest_framework.decorators import detail_route from rest_framework.response import Response class MyViewSet(viewsets.GenericViewSet): @detail_route(methods=['get']) def some_get_method(self, request, pk=None): return Response({'data': 'response_data'}) In order to use it, your URL will be like, http://base_url/< pk >/some_get_method or you can override dispatch method inside of APIView to do so, def MyAPIView(APIView): def some_get_method(self, request): return Response({'data': 'response_data'}) def dispatch(self, request, *args, **kwargs): if request.method.lower() == "get" and request.GET.get('identifier'): return self.some_get_method(request) return super().dispatch(request, *args, **kwargs)
Q: Can we have multiple get method in apiview class django rest framework Am using django rest framework with apiviews. I'd like to use multiple get method in the apiview class and seperate with the name of the medthod in the urls file. A: You can use viewsets instead of apiview for this purpose. Here's an example. from rest_framework import viewsets from rest_framework.decorators import detail_route from rest_framework.response import Response class MyViewSet(viewsets.GenericViewSet): @detail_route(methods=['get']) def some_get_method(self, request, pk=None): return Response({'data': 'response_data'}) In order to use it, your URL will be like, http://base_url/< pk >/some_get_method or you can override dispatch method inside of APIView to do so, def MyAPIView(APIView): def some_get_method(self, request): return Response({'data': 'response_data'}) def dispatch(self, request, *args, **kwargs): if request.method.lower() == "get" and request.GET.get('identifier'): return self.some_get_method(request) return super().dispatch(request, *args, **kwargs)
stackoverflow
{ "language": "en", "length": 129, "provenance": "stackexchange_0000F.jsonl.gz:883903", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601327" }
506a66d4dc5f1e58b6831cc7ce3c588eb90f9f12
Stackoverflow Stackexchange Q: Dynamic CSS Classes in Angular2+ HTML: <div *ngFor="let record of lift" class="list-lifts" [class.showLifts]="isBtnActive"> Component: isBtnActive: boolean = false; toggleClass() { this.isBtnActive = !this.isBtnActive; } CSS: .list-lifts { &:not(:first-of-type) { margin-top: -11px !important; display: none; } } .showLifts { display: block !important; } // I need something like this to be built in the view: .ValueshowLifts {} The toggleClass() function toggles the CSS class .showLifts on the click of a button. This works great. The issue is, I need the class .showLifts to have a dynamic name and I'm not sure what the syntax is to produce it. For logical reasons, here's an example: [class.{{ record.name }}showLifts]="isBtnActive" But of course this isn't valid syntax. A: As others have mentioned you can use [ngClass]. An answer was posted here: Dynamic classname inside ngClass in angular 2 But I wanted to mention that if you're using CSS to only hide or show elements, then instead you can use *ngIf or [hidden], depending if you want the element in the DOM or not.
Q: Dynamic CSS Classes in Angular2+ HTML: <div *ngFor="let record of lift" class="list-lifts" [class.showLifts]="isBtnActive"> Component: isBtnActive: boolean = false; toggleClass() { this.isBtnActive = !this.isBtnActive; } CSS: .list-lifts { &:not(:first-of-type) { margin-top: -11px !important; display: none; } } .showLifts { display: block !important; } // I need something like this to be built in the view: .ValueshowLifts {} The toggleClass() function toggles the CSS class .showLifts on the click of a button. This works great. The issue is, I need the class .showLifts to have a dynamic name and I'm not sure what the syntax is to produce it. For logical reasons, here's an example: [class.{{ record.name }}showLifts]="isBtnActive" But of course this isn't valid syntax. A: As others have mentioned you can use [ngClass]. An answer was posted here: Dynamic classname inside ngClass in angular 2 But I wanted to mention that if you're using CSS to only hide or show elements, then instead you can use *ngIf or [hidden], depending if you want the element in the DOM or not. A: You can leverage ngClass directive here [ngClass]="showLiftsClass" Inside your code you can dynamically add css classes to it as follows, showLiftsClass = { 'record1showLifts' : true, 'record2showLifts' : false, 'record3showLifts' : false, 'record4showLifts' : false ... } You can have single or multiple classes as a true. Value true will add the class to the DOM element. A: <div class="form-group label-floating" [ngClass]="{'is-empty': true, 'second-class' : true}"></div> A: Try this: <div *ngFor="let record of lift; ; let i=index" class="list-lifts" [ngClass]="{'showLifts': isBtnActive}"> Or you can Use: *ngIf *ngIf="expression" (e.g. *ngIf="i!=0" or *ngIf="i==0")
stackoverflow
{ "language": "en", "length": 261, "provenance": "stackexchange_0000F.jsonl.gz:883910", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601343" }
eca96bf918f7f22c1fa4b3a4a662d768bd1eabcb
Stackoverflow Stackexchange Q: How to disable the context menu of a QDockWidget title bar I have a couple of QDockWidgets that are all not closabale (using Qt 5.6). Therefore, the context menu that is displayed when right-clicking a title bar of one of them only has disabled entries, and I would like to disable the whole context menu. I tried to set the contextMenuPolicy to NoContextMenu without success. I then tried to use a subclass of QDockWidget, override the ContextMenuEvent and ignore it. The menu is still displayed. I then tried to install an event filter to catch the ContextMenuEvent, but it did not catch any, just PaintEvents, ResizeEvents etc. I'm out of ideas … any help would be greatly appreciated! A: As per the comments it is necessary to set the context menu policy on the QDockWidget to Qt::PreventContextMenu... dock_widget->setContextMenuPolicy(Qt::PreventContextMenu); rather than simply Qt::NoContextMenu. From the documentation Qt::NoContextMenu simply defers the context menu handling to the parent widget rather than preventing it entirely.
Q: How to disable the context menu of a QDockWidget title bar I have a couple of QDockWidgets that are all not closabale (using Qt 5.6). Therefore, the context menu that is displayed when right-clicking a title bar of one of them only has disabled entries, and I would like to disable the whole context menu. I tried to set the contextMenuPolicy to NoContextMenu without success. I then tried to use a subclass of QDockWidget, override the ContextMenuEvent and ignore it. The menu is still displayed. I then tried to install an event filter to catch the ContextMenuEvent, but it did not catch any, just PaintEvents, ResizeEvents etc. I'm out of ideas … any help would be greatly appreciated! A: As per the comments it is necessary to set the context menu policy on the QDockWidget to Qt::PreventContextMenu... dock_widget->setContextMenuPolicy(Qt::PreventContextMenu); rather than simply Qt::NoContextMenu. From the documentation Qt::NoContextMenu simply defers the context menu handling to the parent widget rather than preventing it entirely.
stackoverflow
{ "language": "en", "length": 162, "provenance": "stackexchange_0000F.jsonl.gz:883917", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601362" }
8a6500d1ea6f328711e44868abab27fd4149cd86
Stackoverflow Stackexchange Q: How to resolve missing Java EE Server Libraries in Netbeans Can you suggest how to add server in the libraries section of netbeans for Java. A: To resolve this issue, you need to add Server to Netbeans -> Service list. You could also follow below steps : 1. Identify the project, which has missing server libraries 2. Right click on project and click Resolve Missing Server Problem.. 3. Then, Select the appropriate Server as per your project requirement, if not available in the list, then add the server. Now, you can verify your project.
Q: How to resolve missing Java EE Server Libraries in Netbeans Can you suggest how to add server in the libraries section of netbeans for Java. A: To resolve this issue, you need to add Server to Netbeans -> Service list. You could also follow below steps : 1. Identify the project, which has missing server libraries 2. Right click on project and click Resolve Missing Server Problem.. 3. Then, Select the appropriate Server as per your project requirement, if not available in the list, then add the server. Now, you can verify your project.
stackoverflow
{ "language": "en", "length": 95, "provenance": "stackexchange_0000F.jsonl.gz:883922", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601373" }
4f4c2960c6764127e66fce4ef12928649091ad60
Stackoverflow Stackexchange Q: What is the unit of the ruler in Android studio layout editor? What is the unit of the ruler in Android studio layout editor? I chose Nexus 5 and the screen size of Nexus 5 is 360dp x 640dp or 1080px x 1920px It's neither dp nor px. What is it? Can I change the unit? A: I think it's dp fixed in xhdpi screen. You can see when select Nexus 5 (1080px width), its screen take approx 550 unit in horizontal ruler.
Q: What is the unit of the ruler in Android studio layout editor? What is the unit of the ruler in Android studio layout editor? I chose Nexus 5 and the screen size of Nexus 5 is 360dp x 640dp or 1080px x 1920px It's neither dp nor px. What is it? Can I change the unit? A: I think it's dp fixed in xhdpi screen. You can see when select Nexus 5 (1080px width), its screen take approx 550 unit in horizontal ruler.
stackoverflow
{ "language": "en", "length": 84, "provenance": "stackexchange_0000F.jsonl.gz:883923", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601375" }
112047c1413f8a58e1763d6a622ee6805e937fc7
Stackoverflow Stackexchange Q: Dynamic Angular Components without defining them in entryComponents array How can we create components dynamically without defining in entryComponents and declarations array. I would like to include components like plugins(like wordpress plugins) so that angular can scan one folder and run components dynamically, I don know if it is possible with angular core, or with any npm module or custom implementation. However I read the book Mastering Angular2 Componets Chapter 10 based on Mastering Angular Components , I tried creating sample angular 4 app with this approach but dynamic components are not getting created without defining them in my module's entryComponents array. Please suggest any way to achieve this without defining them to entryComponents and declarations,
Q: Dynamic Angular Components without defining them in entryComponents array How can we create components dynamically without defining in entryComponents and declarations array. I would like to include components like plugins(like wordpress plugins) so that angular can scan one folder and run components dynamically, I don know if it is possible with angular core, or with any npm module or custom implementation. However I read the book Mastering Angular2 Componets Chapter 10 based on Mastering Angular Components , I tried creating sample angular 4 app with this approach but dynamic components are not getting created without defining them in my module's entryComponents array. Please suggest any way to achieve this without defining them to entryComponents and declarations,
stackoverflow
{ "language": "en", "length": 117, "provenance": "stackexchange_0000F.jsonl.gz:883940", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601409" }
6f46e05392109dc91f3d2f43817b809bd5abf04d
Stackoverflow Stackexchange Q: How to update values in RecyclerView on onResume()? I'm designing a news app in which I'm showing the news articles in a recyclerView. Now on clicking a news article I want to change its background color to indicate that the news item has been read. For this, first I update a status field corresponding to the news article in my Firebase Database when the news is read. Then I check the value of this field in my recycler Adapter and change the background if the status is changed. However since the adapter of the recyclerView is defined in the onCreateView of the fragment, the change does not take place immediately when I press the back button. Rather the changes occur when reopen the app since the onCreateView is called that time. So how do I update the adapter in onResume of the fragment and update the recyclerView accordingly? A: Override the onResume method and call notifyDataSetChanged: @Override public void onResume() { super.onResume(); adapter.notifyDataSetChanged(); } In Kotlin: override fun onResume() { super.onResume() adapter.notifyDataSetChanged() }
Q: How to update values in RecyclerView on onResume()? I'm designing a news app in which I'm showing the news articles in a recyclerView. Now on clicking a news article I want to change its background color to indicate that the news item has been read. For this, first I update a status field corresponding to the news article in my Firebase Database when the news is read. Then I check the value of this field in my recycler Adapter and change the background if the status is changed. However since the adapter of the recyclerView is defined in the onCreateView of the fragment, the change does not take place immediately when I press the back button. Rather the changes occur when reopen the app since the onCreateView is called that time. So how do I update the adapter in onResume of the fragment and update the recyclerView accordingly? A: Override the onResume method and call notifyDataSetChanged: @Override public void onResume() { super.onResume(); adapter.notifyDataSetChanged(); } In Kotlin: override fun onResume() { super.onResume() adapter.notifyDataSetChanged() } A: Initialize and set adapter from oncreateview(); Then you only need to update adapter data and call adapter.notifyDataSetChanged(); form your onResume(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { YourAdapter adapter = new YourAdapter(listofdata); yourRecycleView.setAdapter(adapter); } @Override public void onResume() { super.onResume(); listofdata.clear(); //Reset before update adapter to avoid duplication of list //update listofdata adapter.notifyDataSetChanged(); } A: add your codes to update data and notify Adapter @Override public void onResume() { super.onResume(); /// code to update data then notify Adapter adapter.notifyDataSetChanged(); }
stackoverflow
{ "language": "en", "length": 255, "provenance": "stackexchange_0000F.jsonl.gz:883944", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601422" }
69224eb1adb3265fae9f533a863f023015edaec5
Stackoverflow Stackexchange Q: Cmake Could NOT find PythonLibs I'm trying to download YouCompleteMe for Vim on Windows following this tutorial. When calling CMake: cmake -G "Visual Studio 14 Win64" -DPATH_TO_LLVM_ROOT=%USERPROFILE%/ycm_temp/llvm_root_dir . %USERPROFILE%/vimfiles/bundle/YouCompleteMe/third_party/ycmd/cpp It throws the following exception: CMake Error at C:/Program Files/CMake/share/cmake-3.9/Modules/FindPackageHandleStandardArgs.cmake:137 (message): Could NOT find PythonLibs (missing: PYTHON_LIBRARIES PYTHON_INCLUDE_DIRS) (Required is at least version "2.6") Call Stack (most recent call first): C:/Program Files/CMake/share/cmake-3.9/Modules/FindPackageHandleStandardArgs.cmake:377 (_FPHSA_FAILURE_MESSAGE) C:/Program Files/CMake/share/cmake-3.9/Modules/FindPythonLibs.cmake:262 (FIND_PACKAGE_HANDLE_STANDARD_ARGS) CMakeLists.txt:189 (find_package) I have installed python-2.7.13, and put it under PATH in Environment Variables. What should I do to fix the exception? A: Instead of using: cmake -G "Visual Studio 14 Win64" -DPATH_TO_LLVM_ROOT=%USERPROFILE%/ycm_temp/llvm_root_dir . %USERPROFILE%/vimfiles/bundle/YouCompleteMe/third_party/ycmd/cpp You should set the DPYTHON_INCLUDE_DIR and DPYTHON_LIBRARY flags to something like below: -DPYTHON_INCLUDE_DIR=C:\Python27\include \ -DPYTHON_LIBRARY=C:\Python27\libs If you use the default install path (C:\Python27), the full command is shown below: cmake -G "Visual Studio 14 Win64" -DPATH_TO_LLVM_ROOT=%USERPROFILE%/ycm_temp/llvm_root_dir . %USERPROFILE%/vimfiles/bundle/YouCompleteMe/third_party/ycmd/cpp -DPYTHON_INCLUDE_DIR=C:\Python27\include -DPYTHON_LIBRARY=C:\Python27\libs
Q: Cmake Could NOT find PythonLibs I'm trying to download YouCompleteMe for Vim on Windows following this tutorial. When calling CMake: cmake -G "Visual Studio 14 Win64" -DPATH_TO_LLVM_ROOT=%USERPROFILE%/ycm_temp/llvm_root_dir . %USERPROFILE%/vimfiles/bundle/YouCompleteMe/third_party/ycmd/cpp It throws the following exception: CMake Error at C:/Program Files/CMake/share/cmake-3.9/Modules/FindPackageHandleStandardArgs.cmake:137 (message): Could NOT find PythonLibs (missing: PYTHON_LIBRARIES PYTHON_INCLUDE_DIRS) (Required is at least version "2.6") Call Stack (most recent call first): C:/Program Files/CMake/share/cmake-3.9/Modules/FindPackageHandleStandardArgs.cmake:377 (_FPHSA_FAILURE_MESSAGE) C:/Program Files/CMake/share/cmake-3.9/Modules/FindPythonLibs.cmake:262 (FIND_PACKAGE_HANDLE_STANDARD_ARGS) CMakeLists.txt:189 (find_package) I have installed python-2.7.13, and put it under PATH in Environment Variables. What should I do to fix the exception? A: Instead of using: cmake -G "Visual Studio 14 Win64" -DPATH_TO_LLVM_ROOT=%USERPROFILE%/ycm_temp/llvm_root_dir . %USERPROFILE%/vimfiles/bundle/YouCompleteMe/third_party/ycmd/cpp You should set the DPYTHON_INCLUDE_DIR and DPYTHON_LIBRARY flags to something like below: -DPYTHON_INCLUDE_DIR=C:\Python27\include \ -DPYTHON_LIBRARY=C:\Python27\libs If you use the default install path (C:\Python27), the full command is shown below: cmake -G "Visual Studio 14 Win64" -DPATH_TO_LLVM_ROOT=%USERPROFILE%/ycm_temp/llvm_root_dir . %USERPROFILE%/vimfiles/bundle/YouCompleteMe/third_party/ycmd/cpp -DPYTHON_INCLUDE_DIR=C:\Python27\include -DPYTHON_LIBRARY=C:\Python27\libs
stackoverflow
{ "language": "en", "length": 141, "provenance": "stackexchange_0000F.jsonl.gz:883979", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601548" }
de5ad62c334d2c33af8b552e7922ba17c2a5ec69
Stackoverflow Stackexchange Q: Why doesn't a reference to an array work until we use a pointer? This works very well... int a[5] = {1,2,3,4,5}, int *p = a; int *& ref = p; But why doesn't this work? int a[5] = {1,2,3,4,5}; int*& ref = a; Both a and p are pointers and have the same value (address of a[0]). When I make reference to an array using a pointer (p), it works very well. But when I make reference to that array a[] directly, it doesn't work... Why? A: Adding on to what has already been answered, you can get a reference to an array like int a[5]; int (&ref)[5] = a; Live
Q: Why doesn't a reference to an array work until we use a pointer? This works very well... int a[5] = {1,2,3,4,5}, int *p = a; int *& ref = p; But why doesn't this work? int a[5] = {1,2,3,4,5}; int*& ref = a; Both a and p are pointers and have the same value (address of a[0]). When I make reference to an array using a pointer (p), it works very well. But when I make reference to that array a[] directly, it doesn't work... Why? A: Adding on to what has already been answered, you can get a reference to an array like int a[5]; int (&ref)[5] = a; Live A: a is not a pointer, it is an array. It has the type int[5]. What it can do is decay to a pointer int*, which is what happens in the first case. So, taking a reference to p is ok. Now for the second case. Remember that a is not a pointer. So, there is an implicit conversion happening from int[5] to int*. The result of that conversion is a prvalue. But you can't bind a non-const lvalue reference (which is what ref is) to an rvalue! So the code fails to compile. Here's an analogy: double a = 1.4; int& b = a; // implicit conversion from 'double' to `int` results in prvalue // and you can't bind non-const lvalue refs to rvalues. A: int*& ref = a; int* is a pointer type, not an array type. So, that's why it won't bind to a, which has type int[5]. So, use const int* const& ref = a; It's works fine, Because the array name is an address constant, non-const reference can not refer to a constant.
stackoverflow
{ "language": "en", "length": 290, "provenance": "stackexchange_0000F.jsonl.gz:883984", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601564" }
c7162b43170165c1560dba2ea66125b5ac9c0736
Stackoverflow Stackexchange Q: Opencv-python: Type of input image should be CV_8UC3 or CV_8UC4! in function fastNlMeansDenoisingColored I wrote a simple opencv program, which reduce the noise of images. import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('stream/horse.png') dst = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 21) cv2.imshow(dst) plt.subplot(121), plt.imshow(img) plt.subplot(122), plt.imshow(dst) plt.show() horse.png When I ran the program it gave an error. Which is... OpenCV Error: Bad argument (Type of input image should be CV_8UC3 or CV_8UC4!) in fastNlMeansDenoisingColored, file /home/govinda/github_repos/opencv/modules/photo/src/denoising.cpp, line 176 Traceback (most recent call last): File "/home/govinda/workspace-python/opencv/src/Smle.py", line 7, in <module> dst = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 21) cv2.error: /home/govinda/github_repos/opencv/modules/photo/src/denoising.cpp:176: error: (-5) Type of input image should be CV_8UC3 or CV_8UC4! in function fastNlMeansDenoisingColored How should I over come this? A: you need to convert the image like this: converted_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) A little late to help you, but I hope it helps someone. Cheers!
Q: Opencv-python: Type of input image should be CV_8UC3 or CV_8UC4! in function fastNlMeansDenoisingColored I wrote a simple opencv program, which reduce the noise of images. import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('stream/horse.png') dst = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 21) cv2.imshow(dst) plt.subplot(121), plt.imshow(img) plt.subplot(122), plt.imshow(dst) plt.show() horse.png When I ran the program it gave an error. Which is... OpenCV Error: Bad argument (Type of input image should be CV_8UC3 or CV_8UC4!) in fastNlMeansDenoisingColored, file /home/govinda/github_repos/opencv/modules/photo/src/denoising.cpp, line 176 Traceback (most recent call last): File "/home/govinda/workspace-python/opencv/src/Smle.py", line 7, in <module> dst = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 21) cv2.error: /home/govinda/github_repos/opencv/modules/photo/src/denoising.cpp:176: error: (-5) Type of input image should be CV_8UC3 or CV_8UC4! in function fastNlMeansDenoisingColored How should I over come this? A: you need to convert the image like this: converted_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) A little late to help you, but I hope it helps someone. Cheers! A: It does not matter if it's *.png or *.jpg file. Matplotlib also gives you a different outcome. Try the following code: # fastNlMeansDenoisingColored # Wait for result, takes time to respond import cv2 from tkinter import filedialog from tkinter import * root = Tk() # Do not show graphics window root.withdraw() # Load the original color image origColorImage = cv2.imread(filedialog.askopenfilename(),1) # Image must have 3 channels print("Shape of image ", origColorImage.shape) dest = cv2.fastNlMeansDenoisingColored(origColorImage,None,10,10,7,21) cv2.imshow('Original image',origColorImage) cv2.imshow('fastNlMeansDenoisingColored',dest)
stackoverflow
{ "language": "en", "length": 231, "provenance": "stackexchange_0000F.jsonl.gz:883996", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601593" }
7191dfbbfaa2dfae734c0ab6ac500f761fa428a6
Stackoverflow Stackexchange Q: How to open a directory in Hammerspoon? I would like to open a directory on Hammerspoon with a keyboard shortcut. In order to open any apps via shortcut, you use the following: hs.hotkey.bind({"ctrl"}, "n", function() hs.application.launchOrFocus("Safari") end ) However, this doesn't work on the filesystem. For example, if you want to open ~/Dropbox, what method should you do to open the app? A: I'm not sure if there is an API specifically suitable for this task, but I found that one solution is bind keys to execute a shell command on Hammerspoon (via hs.execute()). local function directoryLaunchKeyRemap(mods, key, dir) local mods = mods or {} hs.hotkey.bind(mods, key, function() local shell_command = "open " .. dir hs.execute(shell_command) end) end directoryLaunchKeyRemap({"ctrl"}, "1", "/Applications") This lets you open /Applications directory via ⌃+1.
Q: How to open a directory in Hammerspoon? I would like to open a directory on Hammerspoon with a keyboard shortcut. In order to open any apps via shortcut, you use the following: hs.hotkey.bind({"ctrl"}, "n", function() hs.application.launchOrFocus("Safari") end ) However, this doesn't work on the filesystem. For example, if you want to open ~/Dropbox, what method should you do to open the app? A: I'm not sure if there is an API specifically suitable for this task, but I found that one solution is bind keys to execute a shell command on Hammerspoon (via hs.execute()). local function directoryLaunchKeyRemap(mods, key, dir) local mods = mods or {} hs.hotkey.bind(mods, key, function() local shell_command = "open " .. dir hs.execute(shell_command) end) end directoryLaunchKeyRemap({"ctrl"}, "1", "/Applications") This lets you open /Applications directory via ⌃+1.
stackoverflow
{ "language": "en", "length": 130, "provenance": "stackexchange_0000F.jsonl.gz:884031", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601713" }
4bb0a93706419e3c496881b0f7842f7c099e0d8e
Stackoverflow Stackexchange Q: Displaying custom (personally created) Unicode characters on a site Let's say I created a shorthand writing system with its own custom set of unique characters that don't exist in Unicode. Is there a way that I could: * *personally draw each character, *then assign each character its own code in Unicode, *then write those codes in an HTML page, *then publish that HTML page on a site, *and then somehow enable other people to actually view those unique characters when they visit that site's page?
Q: Displaying custom (personally created) Unicode characters on a site Let's say I created a shorthand writing system with its own custom set of unique characters that don't exist in Unicode. Is there a way that I could: * *personally draw each character, *then assign each character its own code in Unicode, *then write those codes in an HTML page, *then publish that HTML page on a site, *and then somehow enable other people to actually view those unique characters when they visit that site's page?
stackoverflow
{ "language": "en", "length": 86, "provenance": "stackexchange_0000F.jsonl.gz:884082", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601876" }
10709949f6ff4edd38b607661f601f407e08fe60
Stackoverflow Stackexchange Q: Difference between field and connection in Graphql ruby? I am new to Graphql. For a simple use case, Let's say i have simple model, class Post < ActiveRecord::Base has_many :comments end Below is the code in my graphql query_type.rb PostType = GraphQL::ObjectType.define do #field :comments, types[CommentType] #connection :comments, CommentType.connection_type end Both field and connection works for me. But which one is the right way to go. A: Connection will help you paginate through the list of comments connected to the post with 4 default arguments (first, last, after and before) in the query, whereas field here would return a basic list of CommentType For more on pagination with connection, read up here http://graphql.org/learn/pagination/
Q: Difference between field and connection in Graphql ruby? I am new to Graphql. For a simple use case, Let's say i have simple model, class Post < ActiveRecord::Base has_many :comments end Below is the code in my graphql query_type.rb PostType = GraphQL::ObjectType.define do #field :comments, types[CommentType] #connection :comments, CommentType.connection_type end Both field and connection works for me. But which one is the right way to go. A: Connection will help you paginate through the list of comments connected to the post with 4 default arguments (first, last, after and before) in the query, whereas field here would return a basic list of CommentType For more on pagination with connection, read up here http://graphql.org/learn/pagination/
stackoverflow
{ "language": "en", "length": 114, "provenance": "stackexchange_0000F.jsonl.gz:884087", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601890" }
ad417f14501030d93d67b4f239a7ec8611e6f900
Stackoverflow Stackexchange Q: Xcode Creating a framework that has cocoapods dependencies I'm currently developing a framework for internal usage, but I'm having trouble getting it to play nicely. The issue i seem to be having is that the framework uses cocoapods for some of its dependencies, and then when I tried to test is in a blank project by adding it as subproject it and then import it, it won't build and complains saying "No such module 'x'". Ideally instead of a subproject id like it to work purely as a framework but I'm just taking baby steps for now. A: If you developing a framework with some dependencies you will have next diagram application -> Framework -> dependencies You have next variants: * *If you try to create Umbrella framework[About] it is not a good practice *Use Cocoapods[About] as a dependency manager. If your framework is private you can use closed source[About] distribution *Try to add (and manage) all framework's dependencies to application target
Q: Xcode Creating a framework that has cocoapods dependencies I'm currently developing a framework for internal usage, but I'm having trouble getting it to play nicely. The issue i seem to be having is that the framework uses cocoapods for some of its dependencies, and then when I tried to test is in a blank project by adding it as subproject it and then import it, it won't build and complains saying "No such module 'x'". Ideally instead of a subproject id like it to work purely as a framework but I'm just taking baby steps for now. A: If you developing a framework with some dependencies you will have next diagram application -> Framework -> dependencies You have next variants: * *If you try to create Umbrella framework[About] it is not a good practice *Use Cocoapods[About] as a dependency manager. If your framework is private you can use closed source[About] distribution *Try to add (and manage) all framework's dependencies to application target A: The CocoaPods "pod lib create" tutorial is a good way to learn the CocoaPods framework creation steps incrementally. A: Just a quick note - I got this "No such module MODULE" error when I created my local pod by creating an Xcode project for a new framework and then running pod spec create MODULE. I tried again by just running pod lib create MODULE (without creating any Xcode projects beforehand), and the error isn't bothering me any more. (I'm accessing this pod privately adding pod 'MODULE', :path => '../ModulePath' in my Podfile from another project)
stackoverflow
{ "language": "en", "length": 259, "provenance": "stackexchange_0000F.jsonl.gz:884102", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44601941" }
8ebcfd8f6d7c02ec47ed9655581ae6647ef775d5
Stackoverflow Stackexchange Q: Laravel 5/ 5.4 paginator is not working in NGINX production environement In my local environment i did $items = Model::paginate(10); and it worked. Then i pushed it to production and when i click on the pagination links it displays page 1 again and again. then i did dd($items). i found that the current Page property of length aware pagination is not changing when i change the address to /items?page=*. How to make current page property change accordingly or there is some thing else? thanks in advance A: I am using ubuntu 16.04 nginx server. The problem was that $_GET session variables were not being set properly. so what I did was inside /etc/nginx/sites-available/default and inside location / block/ directive I changed try_files $uri $uri/ /index.php?$query_string; to try_files $uri $uri/ /index.php?$args; and it worked. Or see Laravel 5 - NGINX Server Config Issue with URL Query Strings
Q: Laravel 5/ 5.4 paginator is not working in NGINX production environement In my local environment i did $items = Model::paginate(10); and it worked. Then i pushed it to production and when i click on the pagination links it displays page 1 again and again. then i did dd($items). i found that the current Page property of length aware pagination is not changing when i change the address to /items?page=*. How to make current page property change accordingly or there is some thing else? thanks in advance A: I am using ubuntu 16.04 nginx server. The problem was that $_GET session variables were not being set properly. so what I did was inside /etc/nginx/sites-available/default and inside location / block/ directive I changed try_files $uri $uri/ /index.php?$query_string; to try_files $uri $uri/ /index.php?$args; and it worked. Or see Laravel 5 - NGINX Server Config Issue with URL Query Strings A: Awsome Thanks #Ahmed I just had to change mine from location / { try_files $uri $uri/ /index.php?$query_string; } to location / { index index.php; try_files $uri @rewriteapp; } location @rewriteapp { rewrite ^(.*)$ /index.php/$1 last; } as i saw some of my other sites was using the @rewriteapp part and seem to work fine.
stackoverflow
{ "language": "en", "length": 202, "provenance": "stackexchange_0000F.jsonl.gz:884146", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44602067" }
2491e51d5e2b14236c9cc771ce65a0bf49cc2712
Stackoverflow Stackexchange Q: Pandas: convert all column from string to number except two? Suppose we have >>> df.dtype Name object Height object Weight object Age object Job object Is there any simple way to covert all columns except Name and Job columns with .to_numeric() method? I have tried but it doesn't work df.iloc[df.columns != Name & df.columns != Job] = pd.to_numeric(df.iloc[df.columns != Name & df.columns != Job], errors='coerce') A: The simplest way that comes to my mind would be to make a list of all the columns except Name and Job and then iterate pandas.to_numeric over them: cols=[i for i in df.columns if i not in ["Name","Job"]] for col in cols: df[col]=pd.to_numeric(df[col]) Edit: If you absolutely want to use numbers instead of columns names and already know at which indice they are: for i in [i for i in list(range(len(df.columns))) if i not in [0,4]]: df.iloc[:,i]=pandas.to_numeric(df.iloc[:,i]) That's more complicated than necessary though.
Q: Pandas: convert all column from string to number except two? Suppose we have >>> df.dtype Name object Height object Weight object Age object Job object Is there any simple way to covert all columns except Name and Job columns with .to_numeric() method? I have tried but it doesn't work df.iloc[df.columns != Name & df.columns != Job] = pd.to_numeric(df.iloc[df.columns != Name & df.columns != Job], errors='coerce') A: The simplest way that comes to my mind would be to make a list of all the columns except Name and Job and then iterate pandas.to_numeric over them: cols=[i for i in df.columns if i not in ["Name","Job"]] for col in cols: df[col]=pd.to_numeric(df[col]) Edit: If you absolutely want to use numbers instead of columns names and already know at which indice they are: for i in [i for i in list(range(len(df.columns))) if i not in [0,4]]: df.iloc[:,i]=pandas.to_numeric(df.iloc[:,i]) That's more complicated than necessary though. A: Suppose you have DF: df Out[125]: Name Height Weight Age Job 0 0 2 3 4 5 df.dtypes Out[126]: Name object Height object Weight object Age object Job object dtype: object If you have to use pd.to_numeric to convert those columns, you can do it this way: df2 = pd.concat([pd.DataFrame([pd.to_numeric(df[e],errors='coerce') \ for e in df.columns if e not in ['Name','Job']]).T,\ df[['Name','Job']]],axis=1) df2 Out[138]: Height Weight Age Name Job 0 2 3 4 0 5 df2.dtypes Out[139]: Height int64 Weight int64 Age int64 Name object Job object dtype: object
stackoverflow
{ "language": "en", "length": 239, "provenance": "stackexchange_0000F.jsonl.gz:884165", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44602139" }
ae6090a679043a1d020ec9398259962e6fd8ea92
Stackoverflow Stackexchange Q: How to completely uninstall python 2.7.13 on Ubuntu 16.04 I installed Python 2.7.13 on Ubuntu 16.04 according to this guide, and it became the default version as an alternative to the version 2.7.12. But, I wanted to completely remove Python 2.7.13 and return back to the version 2.7.12 as the default version since the pip command does not work with the following error. bash: /usr/local/bin/pip: /usr/bin/python: bad interpreter: No such file or directory Could you please help me how to completely remove Python 2.7.13 from Ubuntu 16.04? Otherwise, could you please suggest how to fix the above error? A: caution : It is not recommended to remove the default Python from Ubuntu, it may cause GDM(Graphical Display Manager, that provide graphical login capabilities) failed. To completely uninstall Python2.x.x and everything depends on it. use this command: sudo apt purge python2.x-minimal As there are still a lot of packages that depend on Python2.x.x. So you should have a close look at the packages that apt wants to remove before you let it proceed. Thanks, I hope it will be helpful for you.
Q: How to completely uninstall python 2.7.13 on Ubuntu 16.04 I installed Python 2.7.13 on Ubuntu 16.04 according to this guide, and it became the default version as an alternative to the version 2.7.12. But, I wanted to completely remove Python 2.7.13 and return back to the version 2.7.12 as the default version since the pip command does not work with the following error. bash: /usr/local/bin/pip: /usr/bin/python: bad interpreter: No such file or directory Could you please help me how to completely remove Python 2.7.13 from Ubuntu 16.04? Otherwise, could you please suggest how to fix the above error? A: caution : It is not recommended to remove the default Python from Ubuntu, it may cause GDM(Graphical Display Manager, that provide graphical login capabilities) failed. To completely uninstall Python2.x.x and everything depends on it. use this command: sudo apt purge python2.x-minimal As there are still a lot of packages that depend on Python2.x.x. So you should have a close look at the packages that apt wants to remove before you let it proceed. Thanks, I hope it will be helpful for you. A: try following to see all instances of python whereis python which python Then remove all instances using: sudo apt autoremove python repeat sudo apt autoremove python(for all versions) that should do it, then install Anaconda and manage Pythons however you like if you need to reinstall it. A: sudo apt purge python2.7-minimal A: Sometimes you need to first update the apt repo list. sudo apt-get update sudo apt purge python2.7-minimal A: This is what I have after doing purge of all the python versions and reinstalling only 3.6. root@esp32:/# python Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) [GCC 6.2.0 20161005] on linux Type "help", "copyright", "credits" or "license" for more information. >>> root@esp32:/# python3 Python 3.8.0 (default, Dec 15 2019, 14:19:02) [GCC 6.2.0 20161005] on linux Type "help", "copyright", "credits" or "license" for more information. Also the pip and pip3 commands are totally f up: root@esp32:/# pip Traceback (most recent call last): File "/usr/local/bin/pip", line 7, in <module> from pip._internal.cli.main import main File "/usr/local/lib/python3.5/dist-packages/pip/_internal/cli/main.py", line 60 sys.stderr.write(f"ERROR: {exc}") ^ SyntaxError: invalid syntax root@esp32:/# pip3 Traceback (most recent call last): File "/usr/local/bin/pip3", line 7, in <module> from pip._internal.cli.main import main File "/usr/local/lib/python3.5/dist-packages/pip/_internal/cli/main.py", line 60 sys.stderr.write(f"ERROR: {exc}") ^ SyntaxError: invalid syntax I am totally noob at Linux, I just wanted to update Python from 2.x to 3.x so that Platformio could upgrade and now I messed up everything it seems. A: How I do: # Remove python2 sudo apt purge -y python2.7-minimal # You already have Python3 but # don't care about the version sudo ln -s /usr/bin/python3 /usr/bin/python # Same for pip sudo apt install -y python3-pip sudo ln -s /usr/bin/pip3 /usr/bin/pip # Confirm the new version of Python: 3 python --version
stackoverflow
{ "language": "en", "length": 464, "provenance": "stackexchange_0000F.jsonl.gz:884176", "question_score": "73", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44602191" }
7ac109f036b96513cefa0dbac8d0174bfb4d263e
Stackoverflow Stackexchange Q: Asp.Net Core 1.1 The key was not found in the key ring DEFAULT PROJECT IN VS 2017 I have created a new Asp.net Core web application in vs 2017 community and published it on a FTP hosting, but when I submit a form (login or user creation) I get this error: Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery[7] An exception was thrown while deserializing the token. System.InvalidOperationException: The antiforgery token could not be decrypted. ---> System.Security.Cryptography.CryptographicException: The key {...} was not found in the key ring. What do I need to do to make it work? thanks. A: Likely your issue is that you have disabled disable the user profile in IIS , up date that and the error like [WRN] Error unprotecting the session cookie. System.Security.Cryptography.CryptographicException: The key {e47d051f-d492-4df7-8781-31d884833ec6} was not found in the key ring. and Antiforgery [ERR] An exception was thrown while deserializing the token. Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted. ---> System.Security.Cryptography.CryptographicException: The key {e47d051f-d492-4df7-8781-31d884833ec6} was not found in the key ring. Will most likely magically go away.
Q: Asp.Net Core 1.1 The key was not found in the key ring DEFAULT PROJECT IN VS 2017 I have created a new Asp.net Core web application in vs 2017 community and published it on a FTP hosting, but when I submit a form (login or user creation) I get this error: Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery[7] An exception was thrown while deserializing the token. System.InvalidOperationException: The antiforgery token could not be decrypted. ---> System.Security.Cryptography.CryptographicException: The key {...} was not found in the key ring. What do I need to do to make it work? thanks. A: Likely your issue is that you have disabled disable the user profile in IIS , up date that and the error like [WRN] Error unprotecting the session cookie. System.Security.Cryptography.CryptographicException: The key {e47d051f-d492-4df7-8781-31d884833ec6} was not found in the key ring. and Antiforgery [ERR] An exception was thrown while deserializing the token. Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted. ---> System.Security.Cryptography.CryptographicException: The key {e47d051f-d492-4df7-8781-31d884833ec6} was not found in the key ring. Will most likely magically go away. A: If your IIS Application Pool is set to use ApplicationPoolIdentity, then you need to make sure "Load User Profile" is set to "True" for the IIS Application Pool. See: https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/default-settings?view=aspnetcore-2.1 *If the user profile is available, keys are persisted to the %LOCALAPPDATA%\ASP.NET\DataProtection-Keys folder. If the operating system is Windows, the keys are encrypted at rest using DPAPI. A: If your hosting environment is using more than one instance for the application this may be the cause of the problem. The simplest way to solve this is to scale down to one instance and make maximum number of instances 1. This is for the side of identity or login API. As your application is making login to an instance. And checking the token with another instance.
stackoverflow
{ "language": "en", "length": 295, "provenance": "stackexchange_0000F.jsonl.gz:884207", "question_score": "15", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44602304" }
c3f4da2f16b204fb03c4f14a3740291d03a70af9
Stackoverflow Stackexchange Q: Can't build maven jhipster project with lombok ./mvnw and mvn clean install fail when adding lombok dependency but run successfully when launched from Intellij IDE Find the error below : INFO] ------------------------------------------------------------- [ERROR] COMPILATION ERROR : [INFO] ------------------------------------------------------------- [ERROR] src/main/java/web/rest/core/service/impl/ProductServiceImpl.java:[18,29] cannot find symbol symbol: method builder() location: class com.test.one.web.rest.core.model.Product Here is the POJO import lombok.Builder; import lombok.Data; @Data @Builder public class Product { private String name; } A: The maven project Jhipster generated uses a annotationProcessorPaths in the maven compile plugin, that's why it cannot look up the latest lombok unless we specify lombok as one of the annotation processor. Working code is as followed. <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven-compiler-plugin.version}</version> <configuration> <annotationProcessorPaths> <path> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>${mapstruct.version}</version> </path> <!-- For JPA static metamodel generation --> <path> <groupId>org.hibernate</groupId> <artifactId>hibernate-jpamodelgen</artifactId> <version>${hibernate.version}</version> </path> <path> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.18</version> </path> </annotationProcessorPaths> </configuration>
Q: Can't build maven jhipster project with lombok ./mvnw and mvn clean install fail when adding lombok dependency but run successfully when launched from Intellij IDE Find the error below : INFO] ------------------------------------------------------------- [ERROR] COMPILATION ERROR : [INFO] ------------------------------------------------------------- [ERROR] src/main/java/web/rest/core/service/impl/ProductServiceImpl.java:[18,29] cannot find symbol symbol: method builder() location: class com.test.one.web.rest.core.model.Product Here is the POJO import lombok.Builder; import lombok.Data; @Data @Builder public class Product { private String name; } A: The maven project Jhipster generated uses a annotationProcessorPaths in the maven compile plugin, that's why it cannot look up the latest lombok unless we specify lombok as one of the annotation processor. Working code is as followed. <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven-compiler-plugin.version}</version> <configuration> <annotationProcessorPaths> <path> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>${mapstruct.version}</version> </path> <!-- For JPA static metamodel generation --> <path> <groupId>org.hibernate</groupId> <artifactId>hibernate-jpamodelgen</artifactId> <version>${hibernate.version}</version> </path> <path> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.18</version> </path> </annotationProcessorPaths> </configuration> A: I managed to work with the following combination of versions: * *maven-compiler-plugin: 3.3 *lombok: 1.16.18 (latest) So for example, a pom.xml: <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.18</version> <scope>provided</scope> </dependency> ... <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> </plugin>
stackoverflow
{ "language": "en", "length": 170, "provenance": "stackexchange_0000F.jsonl.gz:884213", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44602317" }
22e7880d48302a93a5525ebc923e2cab832bb201
Stackoverflow Stackexchange Q: Angular FormControl valueChanges doesn't work I want to get one of my forms ("family") value if changed by subscribing but it seems something is wrong because I got nothing on my console's log. import { Component , AfterViewInit } from '@angular/core'; import {FormGroup,FormBuilder} from '@angular/forms'; import {Observable} from 'rxjs/Rx'; @Component({ selector: 'app-root', template: `<form [formGroup]="frm1"> <input type="text" formControlName="name" > <input type="text" formControlName="family"> </form> `, }) export class AppComponent implements AfterViewInit{ frm1 : FormGroup; constructor( fb:FormBuilder){ this.frm1 = fb.group({ name : [], family: [] }); } ngAfterViewInit(){ var search = this.frm1.controls.family; search.valueChanges.subscribe( x => console.log(x)); } } A: Try this: import { Component , AfterViewInit, OnInit } from '@angular/core'; import {FormGroup,FormBuilder} from '@angular/forms'; import {Observable} from 'rxjs/Rx'; @Component({ selector: 'app-root', template: `<h1>Hello World!</h1> <form [formGroup]="frm1"> <input type="text" formControlName="name" > <input type="text" formControlName="family"> </form>`}) export class AppComponent implements AfterViewInit, OnInit{ frm1 : FormGroup; constructor( private formBuilder: FormBuilder){} ngOnInit(): void { this.formInit(); this.formSet(); } formInit(): void { this.frm1 = this.formBuilder.group({ name: [''], family[''] }) } formSet(): void { const editForm = { name: 'test-name', family: 'test familty', }; this.frm1.patchValue(editForm) } ngAfterViewInit(){ this.frm1 .controls.family.valueChanges.subscribe( () => { console.log(this.frm1 .controls.family.value) } ) } }
Q: Angular FormControl valueChanges doesn't work I want to get one of my forms ("family") value if changed by subscribing but it seems something is wrong because I got nothing on my console's log. import { Component , AfterViewInit } from '@angular/core'; import {FormGroup,FormBuilder} from '@angular/forms'; import {Observable} from 'rxjs/Rx'; @Component({ selector: 'app-root', template: `<form [formGroup]="frm1"> <input type="text" formControlName="name" > <input type="text" formControlName="family"> </form> `, }) export class AppComponent implements AfterViewInit{ frm1 : FormGroup; constructor( fb:FormBuilder){ this.frm1 = fb.group({ name : [], family: [] }); } ngAfterViewInit(){ var search = this.frm1.controls.family; search.valueChanges.subscribe( x => console.log(x)); } } A: Try this: import { Component , AfterViewInit, OnInit } from '@angular/core'; import {FormGroup,FormBuilder} from '@angular/forms'; import {Observable} from 'rxjs/Rx'; @Component({ selector: 'app-root', template: `<h1>Hello World!</h1> <form [formGroup]="frm1"> <input type="text" formControlName="name" > <input type="text" formControlName="family"> </form>`}) export class AppComponent implements AfterViewInit, OnInit{ frm1 : FormGroup; constructor( private formBuilder: FormBuilder){} ngOnInit(): void { this.formInit(); this.formSet(); } formInit(): void { this.frm1 = this.formBuilder.group({ name: [''], family[''] }) } formSet(): void { const editForm = { name: 'test-name', family: 'test familty', }; this.frm1.patchValue(editForm) } ngAfterViewInit(){ this.frm1 .controls.family.valueChanges.subscribe( () => { console.log(this.frm1 .controls.family.value) } ) } } A: The question already uses subscribe but just in case somebody like me lands here after reading the title. valueChanges was also not working for me but for some other reason. I was using material stepper and auto complete for my project. The sample code on their website, filters the data within map but it did not work. this.filteredOptions = this.myControl.valueChanges.pipe(startWith(''), map(value => this._filter(value))); However subscribing to the valueChange worked and filtered the data. this.myControl.valueChanges.pipe(startWith('')).subscribe(value => this.filteredOptions = of(this._filter(value))); A: Use get method on form variable frm1. And use ngOnInit() instead of ngAfterViewInit() ngOnInit() { this.frm1.get('family').valueChanges.subscribe( x => console.log(x)); }
stackoverflow
{ "language": "en", "length": 290, "provenance": "stackexchange_0000F.jsonl.gz:884236", "question_score": "18", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44602410" }
ab7cad66a62e7964592268c15491da6ea1213dbf
Stackoverflow Stackexchange Q: Why does Git have a 'Check ✓' mark in its querystring? I was searching about something on Git when I noticed that in the query string, there's a parameter utf8 and its value is ✓! Not utf8=yes or utf8=true. The full URL is following in Chrome and Firefox: https://github.com/Modernizr/Modernizr/search?utf8=✓&q=browser&type= But following in IE: https://github.com/Modernizr/Modernizr/search?utf8=%E2%9C%93&q=browser&type= So it seems to be a way of detecting the encoding scheme for the URL, but does anyone know for sure? Also, aren't there any simpler ways of doing this? A: From a StackExchange question: By default, older versions of IE (<=8) will submit form data in Latin-1 encoding if possible. By including a character that can't be expressed in Latin-1, IE is forced to use UTF-8 encoding for its form submissions, which simplifies various backend processes, for example database persistence. If the parameter was instead utf8=true then this wouldn't trigger the UTF-8 encoding in these browsers. This is a hack/feature of Rails (which Github is built with) to force IE to submit UTF-8 text. It's a feature of Rails (which GitHub is built with), although it's not specific to Rails.
Q: Why does Git have a 'Check ✓' mark in its querystring? I was searching about something on Git when I noticed that in the query string, there's a parameter utf8 and its value is ✓! Not utf8=yes or utf8=true. The full URL is following in Chrome and Firefox: https://github.com/Modernizr/Modernizr/search?utf8=✓&q=browser&type= But following in IE: https://github.com/Modernizr/Modernizr/search?utf8=%E2%9C%93&q=browser&type= So it seems to be a way of detecting the encoding scheme for the URL, but does anyone know for sure? Also, aren't there any simpler ways of doing this? A: From a StackExchange question: By default, older versions of IE (<=8) will submit form data in Latin-1 encoding if possible. By including a character that can't be expressed in Latin-1, IE is forced to use UTF-8 encoding for its form submissions, which simplifies various backend processes, for example database persistence. If the parameter was instead utf8=true then this wouldn't trigger the UTF-8 encoding in these browsers. This is a hack/feature of Rails (which Github is built with) to force IE to submit UTF-8 text. It's a feature of Rails (which GitHub is built with), although it's not specific to Rails.
stackoverflow
{ "language": "en", "length": 186, "provenance": "stackexchange_0000F.jsonl.gz:884251", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44602461" }
4491f6dbe671bf8f9e5ec2bdb9e025ad6dabc637
Stackoverflow Stackexchange Q: Atom IDE autocomplete-python not working I have just installed the Atom IDE and the package autocomplete-python (on Windows). But the package is not working. Do I have to make any setting changes? (I have disabled autocomplete-plus and autocomplete-snippets). Do I need to separately install Jedi? A: I was having the same problem, in order to fix it I added python executable path installed package setting and it worked. "C:\Python27\python.exe;C:\Python27\Scripts\". In my case I had PyCharm, Anaconda and Python 2.7 was installed on my system and while using atom editior I was not accessing any of the environment, was working on just a plain .py files saved on my desktop.
Q: Atom IDE autocomplete-python not working I have just installed the Atom IDE and the package autocomplete-python (on Windows). But the package is not working. Do I have to make any setting changes? (I have disabled autocomplete-plus and autocomplete-snippets). Do I need to separately install Jedi? A: I was having the same problem, in order to fix it I added python executable path installed package setting and it worked. "C:\Python27\python.exe;C:\Python27\Scripts\". In my case I had PyCharm, Anaconda and Python 2.7 was installed on my system and while using atom editior I was not accessing any of the environment, was working on just a plain .py files saved on my desktop. A: If autocomplete-python in Atom not working with Python 3.7 In windows, go to: C:\Users\username\.atom\packages\autocomplete-python\lib\jedi\parser Or in linux: cd ~/.atom/packages/autocomplete-python/lib/jedi/parser Duplicate file named "grammar3.6.txt" and change it to "grammar3.7.txt" It's worked for me with python 3.7! A: I was have same problem, my Atom autocomplete-python not working , I went to: C:\Users\username\.atom\packages\autocomplete-python\lib\jedi\parser and because my Python was 3.8 I was created "grammar3.8.txt" too. Then everything was right And the atom was working properly A: It worked when I enabled autocomplete-plus. It seems autocomplete-plus is required for autocomplete-python to work. (I had initially followed a youtube video in which autocomplete-plus and -snippets were disabled and then autocomplete-python was installed.) A: Late to the party, but I had the same issue and resolved it by adding a path to my site-packages for one of my virtual environments in the settings. * *On the toolbar, go to File-> Settings -> packages. *Find your autocomplete-python package. *Go to the settings of the autocomplete-python package. *Scroll down to "Extra Paths For Packages". *Copy and paste a path location to your site packages. e.g: C:\Users\my_username\Miniconda3\envs\my_env_name\Lib\site-packages *Celebrate :) A: Same for me. I followed the previous answer but could not find autocomplete-plus (June 2018). I installed autocomplete and now both packages work just fine. A: For me, enabling autocomplete-plus didn't help. It worked when I changed the Python version that I am using from Python 3.7 to Python 3.6.6. A: I also had the same problem while trying to use the django-atom autocomplete snippet and after reading different articles on it here is how I go about it. * *Go to the directory of the installed autocomplete package, in this case here: C:\Users\user.atom\packages\django-atom *Go to the snippet folder and you'll find a .cson file, right click and open it with an editor in this case here is the directory: C:\Users\user.atom\packages\django-atom\snippets *Copy everything inside the file and go back to the snippets.cson file in .atom parent directory, in this case here: C:\Users\user.atom *Right click and open the snippets file with an editor, scroll down and paste everything you copied earlier into the file then save. *Bro, now you can enjoy your beautiful snippets.
stackoverflow
{ "language": "en", "length": 465, "provenance": "stackexchange_0000F.jsonl.gz:884294", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44602603" }
fbf724baa8d415ccef0432aed0d767db96082552
Stackoverflow Stackexchange Q: Why does a string is considered as color in HTML? Okay, this might seem like my computer's fault, but I tested this with different devices, I get the same result on every device. While setting the background color of a html to blue, I did a typo and wrote bluee and I got violet color. I don't know why it's happening. <body bgcolor="bluee"><div style=color:red;> Weird Color </div></body>
Q: Why does a string is considered as color in HTML? Okay, this might seem like my computer's fault, but I tested this with different devices, I get the same result on every device. While setting the background color of a html to blue, I did a typo and wrote bluee and I got violet color. I don't know why it's happening. <body bgcolor="bluee"><div style=color:red;> Weird Color </div></body>
stackoverflow
{ "language": "en", "length": 68, "provenance": "stackexchange_0000F.jsonl.gz:884303", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44602628" }
7dbaf27c7f3037e159d718b158b80aa8da16ab7b
Stackoverflow Stackexchange Q: Javascript/lodash how to remove empty arrays I'm working with this structure: [ [ { "comments":"asd", "movement":"Back Squat", "userID":"wDHZv3OL55SIymHkhMUejNleNkx1", "weight":"330" } ], [ { "comments":"asd", "movement":"Bench Press", "userID":"wDHZv3OL55SIymHkhMUejNleNkx1", "weight":"100" } ], [ { "comments":"Comment", "movement":"Clean", "userID":"wDHZv3OL55SIymHkhMUejNleNkx1", "weight":"195" } ], [ ], [ ], [ { "comments":"Front squat comment alpha", "movement":"Front Squat", "userID":"wDHZv3OL55SIymHkhMUejNleNkx1", "weight":"315" } ], [ ], [ ], [ ], [ ], [ ], [ { "comments":"abc", "movement":"Strict Press", "userID":"wDHZv3OL55SIymHkhMUejNleNkx1", "weight":"155" } ] ] This is the input I'm using in JSON format. As you can see there are multiple empty arrays. How would I go about filtering through these arrays and remove the empty ones? A: If all the items in the top level array are arrays then you could lodash's reject with the isEmpty predicate. let result = _.reject(data, _.isEmpty); isEmpty will also return true for empty objects amongst other thing so if your top level array can contain such items then to just remove empty arrays you could compose a new function to return just empty arrays and use that as the predicate to reject: let isEmptyArray = item => _.isArray(item) && _.isEmpty(item); let result = _.reject(data, isEmptyArray);
Q: Javascript/lodash how to remove empty arrays I'm working with this structure: [ [ { "comments":"asd", "movement":"Back Squat", "userID":"wDHZv3OL55SIymHkhMUejNleNkx1", "weight":"330" } ], [ { "comments":"asd", "movement":"Bench Press", "userID":"wDHZv3OL55SIymHkhMUejNleNkx1", "weight":"100" } ], [ { "comments":"Comment", "movement":"Clean", "userID":"wDHZv3OL55SIymHkhMUejNleNkx1", "weight":"195" } ], [ ], [ ], [ { "comments":"Front squat comment alpha", "movement":"Front Squat", "userID":"wDHZv3OL55SIymHkhMUejNleNkx1", "weight":"315" } ], [ ], [ ], [ ], [ ], [ ], [ { "comments":"abc", "movement":"Strict Press", "userID":"wDHZv3OL55SIymHkhMUejNleNkx1", "weight":"155" } ] ] This is the input I'm using in JSON format. As you can see there are multiple empty arrays. How would I go about filtering through these arrays and remove the empty ones? A: If all the items in the top level array are arrays then you could lodash's reject with the isEmpty predicate. let result = _.reject(data, _.isEmpty); isEmpty will also return true for empty objects amongst other thing so if your top level array can contain such items then to just remove empty arrays you could compose a new function to return just empty arrays and use that as the predicate to reject: let isEmptyArray = item => _.isArray(item) && _.isEmpty(item); let result = _.reject(data, isEmptyArray); A: Use the native Array#filter or lodash's _.filter(), and keep the sub arrays with length other than 0. Array#filter var arrs = [[{"comments":"asd","movement":"Back Squat","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"330"}],[{"comments":"asd","movement":"Bench Press","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"100"}],[{"comments":"Comment","movement":"Clean","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"195"}],[],[],[{"comments":"Front squat comment alpha","movement":"Front Squat","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"315"}],[],[],[],[],[],[{"comments":"abc","movement":"Strict Press","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"155"}]]; var result = arrs.filter(function(sub) { return sub.length; }); console.log(result); Lodash's _.filter() with _.size: var arrs = [[{"comments":"asd","movement":"Back Squat","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"330"}],[{"comments":"asd","movement":"Bench Press","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"100"}],[{"comments":"Comment","movement":"Clean","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"195"}],[],[],[{"comments":"Front squat comment alpha","movement":"Front Squat","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"315"}],[],[],[],[],[],[{"comments":"abc","movement":"Strict Press","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"155"}]]; var result = _.filter(arrs, _.size); console.log(result); <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> A: Test each array in turn to see if it has a non-zero (truthy) length. If it does, put it in your new array. var array_of_arrays = [[1], [1,1], [], [], [1]]; var array_of_non_empty_arrays = array_of_arrays.filter((array) => array.length); console.log(array_of_non_empty_arrays);
stackoverflow
{ "language": "en", "length": 293, "provenance": "stackexchange_0000F.jsonl.gz:884314", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44602661" }
dc9bb691256f04de8c18dfb2b99d8fd8b002ed31
Stackoverflow Stackexchange Q: Laravel attach manytomany with extra field There are 3 tables. Products, Users and product_user. There are 3 fields in product_user table. product_id, user_id and price. product_id and user_id will be attached and filled automatically. But I want a textfield named price which user fill it to be inserted in price field in database. I mean I want to insert a textfield when attaching. A: To insert an extra field in your pivot table first of all, you need to specify this extra field in your models. For Example this: In Product model public function users() { return $this->belongsToMany('App\User', 'product_user') ->withPivot('price'); } In User model public function products() { return $this->belongsToMany('App\Product', 'product_user') ->withPivot('price'); } Furthermore, in you Controller you can attach this extra field like this: $product->users()->attach($user_id, ['price'=> $price ]); I hope this will help you !!!
Q: Laravel attach manytomany with extra field There are 3 tables. Products, Users and product_user. There are 3 fields in product_user table. product_id, user_id and price. product_id and user_id will be attached and filled automatically. But I want a textfield named price which user fill it to be inserted in price field in database. I mean I want to insert a textfield when attaching. A: To insert an extra field in your pivot table first of all, you need to specify this extra field in your models. For Example this: In Product model public function users() { return $this->belongsToMany('App\User', 'product_user') ->withPivot('price'); } In User model public function products() { return $this->belongsToMany('App\Product', 'product_user') ->withPivot('price'); } Furthermore, in you Controller you can attach this extra field like this: $product->users()->attach($user_id, ['price'=> $price ]); I hope this will help you !!! A: A best practice example to pass one array to attach is this example: $extra = array( 'expense_type_id' => $request->expenseType, 'quantity' => $request->quantity, 'price' => $request->price ); //dd($extra); $logisticCost->expenses()->attach($logisticCost->id,$extra); Cheers!
stackoverflow
{ "language": "en", "length": 167, "provenance": "stackexchange_0000F.jsonl.gz:884315", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44602662" }
9bf596c1dcba6c324c6e6b1611a9792bbf8c563e
Stackoverflow Stackexchange Q: TypeScript imports vs. ES6 object destructuring With TS imports, I believe I can do this: import {foo as bar} from 'foo'; with ES6 object destructuring in JS or TypeScript - is there a way to rename an "imported value" in the same way? For example, const {longVarName as lvn} = x.bar; A: Use the solution suggested by Jaromanda X: const {longVarName: lvn} = x.bar; In fact, you can do more than that: Multiple variables var {p: foo, q: bar} = o; Default values: var {a = 10, b = 5} = {a: 3}; Nested objects: const x = {a: {b: {c: 10}}}; const {a: {b: {c: ten}}} = x; // ten === 10 For more info, see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Q: TypeScript imports vs. ES6 object destructuring With TS imports, I believe I can do this: import {foo as bar} from 'foo'; with ES6 object destructuring in JS or TypeScript - is there a way to rename an "imported value" in the same way? For example, const {longVarName as lvn} = x.bar; A: Use the solution suggested by Jaromanda X: const {longVarName: lvn} = x.bar; In fact, you can do more than that: Multiple variables var {p: foo, q: bar} = o; Default values: var {a = 10, b = 5} = {a: 3}; Nested objects: const x = {a: {b: {c: 10}}}; const {a: {b: {c: ten}}} = x; // ten === 10 For more info, see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
stackoverflow
{ "language": "en", "length": 119, "provenance": "stackexchange_0000F.jsonl.gz:884336", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44602735" }
c131342e0a54cc1963668261573268499395808e
Stackoverflow Stackexchange Q: Unpacking result of delayed function While converting my program using delayed, I stumbled upon a commonly used programming pattern that doesn't work with delayed. Example: from dask import delayed @delayed def myFunction(): return 1,2 a, b = myFunction() a.compute() Raises: TypeError: Delayed objects of unspecified length are not iterable While the following work around does not. But looks a lot more clumsy from dask import delayed @delayed def myFunction(): return 1,2 dummy = myFunction() a, b = dummy[0], dummy[1] a.compute() Is this the intended behaviour? A: Use the nout= keyword as described in the delayed docstring @delayed(nout=2) def f(...): return a, b x, y = f(1) Docstring nout : int, optional The number of outputs returned from calling the resulting ``Delayed`` object. If provided, the ``Delayed`` output of the call can be iterated into ``nout`` objects, allowing for unpacking of results. By default iteration over ``Delayed`` objects will error. Note, that ``nout=1`` expects ``obj``, to return a tuple of length 1, and consequently for `nout=0``, ``obj`` should return an empty tuple.
Q: Unpacking result of delayed function While converting my program using delayed, I stumbled upon a commonly used programming pattern that doesn't work with delayed. Example: from dask import delayed @delayed def myFunction(): return 1,2 a, b = myFunction() a.compute() Raises: TypeError: Delayed objects of unspecified length are not iterable While the following work around does not. But looks a lot more clumsy from dask import delayed @delayed def myFunction(): return 1,2 dummy = myFunction() a, b = dummy[0], dummy[1] a.compute() Is this the intended behaviour? A: Use the nout= keyword as described in the delayed docstring @delayed(nout=2) def f(...): return a, b x, y = f(1) Docstring nout : int, optional The number of outputs returned from calling the resulting ``Delayed`` object. If provided, the ``Delayed`` output of the call can be iterated into ``nout`` objects, allowing for unpacking of results. By default iteration over ``Delayed`` objects will error. Note, that ``nout=1`` expects ``obj``, to return a tuple of length 1, and consequently for `nout=0``, ``obj`` should return an empty tuple.
stackoverflow
{ "language": "en", "length": 172, "provenance": "stackexchange_0000F.jsonl.gz:884349", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44602766" }
87938cbdbc6fd21d677573a2715d783f7515e7a8
Stackoverflow Stackexchange Q: How to get table name from Django filter objects I have diffrent tables with same columns Like class teachers(models.Model): x= models..CharField(max_length=250, blank=True, null=True); y= models..CharField(max_length=250, blank=True, null=True); class students(models.Model): x= models..CharField(max_length=250, blank=True, null=True); z= models..CharField(max_length=250, blank=True, null=True); I am using a function to process column x of both tables. So If any undesired values come in the value for x, I need to log that with the column name. Like f = students.objects.filter() def validate_x(obj): if obj.x == None: logger.error("None object found in table" + str(obj__tablename)) return False else: return True for i in f: validate_result = validate_x(i) My actual scenario is not null check. I just tried to explain it with this example. Is there any way to achieve this. I am using Django 1.6 A: Use this for getting database table name obj._meta.db_table This might be useful but in 1.11
Q: How to get table name from Django filter objects I have diffrent tables with same columns Like class teachers(models.Model): x= models..CharField(max_length=250, blank=True, null=True); y= models..CharField(max_length=250, blank=True, null=True); class students(models.Model): x= models..CharField(max_length=250, blank=True, null=True); z= models..CharField(max_length=250, blank=True, null=True); I am using a function to process column x of both tables. So If any undesired values come in the value for x, I need to log that with the column name. Like f = students.objects.filter() def validate_x(obj): if obj.x == None: logger.error("None object found in table" + str(obj__tablename)) return False else: return True for i in f: validate_result = validate_x(i) My actual scenario is not null check. I just tried to explain it with this example. Is there any way to achieve this. I am using Django 1.6 A: Use this for getting database table name obj._meta.db_table This might be useful but in 1.11 A: object.__class__.__name__ or object._meta.object_name should give you the name of the model. (if you need model name). when you need name of db table then you should use object._meta.db_table, as arpit-solanki said.
stackoverflow
{ "language": "en", "length": 175, "provenance": "stackexchange_0000F.jsonl.gz:884353", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44602786" }
945f5fda73e568c76611fc5bdeb430e2405bf617
Stackoverflow Stackexchange Q: Vue component props without value I want to set an attribute on my component without any value. For example: <my-button primary>Save</my-button> I'm declaring primary in props of my component: Vue.component("my-button", { props: ["primary"], template: "<button v-bind:class='{primary: primary}'><slot></slot></button>" }) Unfortunately, it doesn't work. The primary property is undefined and the class is not applied. JSFiddle: https://jsfiddle.net/LukaszWiktor/g3jkscna/ A: The key is to declare type of the prop as Boolean: props: { primary: Boolean } Then specifying only attribute name makes its value set to true. Working JSFiddle: https://jsfiddle.net/LukaszWiktor/gfa7gkdb/
Q: Vue component props without value I want to set an attribute on my component without any value. For example: <my-button primary>Save</my-button> I'm declaring primary in props of my component: Vue.component("my-button", { props: ["primary"], template: "<button v-bind:class='{primary: primary}'><slot></slot></button>" }) Unfortunately, it doesn't work. The primary property is undefined and the class is not applied. JSFiddle: https://jsfiddle.net/LukaszWiktor/g3jkscna/ A: The key is to declare type of the prop as Boolean: props: { primary: Boolean } Then specifying only attribute name makes its value set to true. Working JSFiddle: https://jsfiddle.net/LukaszWiktor/gfa7gkdb/
stackoverflow
{ "language": "en", "length": 87, "provenance": "stackexchange_0000F.jsonl.gz:884359", "question_score": "35", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44602795" }
0d64a1182722b4c8527385c23e1e78373c455eac
Stackoverflow Stackexchange Q: Starting Zookeeper and Kafka servers from Java application I am using a Java application which start a consumer reading Kafka topics. Every time I need to start the consumer application, I have to start the Zookeeper and Kafka servers with commands in cmd. Is it possible to start/stop them with small Java programs? Thank you. A: If you need this for something like testing the I think that the better way is using the Debezium library which provides a KafkaCluster embedded implementation. You can see how we use it in the Vert.x Kafka Client project for unit testing here : https://github.com/vert-x3/vertx-kafka-client/blob/master/src/test/java/io/vertx/kafka/client/tests/KafkaClusterTestBase.java Take a look around that ;)
Q: Starting Zookeeper and Kafka servers from Java application I am using a Java application which start a consumer reading Kafka topics. Every time I need to start the consumer application, I have to start the Zookeeper and Kafka servers with commands in cmd. Is it possible to start/stop them with small Java programs? Thank you. A: If you need this for something like testing the I think that the better way is using the Debezium library which provides a KafkaCluster embedded implementation. You can see how we use it in the Vert.x Kafka Client project for unit testing here : https://github.com/vert-x3/vertx-kafka-client/blob/master/src/test/java/io/vertx/kafka/client/tests/KafkaClusterTestBase.java Take a look around that ;) A: Please see this topic, it's about starting Zookeeper in Java: Best way to start zookeeper server from java program directing to this: Is it possible to start a zookeeper server instance in process, say for unit tests? A: To start up a Kafka cluster for your tests, you can use the following wrapper: https://www.testcontainers.org/modules/kafka/ See also this project which integrates Kafka further in the context of a Spring application: https://github.com/vspiliop/embedded-kafka-cluster
stackoverflow
{ "language": "en", "length": 179, "provenance": "stackexchange_0000F.jsonl.gz:884360", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44602797" }
efd356e9926e39c88782f37c3cbb80f750633df6
Stackoverflow Stackexchange Q: window.location.href - Link in new tab var notification = new Notification(theTitle, options); notification.onclick = function() { window.location.href = theLink; //redirects to the specified link }; I am trying to open a new tab by clicking the notification box. Using the above code the redirection works fine. But I want to open the link in a new tab. How Can I do this? A: notification.onclick = function() { window.open(theLink); };
Q: window.location.href - Link in new tab var notification = new Notification(theTitle, options); notification.onclick = function() { window.location.href = theLink; //redirects to the specified link }; I am trying to open a new tab by clicking the notification box. Using the above code the redirection works fine. But I want to open the link in a new tab. How Can I do this? A: notification.onclick = function() { window.open(theLink); }; A: try window.open("page url") hope it works
stackoverflow
{ "language": "en", "length": 77, "provenance": "stackexchange_0000F.jsonl.gz:884382", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44602848" }
4e3cd4dc1990a1d143cbc99c467f193723a6bdcf
Stackoverflow Stackexchange Q: Rest API for both create and update What is the preferred way of handling create and update request in a REST api? On my frontend i am using the same form for both creating and updating, the only difference is that in case of update a hidden form field with id is filled. Is it ok to send both requests to /api/post with POST method and based on the id decide whether to post or update? Or should this be handled otherwise? A: If you want to follow REST principles, separating the endpoint like below is preferred. POST api/collections (e.g. api/users) PUT api/collections/:id (e.g. api/users/23) There are 2 reasons to separate the endpoint. * *PUT has to be idempotent, while POST does not. *If the URL of the resource (like api/users/23) is already there, use PUT. If not, send POST and let the server generate URL. (In many cases, it uses DB’s auto-increment key) Of course, it is up to you to decide whether you follow REST principles. Reference https://restcookbook.com/HTTP%20Methods/put-vs-post/
Q: Rest API for both create and update What is the preferred way of handling create and update request in a REST api? On my frontend i am using the same form for both creating and updating, the only difference is that in case of update a hidden form field with id is filled. Is it ok to send both requests to /api/post with POST method and based on the id decide whether to post or update? Or should this be handled otherwise? A: If you want to follow REST principles, separating the endpoint like below is preferred. POST api/collections (e.g. api/users) PUT api/collections/:id (e.g. api/users/23) There are 2 reasons to separate the endpoint. * *PUT has to be idempotent, while POST does not. *If the URL of the resource (like api/users/23) is already there, use PUT. If not, send POST and let the server generate URL. (In many cases, it uses DB’s auto-increment key) Of course, it is up to you to decide whether you follow REST principles. Reference https://restcookbook.com/HTTP%20Methods/put-vs-post/
stackoverflow
{ "language": "en", "length": 171, "provenance": "stackexchange_0000F.jsonl.gz:884407", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44602911" }
99edf434a03df77f3aea0fd8d5d17e46374bc552
Stackoverflow Stackexchange Q: Notification onclick - Open a link in new tab and focus function spawnNotification(theBody, theIcon, theTitle, theLink) { var options = { body: theBody, icon: theIcon } var notification = new Notification(theTitle, options); notification.onclick = function() { var myWindow = window.open(theLink,"_blank"); myWindow.focus(); }; setTimeout(notification.close.bind(notification), 4000); } I am trying to open a new tab and to focus it , when the notification box is clicked. I am using the above fuction to open a link in a new tab and to focus on that newly opened tab. But its not working. New tab is opened, but the focus remains on the old tab itself. How can I solve this? A: function spawnNotification(theBody, theIcon, theTitle, theLink) { var options = { body: theBody, icon: theIcon } var notification = new Notification(theTitle, options); notification.onclick = function(event) { event.preventDefault(); // prevent the browser from focusing the Notification's tab window.open(theLink, '_blank'); } setTimeout(notification.close.bind(notification), 7000); } I changed my code as shown above. Now it works perfect. See: https://developer.mozilla.org/en-US/docs/Web/API/Notification/onclick#Examples
Q: Notification onclick - Open a link in new tab and focus function spawnNotification(theBody, theIcon, theTitle, theLink) { var options = { body: theBody, icon: theIcon } var notification = new Notification(theTitle, options); notification.onclick = function() { var myWindow = window.open(theLink,"_blank"); myWindow.focus(); }; setTimeout(notification.close.bind(notification), 4000); } I am trying to open a new tab and to focus it , when the notification box is clicked. I am using the above fuction to open a link in a new tab and to focus on that newly opened tab. But its not working. New tab is opened, but the focus remains on the old tab itself. How can I solve this? A: function spawnNotification(theBody, theIcon, theTitle, theLink) { var options = { body: theBody, icon: theIcon } var notification = new Notification(theTitle, options); notification.onclick = function(event) { event.preventDefault(); // prevent the browser from focusing the Notification's tab window.open(theLink, '_blank'); } setTimeout(notification.close.bind(notification), 7000); } I changed my code as shown above. Now it works perfect. See: https://developer.mozilla.org/en-US/docs/Web/API/Notification/onclick#Examples
stackoverflow
{ "language": "en", "length": 164, "provenance": "stackexchange_0000F.jsonl.gz:884460", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603081" }
cc14030e900b2252c1f7ec0492442b0d54e5f066
Stackoverflow Stackexchange Q: How to run a single scala test with scoverage? I know that sbt clean coverage test will generate coverage report using all test cases on the project, this takes ages to finish even with the warm JVM. I wish to run coverage on the tests for the code I wrote so, I tried to run a single testcase like sbt coverage test-only package.ScalaSpec and I get the following error. ERROR [scala-project] $ coverage test-only package.ScalaSpec <set>:1: error: eof expected but 'package' found. coverageEnabled in ThisBuild := true test-only package.ScalaSpec ^ [error] Error parsing expression. A: Surround your fully-qualified package name in quotes. coverage is failing because it is parsing the command as though the test goal is the first argument to coverage, and the qualified package name package.ScalaSpec as the second. What you want to do instead is give coverage only one argument like this: sbt coverage "testOnly package.ScalaSpec" Before, coverage is given the command test as its goal, followed by an unexpected 2nd parameter. After, coverage is given the command testOnly package.ScalaSpec as its goal.
Q: How to run a single scala test with scoverage? I know that sbt clean coverage test will generate coverage report using all test cases on the project, this takes ages to finish even with the warm JVM. I wish to run coverage on the tests for the code I wrote so, I tried to run a single testcase like sbt coverage test-only package.ScalaSpec and I get the following error. ERROR [scala-project] $ coverage test-only package.ScalaSpec <set>:1: error: eof expected but 'package' found. coverageEnabled in ThisBuild := true test-only package.ScalaSpec ^ [error] Error parsing expression. A: Surround your fully-qualified package name in quotes. coverage is failing because it is parsing the command as though the test goal is the first argument to coverage, and the qualified package name package.ScalaSpec as the second. What you want to do instead is give coverage only one argument like this: sbt coverage "testOnly package.ScalaSpec" Before, coverage is given the command test as its goal, followed by an unexpected 2nd parameter. After, coverage is given the command testOnly package.ScalaSpec as its goal.
stackoverflow
{ "language": "en", "length": 177, "provenance": "stackexchange_0000F.jsonl.gz:884476", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603140" }
598a1e190d46d3b8ac7fbecc1d5c4c36ef76637f
Stackoverflow Stackexchange Q: Use route parameters in Angular 4 with ID is String How to use route parameters with ID is String? {path: 'param/:id', component: MyComponent} let id = this.route.snapshot.params['id']; Any idea Blockquote A: Using the route snapshot to get the id query parameter as you've shown should give you a string. If you want to implicitly convert that string to a number so you can use it in a route parameter for navigation, you can prefix the variable with a +: // (+) converts string 'id' to a number let id = +this.route.snapshot.params['id']; Then: this.router.navigate(['/example', id]); Check out this example of getting the query param in the documentation https://angular.io/guide/router#snapshot-the-no-observable-alternative.
Q: Use route parameters in Angular 4 with ID is String How to use route parameters with ID is String? {path: 'param/:id', component: MyComponent} let id = this.route.snapshot.params['id']; Any idea Blockquote A: Using the route snapshot to get the id query parameter as you've shown should give you a string. If you want to implicitly convert that string to a number so you can use it in a route parameter for navigation, you can prefix the variable with a +: // (+) converts string 'id' to a number let id = +this.route.snapshot.params['id']; Then: this.router.navigate(['/example', id]); Check out this example of getting the query param in the documentation https://angular.io/guide/router#snapshot-the-no-observable-alternative. A: In the component you can use this code to transform from string into number: constructor(private route: ActivatedRoute) { } ngOnInit() { this.route.paramMap .subscribe((params: ParamMap) => { let id = +params.get('id'); // This line converts id from string into num }); }
stackoverflow
{ "language": "en", "length": 150, "provenance": "stackexchange_0000F.jsonl.gz:884477", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603142" }
0ab62411a6c984b0876a8d12d5bef14176fc7b22
Stackoverflow Stackexchange Q: PHP script on server request (apache) I want to make my own custom logging script on my Apache2 webserver. It should be executed on every server request (POST, GET, etc.) and then write some information into my database. My problem is: I don't now how to trigger the execution. I have searched (Google) for handlers in apache. "addHandler/setHandler" in apache2.conf. But these are just executed if a special file is requested. And putting a script on each of my pages is no option too. Just because I can't put a script to a requested image. Is there any option in config files to do something like: onRequest var/www/html/customLog.php I woud prefer .php or .sh. Thank you for giving a hint. P.S. I'm running my server on linux. A: The best way to do this is probably with CustomLog, you can log everything described in custom log formats which should cover everything you might want to log, and you can pipe it to a program which could be PHP or a shell script as you like, for logging it to your database.
Q: PHP script on server request (apache) I want to make my own custom logging script on my Apache2 webserver. It should be executed on every server request (POST, GET, etc.) and then write some information into my database. My problem is: I don't now how to trigger the execution. I have searched (Google) for handlers in apache. "addHandler/setHandler" in apache2.conf. But these are just executed if a special file is requested. And putting a script on each of my pages is no option too. Just because I can't put a script to a requested image. Is there any option in config files to do something like: onRequest var/www/html/customLog.php I woud prefer .php or .sh. Thank you for giving a hint. P.S. I'm running my server on linux. A: The best way to do this is probably with CustomLog, you can log everything described in custom log formats which should cover everything you might want to log, and you can pipe it to a program which could be PHP or a shell script as you like, for logging it to your database.
stackoverflow
{ "language": "en", "length": 182, "provenance": "stackexchange_0000F.jsonl.gz:884478", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603144" }
3ced690ed5003271820656238622993cb17d5be6
Stackoverflow Stackexchange Q: Why to use fluentmigrator? When and why to use FluentMigrator as Entity Framework Code-First Migration does the same job. The two appear to be very similar, what problem or flaw does FluentMigrator solve when EF already provides classes to manipulate the database schema. I am not clear why and when(in which cases) to use fluentmigrator? A: Not everybody uses Entity Framework. I don't use it in my current project for example. In this scenario FluentMigrator is very useful for managing the database changes for each release.
Q: Why to use fluentmigrator? When and why to use FluentMigrator as Entity Framework Code-First Migration does the same job. The two appear to be very similar, what problem or flaw does FluentMigrator solve when EF already provides classes to manipulate the database schema. I am not clear why and when(in which cases) to use fluentmigrator? A: Not everybody uses Entity Framework. I don't use it in my current project for example. In this scenario FluentMigrator is very useful for managing the database changes for each release. A: EntityFramework kind of gives you both tasks: ORM and migration (CodeFirst). I, for instance, use NHibernate and use FluentMigrator. The first as ORM and the second as the database migration library. You could say indeed that I am writing two faces of the same concept so it is more maintenance costs, however, I prefer higher control over this (ORM and migration separately) because you could screw up very easily if it's not explicit up front. A: Adding to the examples above: in case you use some Micro ORM like Dapper, you'll need a separate tool for database migrations. That's what Fluent Migrator is all about.
stackoverflow
{ "language": "en", "length": 193, "provenance": "stackexchange_0000F.jsonl.gz:884498", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603221" }
bcb806d1fe4fdc053796c0e1eec98171f3823007
Stackoverflow Stackexchange Q: Laravel Limit Client Download Speed (Bandwidth throttling) In Laravel, I can download using response()->download(); But is there any way to limit client speed? A: You can use this package: https://github.com/bandwidth-throttle/bandwidth-throttle Installation composer require bandwidth-throttle/bandwidth-throttle This example will stream a video with a rate of 100KiB/s to the browser: use bandwidthThrottle\BandwidthThrottle; $in = fopen(__DIR__ . "/video.mpg", "r"); $out = fopen("php://output", "w"); $throttle = new BandwidthThrottle(); $throttle->setRate(100, BandwidthThrottle::KIBIBYTES); // Set limit to 100KiB/s $throttle->throttle($out); stream_copy_to_stream($in, $out);
Q: Laravel Limit Client Download Speed (Bandwidth throttling) In Laravel, I can download using response()->download(); But is there any way to limit client speed? A: You can use this package: https://github.com/bandwidth-throttle/bandwidth-throttle Installation composer require bandwidth-throttle/bandwidth-throttle This example will stream a video with a rate of 100KiB/s to the browser: use bandwidthThrottle\BandwidthThrottle; $in = fopen(__DIR__ . "/video.mpg", "r"); $out = fopen("php://output", "w"); $throttle = new BandwidthThrottle(); $throttle->setRate(100, BandwidthThrottle::KIBIBYTES); // Set limit to 100KiB/s $throttle->throttle($out); stream_copy_to_stream($in, $out); A: No as far as i know, you can't limit the download speed via script.
stackoverflow
{ "language": "en", "length": 90, "provenance": "stackexchange_0000F.jsonl.gz:884523", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603309" }
532e0993f0d3a37bd614e0e5f03be12d90410b89
Stackoverflow Stackexchange Q: How to destroy reactive FormControl on Component destroy? I have a component with FormControl and subscription on it's value change: @Component(...) export class FooComponent implements OnInit, OnDestroy { fooFormControl: FormControl; ... ngOnInit() { this.fooFormControl.valueChanges.subscribe( () => {...}, () => {}, () => { // never happens }, ); } ngOnDestroy() { //happens } } But when component is destroyed FormControl element isn't destroyed and onComplete callback never happens. What is the right way to destroy FormControl element on component destroy? A: FormControl observables aren't supposed to be completed, although it is possible to do this manually if there is some logic that belongs to complete callback. Since valueChanges is event emitter and inherits from RxJS Subject, it can be unsubscribed or completed: ngOnDestroy() { this.fooFormControl.valueChanges.complete(); // and/or this.fooFormControl.valueChanges.unsubscribe(); } It is possible that EventEmitter won't be a subject in future. This may cause breaking changes, but currently it solely relies on RxJS.
Q: How to destroy reactive FormControl on Component destroy? I have a component with FormControl and subscription on it's value change: @Component(...) export class FooComponent implements OnInit, OnDestroy { fooFormControl: FormControl; ... ngOnInit() { this.fooFormControl.valueChanges.subscribe( () => {...}, () => {}, () => { // never happens }, ); } ngOnDestroy() { //happens } } But when component is destroyed FormControl element isn't destroyed and onComplete callback never happens. What is the right way to destroy FormControl element on component destroy? A: FormControl observables aren't supposed to be completed, although it is possible to do this manually if there is some logic that belongs to complete callback. Since valueChanges is event emitter and inherits from RxJS Subject, it can be unsubscribed or completed: ngOnDestroy() { this.fooFormControl.valueChanges.complete(); // and/or this.fooFormControl.valueChanges.unsubscribe(); } It is possible that EventEmitter won't be a subject in future. This may cause breaking changes, but currently it solely relies on RxJS. A: Here are two ideas that may help you. Not sure if they are the "right way" but it has worked pretty well for me so far. Besides this I am unsubscribing in ngOnDestroy like usual. #1 Force completion by introducing your own subject via takeUntil In TypeScript the valueChanges property is of type Observable. If you don't want to work around that and get to the Subject then you can introduce your own Subject by using the takeUntil operator. This will allow you to force the propagation of completion at a level above the valueChanges observable. It is important to not put the takeUntil operator before a switchmap or the switched to observable will continue and your subscription will not be canceled! For that reason I put it right before the subscribe operator. Here is an example: const stop = new Subject(); // simulate ngOnDestroy window.setTimeout(() => { stop.next(); stop.complete(); }, 3500); Observable .interval(1000) .takeUntil(stop) .subscribe( () => { console.log('next'); }, () => { console.log('error'); }, () => { console.log('complete'); } ); Here is a working example: https://rxviz.com/v/RoQNBnOM #2 add the FormBuilder to your component's provider list This is what I usually do. Actually I usually encapsulate my form inside a service that uses the FormBuilder but the effect is the same. Providing the service at this level will destroy and recreate the service each time the component is created. I started doing this because I kept having weird bugs caused by observable streams that were created off of valueChanges persisting past the lifespan of the component. They would get resubscribed to when the component was recreated and stuff like that. Here is an example: @Component({ selector: 'my-form', templateUrl: './my-form.component.html', styleUrls: ['./my-form.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [ FormBuilder ] // <-- THIS PART }) export class MyFormComponent implements OnInit, OnDestroy { } Note that this doesn't actually propagate completion. But it does give you a fresh source subject each time. A: You can't destroy your form control. Everything inside the component will be destroyed with it, but the events can holds in your app. So you can unsubscribe it's events. @Component(...) export class FooComponent implements OnInit, OnDestroy { fooFormControl: FormControl; var subscriber; ... ngOnInit() { this.subscriber = this.fooFormControl.valueChanges.subscribe( () => {...}, () => {}, () => { // never happens }, ); } ngOnDestroy() { this.subscriber.unsubscribe(); } }
stackoverflow
{ "language": "en", "length": 541, "provenance": "stackexchange_0000F.jsonl.gz:884528", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603327" }
2e1b029e20c71d3e556ea29cc6b3245a0cd5e4e8
Stackoverflow Stackexchange Q: Google Cloud Console Language Interface I have a problem with the language interface of page console.cloud.google.com My language in the account is Vietnamese and English. But now it was changed to this language. I don't know to change it back to English. Can somebody help me with this problem? A: * *Click the menu button (one with 3 vertical dots) in the top right hand side corner, left of your profile image. *Choose Preferences, which is the first item in the menu overlay. You will be now taken to the User Preferences page. *You will see 3 items in the left hand side list, the second one is Language & Region. Click on this second item. *You will see the page where you can choose language, date, time and number formats. The first drop-down in this page is Language selection. Choose your desired language from this list. *After selecting the language, hit the Save button, which is the only blue colored button on this page.
Q: Google Cloud Console Language Interface I have a problem with the language interface of page console.cloud.google.com My language in the account is Vietnamese and English. But now it was changed to this language. I don't know to change it back to English. Can somebody help me with this problem? A: * *Click the menu button (one with 3 vertical dots) in the top right hand side corner, left of your profile image. *Choose Preferences, which is the first item in the menu overlay. You will be now taken to the User Preferences page. *You will see 3 items in the left hand side list, the second one is Language & Region. Click on this second item. *You will see the page where you can choose language, date, time and number formats. The first drop-down in this page is Language selection. Choose your desired language from this list. *After selecting the language, hit the Save button, which is the only blue colored button on this page. A: First, click on the 3dots, go to preferences, then Language & Region :
stackoverflow
{ "language": "en", "length": 180, "provenance": "stackexchange_0000F.jsonl.gz:884547", "question_score": "13", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603384" }
1ac5c1ce13af4090778c432fa9fede7ed9f84e4f
Stackoverflow Stackexchange Q: Google Spreadsheet adding tooltip I need to add a tooltip (mouser over a cell) in a Google spreadsheet. I want the tooltip text to be taken from another cell, some idea? Thanks in advance! A: Consider using notes - they appear when you hover mouse over cells in a spreadsheet. You can add notes manually by clicking the right mouse button on a cell and selecting 'insert note'. This can also be done programmatically. Say, you've got 2 adjacent cells. We'll use text from the second cell to add a note to the first one. You can create the note with the text from the second cell using the following code. function addNote() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var targetCell = sheet.getRange("A1"); var sourceCell = sheet.getRange("B1"); var noteText = sourceCell.getValue(); targetCell.setNote(noteText); } Here's the end result after executing the function You can modify the code to make it run only when the sheet is edited and dynamically update the note when the text in the source cell changes.
Q: Google Spreadsheet adding tooltip I need to add a tooltip (mouser over a cell) in a Google spreadsheet. I want the tooltip text to be taken from another cell, some idea? Thanks in advance! A: Consider using notes - they appear when you hover mouse over cells in a spreadsheet. You can add notes manually by clicking the right mouse button on a cell and selecting 'insert note'. This can also be done programmatically. Say, you've got 2 adjacent cells. We'll use text from the second cell to add a note to the first one. You can create the note with the text from the second cell using the following code. function addNote() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var targetCell = sheet.getRange("A1"); var sourceCell = sheet.getRange("B1"); var noteText = sourceCell.getValue(); targetCell.setNote(noteText); } Here's the end result after executing the function You can modify the code to make it run only when the sheet is edited and dynamically update the note when the text in the source cell changes.
stackoverflow
{ "language": "en", "length": 173, "provenance": "stackexchange_0000F.jsonl.gz:884560", "question_score": "23", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603429" }
63577dd75691e11177c95a64598d1abaa732485b
Stackoverflow Stackexchange Q: How to validate Iranian National Code (Melli Code or Code Melli) in android I need a method to validate the Melli Code (National Code or Code Melli) of Iranian people. I Know it has a formula. A: Good job Alireza, Here is my code which is very similar to yours. ‍‍‍ private boolean isValidNationalCode(String nationalCode) { if (nationalCode.length() != 10) { return false; } else { //Check for equal numbers String[] allDigitEqual = {"0000000000", "1111111111", "2222222222", "3333333333", "4444444444", "5555555555", "6666666666", "7777777777", "8888888888", "9999999999"}; if (Arrays.asList(allDigitEqual).contains(nationalCode)) { return false; } else { int sum = 0; int lenght = 10; for (int i = 0; i < lenght - 1; i++) { sum += Integer.parseInt(String.valueOf(nationalCode.charAt(i))) * (lenght - i); } int r = Integer.parseInt(String.valueOf(nationalCode.charAt(9))); int c = sum % 11; return (((c < 2) && (r == c)) || ((c >= 2) && ((11 - c) == r))); } } }
Q: How to validate Iranian National Code (Melli Code or Code Melli) in android I need a method to validate the Melli Code (National Code or Code Melli) of Iranian people. I Know it has a formula. A: Good job Alireza, Here is my code which is very similar to yours. ‍‍‍ private boolean isValidNationalCode(String nationalCode) { if (nationalCode.length() != 10) { return false; } else { //Check for equal numbers String[] allDigitEqual = {"0000000000", "1111111111", "2222222222", "3333333333", "4444444444", "5555555555", "6666666666", "7777777777", "8888888888", "9999999999"}; if (Arrays.asList(allDigitEqual).contains(nationalCode)) { return false; } else { int sum = 0; int lenght = 10; for (int i = 0; i < lenght - 1; i++) { sum += Integer.parseInt(String.valueOf(nationalCode.charAt(i))) * (lenght - i); } int r = Integer.parseInt(String.valueOf(nationalCode.charAt(9))); int c = sum % 11; return (((c < 2) && (r == c)) || ((c >= 2) && ((11 - c) == r))); } } } A: You can validate your national code like this: Updated public static boolean isValidNationalCode(String nationalCode) { if (!nationalCode.matches("^\\d{10}$")) return false; int sum = 0; for (int i = 0; i < 9; i++) { sum += Character.getNumericValue(nationalCode.charAt(i)) * (10 - i); } int lastDigit = Integer.parseInt(String.valueOf(nationalCode.charAt(9))); int divideRemaining = sum % 11; return ((divideRemaining < 2 && lastDigit == divideRemaining) || (divideRemaining >= 2 && (11 - divideRemaining) == lastDigit )); } A: I have different versions of it here and the following is its Kotlin one, fun isValidIranianNationalCode(input: String) = input.takeIf { it.length == 10 } ?.mapNotNull(Char::digitToIntOrNull)?.takeIf { it.size == 10 }?.let { val check = it[9] val sum = it.slice(0..8).mapIndexed { i, x -> x * (10 - i) }.sum() % 11 if (sum < 2) check == sum else check + sum == 11 } ?: false A: This method validates the Iranian people's National code. public boolean validateMelliCode(String melliCode) { String[] identicalDigits = {"0000000000", "1111111111", "2222222222", "3333333333", "4444444444", "5555555555", "6666666666", "7777777777", "8888888888", "9999999999"}; if (melliCode.trim().isEmpty()) { Toast.makeText(getApplicationContext(), "National Code is empty", Toast.LENGTH_LONG).show(); return false; // National Code is empty } else if (melliCode.length() != 10) { Toast.makeText(getApplicationContext(), "National Code must be exactly 10 digits", Toast.LENGTH_LONG).show(); return false; // National Code is less or more than 10 digits } else if (Arrays.asList(identicalDigits).contains(melliCode)) { Toast.makeText(getApplicationContext(), "MelliCode is not valid (Fake MelliCode)", Toast.LENGTH_LONG).show(); return false; // Fake National Code } else { int sum = 0; for (int i = 0; i < 9; i++) { sum += Character.getNumericValue(melliCode.charAt(i)) * (10 - i); } int lastDigit; int divideRemaining = sum % 11; if (divideRemaining < 2) { lastDigit = divideRemaining; } else { lastDigit = 11 - (divideRemaining); } if (Character.getNumericValue(melliCode.charAt(9)) == lastDigit) { Toast.makeText(getApplicationContext(), "MelliCode is valid", Toast.LENGTH_LONG).show(); return true; } else { Toast.makeText(getApplicationContext(), "MelliCode is not valid", Toast.LENGTH_LONG).show(); return false; // Invalid MelliCode } } } UPDATE This authentic news agency said there is a man who has "1111111111" national code, so we have to accept the national codes composed of repetitive digits. So we don't need this Array: String[] identicalDigits = {"0000000000", "1111111111", "2222222222", "3333333333", "4444444444", "5555555555", "6666666666", "7777777777", "8888888888", "9999999999"}; and also we don't need this part of condition: else if (Arrays.asList(identicalDigits).contains(melliCode)) { Toast.makeText(getApplicationContext(), "MelliCode is not valid (Fake MelliCode)", Toast.LENGTH_LONG).show(); return false; // Fake National Code } Good Luck! A: For Javascript Developers: const checkCodeMeli = code => { console.log("an"); var L = code.length; if (L < 8 || parseInt(code, 10) === 0) return false; code = ("0000" + code).substr(L + 4 - 10); if (parseInt(code.substr(3, 6), 10) === 0) return false; var c = parseInt(code.substr(9, 1), 10); var s = 0; for (var i = 0; i < 9; i++) { s += parseInt(code.substr(i, 1), 10) * (10 - i); } s = s % 11; return (s < 2 && c === s) || (s >= 2 && c === 11 - s); }; A: Java 8 import java.util.stream.Streams; import java.util.function.IntUnaryOperator; public static boolean isValidIranianNationalCode(String input) { if (!input.matches("^\\d{10}$")) return false; int check = Integer.parseInt(input.substring(9, 10)); int sum = IntStream.range(0, 9) .map(x -> Integer.parseInt(input.substring(x, x + 1)) * (10 - x)) .sum() % 11; return (sum < 2 && check == sum) || (sum >= 2 && check + sum == 11); } A: First, use the System.Text.RegularExpressions class and then use this script:. #region NationalCode Check public bool NationalCodeCheck(string input) { if (!Regex.IsMatch(input, @"^\d{10}$")) return false; var check = Convert.ToInt32(input.Substring(9, 1)); var sum = Enumerable.Range(0, 9) .Select(x => Convert.ToInt32(input.Substring(x, 1)) * (10 - x)) .Sum() % 11; return (sum < 2 && check == sum) || (sum >= 2 && check + sum == 11); } #endregion
stackoverflow
{ "language": "en", "length": 757, "provenance": "stackexchange_0000F.jsonl.gz:884598", "question_score": "16", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603570" }
fae681e37dff4d71d82631ee97e92bd132e479a7
Stackoverflow Stackexchange Q: Injecting c# type into Ironpython Right now I can use following code to access my c# types in IronPython as follow import clr clr.AddReference('myDLL.dll') import myType obj = myType() however I don't want script developers to have clr.AddReference('myDLL.dll') line in Python source code, and inject myDLL.dll (and/or a c# class) directly from c# into ScriptEngine so the previous code will be something similar to: import myType obj = myType() how can I achieve this? A: You can solve this problem using following solution : ScriptRuntime runtime = Python.CreateRuntime(); runtime.LoadAssembly(Assembly.GetAssembly(typeof(MyNameSpace.MyClass))); ScriptEngine eng = runtime.GetEngine("py"); ScriptScope scope = eng.CreateScope(); ScriptSource src = eng.CreateScriptSourceFromString(MySource, SourceCodeKind.Statements); var result = src.Execute(scope); Now, in python script you can write: from MyNameSpace import * n=MyClass() print n.DoSomeThing()
Q: Injecting c# type into Ironpython Right now I can use following code to access my c# types in IronPython as follow import clr clr.AddReference('myDLL.dll') import myType obj = myType() however I don't want script developers to have clr.AddReference('myDLL.dll') line in Python source code, and inject myDLL.dll (and/or a c# class) directly from c# into ScriptEngine so the previous code will be something similar to: import myType obj = myType() how can I achieve this? A: You can solve this problem using following solution : ScriptRuntime runtime = Python.CreateRuntime(); runtime.LoadAssembly(Assembly.GetAssembly(typeof(MyNameSpace.MyClass))); ScriptEngine eng = runtime.GetEngine("py"); ScriptScope scope = eng.CreateScope(); ScriptSource src = eng.CreateScriptSourceFromString(MySource, SourceCodeKind.Statements); var result = src.Execute(scope); Now, in python script you can write: from MyNameSpace import * n=MyClass() print n.DoSomeThing()
stackoverflow
{ "language": "en", "length": 121, "provenance": "stackexchange_0000F.jsonl.gz:884609", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603598" }
b4ac4840065be3bbb12ee27461e46f2ec316620d
Stackoverflow Stackexchange Q: python how to plot classification data I'm unable to plot the data for classification algo using numpy as it throws this error ValueError: x and y must be the same size My data in the data variable look like this: [[ 34.62365962 78.02469282 0. ] [ 30.28671077 43.89499752 0. ] [ 35.84740877 72.90219803 0. ] [ 60.18259939 86.3085521 1. ] [ 79.03273605 75.34437644 1. ] [ 45.08327748 56.31637178 0. ] [ 61.10666454 96.51142588 1. ] [ 75.02474557 46.55401354 1. ]] Code: data=np.loadtxt('ex2data1.txt',delimiter=',',dtype=None) X = data[:, [0,1]] y = data[:, 2] pylab.scatter(X,y) pylab.show() I'm trying to plot this: A: The easiest way would be to unpack the data already while loading import matplotlib.pyplot as plt x,y,c = np.loadtxt('ex2data1.txt',delimiter=',', unpack=True) plt.scatter(x,y,c=c) plt.show() Obviously you can do the unpacking also afterwards, import matplotlib.pyplot as plt data = np.loadtxt('ex2data1.txt',delimiter=',') plt.scatter(data[:,0],data[:,1],c=data[:,2]) plt.show()
Q: python how to plot classification data I'm unable to plot the data for classification algo using numpy as it throws this error ValueError: x and y must be the same size My data in the data variable look like this: [[ 34.62365962 78.02469282 0. ] [ 30.28671077 43.89499752 0. ] [ 35.84740877 72.90219803 0. ] [ 60.18259939 86.3085521 1. ] [ 79.03273605 75.34437644 1. ] [ 45.08327748 56.31637178 0. ] [ 61.10666454 96.51142588 1. ] [ 75.02474557 46.55401354 1. ]] Code: data=np.loadtxt('ex2data1.txt',delimiter=',',dtype=None) X = data[:, [0,1]] y = data[:, 2] pylab.scatter(X,y) pylab.show() I'm trying to plot this: A: The easiest way would be to unpack the data already while loading import matplotlib.pyplot as plt x,y,c = np.loadtxt('ex2data1.txt',delimiter=',', unpack=True) plt.scatter(x,y,c=c) plt.show() Obviously you can do the unpacking also afterwards, import matplotlib.pyplot as plt data = np.loadtxt('ex2data1.txt',delimiter=',') plt.scatter(data[:,0],data[:,1],c=data[:,2]) plt.show() A: # Visualising the Training set results from matplotlib.colors import ListedColormap X_set, y_set = X_train, y_train X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) plt.contourf(X1, X2, cla.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('KNN (Training set)') plt.fig(figsize=(12,6)) plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show() See the example
stackoverflow
{ "language": "en", "length": 234, "provenance": "stackexchange_0000F.jsonl.gz:884614", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603609" }
1616ef058a1b274bc4426631d3604973e11a20a6
Stackoverflow Stackexchange Q: Plot 95% confidence interval errorbar python pandas dataframes I want to show 95% confidence interval with Python pandas, matpolib... But I stucked, because for usual .std() I would do smth like this: import pandas as pd import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import math data = pd.read_table('output.txt',sep=r'\,', engine='python') Ox = data.groupby(['Ox'])['Ox'].mean() Oy = data.groupby(['Ox'])['Oy'].mean() std = data.groupby(['Ox'])['Oy'].std() plt.plot(Ox, Oy , label = 'STA = '+ str(x)) plt.errorbar(Ox, Oy, std, label = 'errorbar', linewidth=2) plt.legend(loc='best', prop={'size':9.2}) plt.savefig('plot.pdf') plt.close() But I haven't found something in pandas methods which can help me. Does anybody know? A: For a normal distribution ~95% of the values lie within a window of 4 standard deviations around the mean, or in other words, 95% of the values are within plus/minus 2 standard deviations from the mean. See, e.g. 68–95–99.7-rule. plt.errorbar's yerr argument specifies the length of the single sided errorbar. Thus taking plt.errorbar(x,y,yerr=2*std) where std is the standard deviation shows the errorbars of the 95% confidence interval.
Q: Plot 95% confidence interval errorbar python pandas dataframes I want to show 95% confidence interval with Python pandas, matpolib... But I stucked, because for usual .std() I would do smth like this: import pandas as pd import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import math data = pd.read_table('output.txt',sep=r'\,', engine='python') Ox = data.groupby(['Ox'])['Ox'].mean() Oy = data.groupby(['Ox'])['Oy'].mean() std = data.groupby(['Ox'])['Oy'].std() plt.plot(Ox, Oy , label = 'STA = '+ str(x)) plt.errorbar(Ox, Oy, std, label = 'errorbar', linewidth=2) plt.legend(loc='best', prop={'size':9.2}) plt.savefig('plot.pdf') plt.close() But I haven't found something in pandas methods which can help me. Does anybody know? A: For a normal distribution ~95% of the values lie within a window of 4 standard deviations around the mean, or in other words, 95% of the values are within plus/minus 2 standard deviations from the mean. See, e.g. 68–95–99.7-rule. plt.errorbar's yerr argument specifies the length of the single sided errorbar. Thus taking plt.errorbar(x,y,yerr=2*std) where std is the standard deviation shows the errorbars of the 95% confidence interval. A: Using 2 * std to estimate the 95 % interval In a normal distribution, the interval [μ - 2σ, μ + 2σ] covers 95.5 %, so you can use 2 * std to estimate the 95 % interval: import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame() df['category'] = np.random.choice(np.arange(10), 1000, replace=True) df['number'] = np.random.normal(df['category'], 1) mean = df.groupby('category')['number'].mean() std = df.groupby('category')['number'].std() plt.errorbar(mean.index, mean, xerr=0.5, yerr=2*std, linestyle='') plt.show() Result: Using percentiles If your distribution is skewed, it is better to use asymmetrical errorbars and get your 95% interval from the percentiles. import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.stats import skewnorm df = pd.DataFrame() df['category'] = np.random.choice(np.arange(10), 1000, replace=True) df['number'] = skewnorm.rvs(5, df['category'], 1) mean = df.groupby('category')['number'].mean() p025 = df.groupby('category')['number'].quantile(0.025) p975 = df.groupby('category')['number'].quantile(0.975) plt.errorbar( mean.index, mean, xerr=0.5, yerr=[mean - p025, p975 - mean], linestyle='', ) plt.show() Result: A: To obtain the 95% confidence interval you'll need to define a function. Tweaking: Compute a confidence interval from sample data def mean_confidence_interval(data, confidence=0.95): a = 1.0 * np.array(data) n = len(a) m, se = np.mean(a), scipy.stats.sem(a) h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1) return m def bound_confidence_interval(data, confidence=0.95): a = 1.0 * np.array(data) n = len(a) m, se = np.mean(a), scipy.stats.sem(a) h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1) return h Then define: mean = df.groupby(by='yourquery').agg(mean_confidence_interval) bound = df.groupby(by='yourquery').agg(bound_confidence_interval) Finally plot with a library of your choice: e.g. plotly import plotly.graph_objects as go fig = go.Figure(data=go.Scatter( x=mean[yourquery], y=mean[yourquery2], error_y=dict( type='data', # value of error bar given in data coordinates array=bound[yourquery2], visible=True) )) fig.show()
stackoverflow
{ "language": "en", "length": 435, "provenance": "stackexchange_0000F.jsonl.gz:884616", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603615" }
ba3552b35c237ace4bf7aabdca84323062a5211d
Stackoverflow Stackexchange Q: How to import multiple vector drawables to Android Studio project I used https://inloop.github.io/svg2android/ to convert 50+ SVG's to XML as suggested in this answer. Now I have a .zip containing all the XML files. Where do I put them to be able to use them in Android Studio? I know I can import one by one but that's what I'm trying to avoid in the first place. A: Just put the xml files in drawable folder, and you will be able to retrieve them using R.drawable.names
Q: How to import multiple vector drawables to Android Studio project I used https://inloop.github.io/svg2android/ to convert 50+ SVG's to XML as suggested in this answer. Now I have a .zip containing all the XML files. Where do I put them to be able to use them in Android Studio? I know I can import one by one but that's what I'm trying to avoid in the first place. A: Just put the xml files in drawable folder, and you will be able to retrieve them using R.drawable.names
stackoverflow
{ "language": "en", "length": 87, "provenance": "stackexchange_0000F.jsonl.gz:884628", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603663" }
2ad1416f27a3ea307e9ba1dcb04e1921aa0350c9
Stackoverflow Stackexchange Q: How to merge two shapes in a single gradient android how to merge border or single gradient in both.how to possible?? Already tried this background shape as below :- shape.xml <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:top="175dp"> <shape android:shape="oval"> <gradient android:angle="135" android:startColor="#f56f2c" android:endColor="#fa9f46"/> </shape> </item> <item android:bottom="40dp" > <shape android:shape="rectangle"> <gradient android:angle="135" android:startColor="#f56f2c" android:endColor="#fa9f46"/> </shape> </item> </layer-list> A: I solved the problem...the gradient angle change to 90.the matter is keeps the colours variation together item borders.fixed to same colour each boarder. example: <item android:top="165dp"> <shape android:shape="oval" > <gradient android:angle="0" android:startColor="#C96DD8" android:centerColor="#C96DD8" android:endColor="#C96DD8"/> </shape> </item> <item android:bottom="40dp"> <shape android:shape="rectangle"> <gradient android:angle="-90" android:startColor="#3023AE" android:centerColor="#7344ac" android:endColor="#C96DD8"/> </shape> </item>
Q: How to merge two shapes in a single gradient android how to merge border or single gradient in both.how to possible?? Already tried this background shape as below :- shape.xml <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:top="175dp"> <shape android:shape="oval"> <gradient android:angle="135" android:startColor="#f56f2c" android:endColor="#fa9f46"/> </shape> </item> <item android:bottom="40dp" > <shape android:shape="rectangle"> <gradient android:angle="135" android:startColor="#f56f2c" android:endColor="#fa9f46"/> </shape> </item> </layer-list> A: I solved the problem...the gradient angle change to 90.the matter is keeps the colours variation together item borders.fixed to same colour each boarder. example: <item android:top="165dp"> <shape android:shape="oval" > <gradient android:angle="0" android:startColor="#C96DD8" android:centerColor="#C96DD8" android:endColor="#C96DD8"/> </shape> </item> <item android:bottom="40dp"> <shape android:shape="rectangle"> <gradient android:angle="-90" android:startColor="#3023AE" android:centerColor="#7344ac" android:endColor="#C96DD8"/> </shape> </item> A: example: <item android:top="165dp"> <shape android:shape="oval" > <gradient android:angle="0" android:startColor="#C96DD8" android:centerColor="#C96DD8" android:endColor="#C96DD8"/> </shape> </item> <item android:bottom="40dp"> <shape android:shape="rectangle"> <gradient android:angle="-90" android:startColor="#3023AE" android:centerColor="#7344ac" android:endColor="#C96DD8"/> </shape> </item>
stackoverflow
{ "language": "en", "length": 128, "provenance": "stackexchange_0000F.jsonl.gz:884657", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603763" }
39f7db27a6134bdcde555786a94089057f2d092e
Stackoverflow Stackexchange Q: Android AudioRecord read always returns -3 (ERROR_INVALID_OPERATION) I have tried simplifying the code to the bare minimum and it still doesn't work: public class MainActivity extends AppCompatActivity { AudioRecord rec; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rec= new AudioRecord(MediaRecorder.AudioSource.MIC,44100, AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT,8192); short buff[] = new short[8192]; int read = rec.read(buff,0,buff.length); System.out.print(read); } Always returns -3 no matter what. What am I missing? A: Together with my friend we have finally managed to solve this issue. You need to call AudioRecord.startRecording() before calling read(). Also after you're done you should call AudioRecord.stop(). I wonder why it's so hard to find this basic piece of information
Q: Android AudioRecord read always returns -3 (ERROR_INVALID_OPERATION) I have tried simplifying the code to the bare minimum and it still doesn't work: public class MainActivity extends AppCompatActivity { AudioRecord rec; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rec= new AudioRecord(MediaRecorder.AudioSource.MIC,44100, AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT,8192); short buff[] = new short[8192]; int read = rec.read(buff,0,buff.length); System.out.print(read); } Always returns -3 no matter what. What am I missing? A: Together with my friend we have finally managed to solve this issue. You need to call AudioRecord.startRecording() before calling read(). Also after you're done you should call AudioRecord.stop(). I wonder why it's so hard to find this basic piece of information A: Did you checked the permissions in manifest ? </application> <uses-permission android:name="android.permission.RECORD_AUDIO" /> Documentation says : Reads audio data from the audio hardware for recording into a byte array. The format specified in the AudioRecord constructor should be ENCODING_PCM_8BIT to correspond to the data in the array. Parameters audioData byte: the array to which the recorded audio data is written. This value must never be null. offsetInBytes int: index in audioData from which the data is written expressed in bytes. sizeInBytes int: the number of requested bytes. Returns int zero or the positive number of bytes that were read, or one of the following error codes. The number of bytes will not exceed sizeInBytes. ERROR_INVALID_OPERATION if the object isn't properly initialized i think you should check the initialization of AudioRecord object. So look at this answer : Android AudioRecord example A: According to the Android documentation - -3 indicates that it is an invalid operation. Denotes a failure due to the improper use of a method. Constant Value: -3 (0xfffffffd) This problem is mostly likely because it couldn't create an AudioRecord instance with the parameters that you have specified. After you create the object try to check whether it was initialized correctly via the method getState if (rec.getState() == AudioRecord.STATE_UNINITIALIZED) { // Oops looks like it was not initalized correctly } If it is the state is indeed uninitialized then try setting different audio properties. Check the documentation for AudioRecord [constructor](https://developer.android.com/reference/android/media/AudioRecord.html#AudioRecord(int, int, int, int, int)), the documentation provides a comprehensive details on how to initialize the different parameters.
stackoverflow
{ "language": "en", "length": 364, "provenance": "stackexchange_0000F.jsonl.gz:884677", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603818" }
da283f5ab5cc76fbb66b0c34dc94cc19d5d9c800
Stackoverflow Stackexchange Q: Is there a way to use functions with same names but different return types? My intention is the following: My first function: public mutating func replaceSubstringInRange(_ range: CountableClosedRange<Int>, withString string: String) -> String that I can use it in a context of print() for example. And my second: public mutating func replaceSubstringInRange(_ range: CountableClosedRange<Int>, withString string: String) -> Void just for modifying something. I know that there is a different function signature needed, but is there any better way? A: You cannot define two functions with identical parameter types without creating an ambiguity, but you can call a function returning a value as if it were Void. This generates a warning, which you can silence by designating your function result discardable: @discardableResult public mutating func replaceSubstringInRange(_ range: CountableClosedRange<Int>, withString string: String) -> String { }
Q: Is there a way to use functions with same names but different return types? My intention is the following: My first function: public mutating func replaceSubstringInRange(_ range: CountableClosedRange<Int>, withString string: String) -> String that I can use it in a context of print() for example. And my second: public mutating func replaceSubstringInRange(_ range: CountableClosedRange<Int>, withString string: String) -> Void just for modifying something. I know that there is a different function signature needed, but is there any better way? A: You cannot define two functions with identical parameter types without creating an ambiguity, but you can call a function returning a value as if it were Void. This generates a warning, which you can silence by designating your function result discardable: @discardableResult public mutating func replaceSubstringInRange(_ range: CountableClosedRange<Int>, withString string: String) -> String { } A: You can have two functions with same name, same parameters and different return type. But if you call that function and do not provide any clue to compiler which function of the two to call, then it gives ambiguity error, Examples: func a() -> String { return "a" } func a() -> Void { print("test") } var s: String; s = a() // here the output of a is getting fetched to a variable of type string, // and hence compiler understands you want to call a() which returns string var d: Void = a() // this will call a which returns void a() // this will give error Ambiguous use of 'a()'
stackoverflow
{ "language": "en", "length": 250, "provenance": "stackexchange_0000F.jsonl.gz:884683", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603840" }
de4de927020b858de8c04be6062a22fce1c4ccb9
Stackoverflow Stackexchange Q: Alternative for strings.xml (It is in android) for IOS There is strings.xml in Android which we can write Strings in. I want to do the same thing using swift. So I wrote string in a String file //sample.String "name" = "Sara"; "family" = "Young"; But I don't know how to access these strings in viewControllers. A: There are lot's of was to do this. * *Create a Constants type that has static lets: class Constants { static let name = "Sara" static let family = "Young" } you can use these like: someLabel.text = Constants.name *Declare constants globally Create a swift file named Constants.swift and declare constants: let name = "Sara" let family = "Young" If you use this method, I suggest that you add a prefix to each constant to avoid name conflicts. *Use a dictionary: let constantsDict = [ "name": "Sara", "family": "Young" ] Usage: someLabel.text = constantsDict["name"]! Obviously, the compile won't check whether the key is valid or not if you use this method.
Q: Alternative for strings.xml (It is in android) for IOS There is strings.xml in Android which we can write Strings in. I want to do the same thing using swift. So I wrote string in a String file //sample.String "name" = "Sara"; "family" = "Young"; But I don't know how to access these strings in viewControllers. A: There are lot's of was to do this. * *Create a Constants type that has static lets: class Constants { static let name = "Sara" static let family = "Young" } you can use these like: someLabel.text = Constants.name *Declare constants globally Create a swift file named Constants.swift and declare constants: let name = "Sara" let family = "Young" If you use this method, I suggest that you add a prefix to each constant to avoid name conflicts. *Use a dictionary: let constantsDict = [ "name": "Sara", "family": "Young" ] Usage: someLabel.text = constantsDict["name"]! Obviously, the compile won't check whether the key is valid or not if you use this method.
stackoverflow
{ "language": "en", "length": 168, "provenance": "stackexchange_0000F.jsonl.gz:884702", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603902" }
45baed7eb352f00b7b133fb893d5e44128262f76
Stackoverflow Stackexchange Q: React native react-navigation tabBarIcon does not display I'm having a TabNavigator where I want to have icons at each tab together with a label. However, even though I've tried numerous ways in order to get the icon to appear, nothing happens. // Imports... const StartScreen = TabNavigator({ Home: { screen: HomeTab, navigationOptions: { tabBarLabel: 'Test', tabBarIcon:() => <Icon size={ 20 } name={ 'cogs' } color={ 'red' }/> } }, Calendar: { screen: CalendarTab, navigationOptions: {} } }); StartScreen.navigationOptions = { title: 'TestApp', headerTintColor: '#ffa500', showIcon: true }; export default StartScreen; And yes, I've tried out using the Icon-component so I know that it works. Any tips or guidance would be really helpful, thanks! A: This works const StartScreen = TabNavigator({ Home: { ... }, Calendar: { ... }, }, { tabBarOptions: { showIcon: true }, }); EDIT: I just checked and there is no google material icon named cogs. You should double check your naming :)
Q: React native react-navigation tabBarIcon does not display I'm having a TabNavigator where I want to have icons at each tab together with a label. However, even though I've tried numerous ways in order to get the icon to appear, nothing happens. // Imports... const StartScreen = TabNavigator({ Home: { screen: HomeTab, navigationOptions: { tabBarLabel: 'Test', tabBarIcon:() => <Icon size={ 20 } name={ 'cogs' } color={ 'red' }/> } }, Calendar: { screen: CalendarTab, navigationOptions: {} } }); StartScreen.navigationOptions = { title: 'TestApp', headerTintColor: '#ffa500', showIcon: true }; export default StartScreen; And yes, I've tried out using the Icon-component so I know that it works. Any tips or guidance would be really helpful, thanks! A: This works const StartScreen = TabNavigator({ Home: { ... }, Calendar: { ... }, }, { tabBarOptions: { showIcon: true }, }); EDIT: I just checked and there is no google material icon named cogs. You should double check your naming :) A: I had the same problem with version 1.0.0-beta14. For me, upgrading to 1.0.0-beta15 fixed it A: try to use tabBarOptions = {{ showIcon: true }} I had the same problem , I have to force the display of my icons I set showIcon to true. This previously solved my problem. A: Try adding return before the icon, like this: tabBarIcon:() => return <Icon size={ 20 } name={ 'cogs' } color={ 'red' }/> A: what is the version your react-navigation is??? you can try this navigationOptions: { tabBar: { label: 'Test', icon: ({tintColor}) => (<Icon ... />), }, } it will work in version 1.0.0-beta.7
stackoverflow
{ "language": "en", "length": 262, "provenance": "stackexchange_0000F.jsonl.gz:884705", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603911" }
7f53ffce004e22198f9beb5e6b6375751facbe73
Stackoverflow Stackexchange Q: How to override method when instantiating object in Kotlin? In Java, to override method when instantiating new object we can do this public ActivityTestRule<MainActivity> rule = new ActivityTestRule<MainActivity>( MainActivity.class) { @Override protected void beforeActivityLaunched() { // implement code super.beforeActivityLaunched(); } }; How to do that in Kotlin? I tried this code but it failed to compile. @Rule @JvmField var rule = ActivityTestRule<MainActivity>(MainActivity::class.java) { override fun beforeActivityLaunched() { super.beforeActivityLaunched() } } A: If you want to create anonymous inner class, you should use object. var rule = object : ActivityTestRule<MainActivity>(MainActivity::class.java) { override fun beforeActivityLaunched() { super.beforeActivityLaunched() } } See also Object Expressions and Declarations.
Q: How to override method when instantiating object in Kotlin? In Java, to override method when instantiating new object we can do this public ActivityTestRule<MainActivity> rule = new ActivityTestRule<MainActivity>( MainActivity.class) { @Override protected void beforeActivityLaunched() { // implement code super.beforeActivityLaunched(); } }; How to do that in Kotlin? I tried this code but it failed to compile. @Rule @JvmField var rule = ActivityTestRule<MainActivity>(MainActivity::class.java) { override fun beforeActivityLaunched() { super.beforeActivityLaunched() } } A: If you want to create anonymous inner class, you should use object. var rule = object : ActivityTestRule<MainActivity>(MainActivity::class.java) { override fun beforeActivityLaunched() { super.beforeActivityLaunched() } } See also Object Expressions and Declarations.
stackoverflow
{ "language": "en", "length": 104, "provenance": "stackexchange_0000F.jsonl.gz:884718", "question_score": "39", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603956" }
fe2305427d463d84a633a0defb1b5800944639d0
Stackoverflow Stackexchange Q: 12 MHz crystal speed So I just noticed that my Chinese Arduino Uno has a 12 MHz crystal instead of the original 16Mhz. I made calculations and that turned out to be a quarter millisecond's difference. My questions: * *Does this affect servos or tone(), or any other time sensitive hardware/library? *Can I notify by code that "clock speed is 12,000"? A: The reduced clock speed will affect anything that uses a timer, unless that code can be altered to accommodate the slower clock. Delays, millis(), explicitly coded timer interrupts, etc. And one must remember that you'll get fewer overall instructions per second, so a fast interrupt that barely "fits" at 16MHz might not "fit" at all in the clock cycles available at 12MHz. Hobby-level servos in particular are sensitive to timing...they depend on a pulse in the 0.5-2.0 millisecond range every 20 milliseconds or so. So if your project includes servos as so many hobby projects do, you'll want to be especially cognizant of timings. In gcc-c programming the #define F_CPU = 12000000 directive would alert the compiler/preprocessor to compute delays with the 12 MHz clock in mind. Your toolset may vary.
Q: 12 MHz crystal speed So I just noticed that my Chinese Arduino Uno has a 12 MHz crystal instead of the original 16Mhz. I made calculations and that turned out to be a quarter millisecond's difference. My questions: * *Does this affect servos or tone(), or any other time sensitive hardware/library? *Can I notify by code that "clock speed is 12,000"? A: The reduced clock speed will affect anything that uses a timer, unless that code can be altered to accommodate the slower clock. Delays, millis(), explicitly coded timer interrupts, etc. And one must remember that you'll get fewer overall instructions per second, so a fast interrupt that barely "fits" at 16MHz might not "fit" at all in the clock cycles available at 12MHz. Hobby-level servos in particular are sensitive to timing...they depend on a pulse in the 0.5-2.0 millisecond range every 20 milliseconds or so. So if your project includes servos as so many hobby projects do, you'll want to be especially cognizant of timings. In gcc-c programming the #define F_CPU = 12000000 directive would alert the compiler/preprocessor to compute delays with the 12 MHz clock in mind. Your toolset may vary. A: The 12mhz crystal is NOT the Arduino clock source, it is used for the USB chip (CH340) on these clone boards. The Arduino is clocked as usual at 16mhz by a tiny resonator (probably between C5 and C6). You don't need to make any adjustments.
stackoverflow
{ "language": "en", "length": 240, "provenance": "stackexchange_0000F.jsonl.gz:884725", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44603967" }
ead43ebaf7343e0a9b1b9516d86de500d34d6a61
Stackoverflow Stackexchange Q: Kotlin custom dialog Parameter specified as non-null I got this error : Caused by: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter savedInstanceState When i am trying to inflate a custom dialog in Kotlin , i got the error i wrote above on the super.onCreate line in the dialog. the dialog code is : class Custom_Dialog_Exit_App(var activity: Activity)// TODO Auto-generated constructor stub : Dialog(activity, R.style.full_screen_dialog) { override fun onCreate(savedInstanceState: Bundle) { super.onCreate(savedInstanceState) requestWindowFeature(Window.FEATURE_NO_TITLE) setContentView(R.layout.custom_dialog_exit_app) activity.window!!.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT) initView() } fun initView() { initClicks() } fun initClicks() { } } and the init is : val omer = Custom_Dialog_Exit_App(this@MainActivity) omer.show() Please help A: override fun onCreate(savedInstanceState: Bundle) { Since savedInstanceState can be null the type has to be Bundle?. When you specify that a parameter is not null then kotlin generates a check in all cases. This includes when implementing a Java interface so you need to be careful about making nullable parameters non-null.
Q: Kotlin custom dialog Parameter specified as non-null I got this error : Caused by: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter savedInstanceState When i am trying to inflate a custom dialog in Kotlin , i got the error i wrote above on the super.onCreate line in the dialog. the dialog code is : class Custom_Dialog_Exit_App(var activity: Activity)// TODO Auto-generated constructor stub : Dialog(activity, R.style.full_screen_dialog) { override fun onCreate(savedInstanceState: Bundle) { super.onCreate(savedInstanceState) requestWindowFeature(Window.FEATURE_NO_TITLE) setContentView(R.layout.custom_dialog_exit_app) activity.window!!.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT) initView() } fun initView() { initClicks() } fun initClicks() { } } and the init is : val omer = Custom_Dialog_Exit_App(this@MainActivity) omer.show() Please help A: override fun onCreate(savedInstanceState: Bundle) { Since savedInstanceState can be null the type has to be Bundle?. When you specify that a parameter is not null then kotlin generates a check in all cases. This includes when implementing a Java interface so you need to be careful about making nullable parameters non-null. A: I also meet the error ,I changed the type Bundle to "Bundle?".Then it workd for me. In Kotlin you have to specify if the variable/parameter is null or not. override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) init() } A: change this line activity.window!!.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT) to if(activity.window != null) { activity.window!!.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT) } else { Log.e(TAG, "Window is null"); }
stackoverflow
{ "language": "en", "length": 214, "provenance": "stackexchange_0000F.jsonl.gz:884769", "question_score": "17", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604156" }
e66f17730279a6eb51b7b55078436a2a874646a3
Stackoverflow Stackexchange Q: How to fix the jquery url.indexOf function not defined at jQuery.fn.init.jQuery? I have developed a web application application in MVC using jQuery. Now I am getting this error again and again. I don't know what I am missing right now. Can anyone guide me about this? It throws this error message in browsers' console: jQuery.Deferred exception: url.indexOf is not a function TypeError: url.indexOf is not a function at jQuery.fn.init.jQuery.fn.load (http://localhost:5713/Scripts/jquery-3.1.1.js:9793:13) at HTMLDocument. (http://localhost:5713/Theme/js/main.js:27:12) at mightThrow (http://localhost:5713/Scripts/jquery-3.1.1.js:3570:29) at process (http://localhost:5713/Scripts/jquery-3.1.1.js:3638:12) undefined jQuery.Deferred.exceptionHook @ jquery-3.1.1.js:3846 jquery-3.1.1.js:3855 Uncaught TypeError: url.indexOf is not a function at jQuery.fn.init.jQuery.fn.load (jquery-3.1.1.js:9793) at HTMLDocument. (main.js:27) at mightThrow (jquery-3.1.1.js:3570) at process (jquery-3.1.1.js:3638) A: With Jquery 3.x there were some breaking changes in the Library Jquery Breaking Changes Jquery Removed the load,unload and error event listeners completely, although they were deprecated long back in Jquery 1.8. use .on to register your event.
Q: How to fix the jquery url.indexOf function not defined at jQuery.fn.init.jQuery? I have developed a web application application in MVC using jQuery. Now I am getting this error again and again. I don't know what I am missing right now. Can anyone guide me about this? It throws this error message in browsers' console: jQuery.Deferred exception: url.indexOf is not a function TypeError: url.indexOf is not a function at jQuery.fn.init.jQuery.fn.load (http://localhost:5713/Scripts/jquery-3.1.1.js:9793:13) at HTMLDocument. (http://localhost:5713/Theme/js/main.js:27:12) at mightThrow (http://localhost:5713/Scripts/jquery-3.1.1.js:3570:29) at process (http://localhost:5713/Scripts/jquery-3.1.1.js:3638:12) undefined jQuery.Deferred.exceptionHook @ jquery-3.1.1.js:3846 jquery-3.1.1.js:3855 Uncaught TypeError: url.indexOf is not a function at jQuery.fn.init.jQuery.fn.load (jquery-3.1.1.js:9793) at HTMLDocument. (main.js:27) at mightThrow (jquery-3.1.1.js:3570) at process (jquery-3.1.1.js:3638) A: With Jquery 3.x there were some breaking changes in the Library Jquery Breaking Changes Jquery Removed the load,unload and error event listeners completely, although they were deprecated long back in Jquery 1.8. use .on to register your event.
stackoverflow
{ "language": "en", "length": 143, "provenance": "stackexchange_0000F.jsonl.gz:884772", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604167" }
5b7f0ded15a148884fed15b92a11b16b5ea01ccc
Stackoverflow Stackexchange Q: Tensorflow: How to sensibly merge two neural network layers into one Assume a simple neural net with two inputs Tensorflow: W0 = tf.Variable(tf.zeros([784, 100])) b0 = tf.Variable(tf.zeros([100])) h_a = tf.nn.relu(tf.matmul(x, W0) + b0) W1 = tf.Variable(tf.zeros([100, 10])) b1 = tf.Variable(tf.zeros([10])) h_b = tf.nn.relu(tf.matmul(z, W1) + b1) Question: What would be a good way to merge these two layers into one on the next layer? I mean something like: h_master = tf.nn.relu(tf.matmul(concat(h_a, h_b), W_master) + b_master) However I can't seem to find a suitable function for this. Edit: Please note: if I do this: h_master = tf.nn.tanh(tf.matmul(np.concatenate((h_a,h_b)),W_master) + b_master), I get the following error: ValueError: zero-dimensional arrays cannot be concatenated (My guess is that it happens because the placeholder is seen by the numpy as an empty array, hence h_a and h_b are zero-dimensional.) A: I found a way: h_master = tf.nn.tanh(tf.matmul(tf.concat((h_a, h_b), axis=1), W_master) + b_master) where: W_master = tf.Variable(tf.random_uniform([110, 10], -0.01, 0.01)) b_master = tf.Variable(tf.zeros([10]))
Q: Tensorflow: How to sensibly merge two neural network layers into one Assume a simple neural net with two inputs Tensorflow: W0 = tf.Variable(tf.zeros([784, 100])) b0 = tf.Variable(tf.zeros([100])) h_a = tf.nn.relu(tf.matmul(x, W0) + b0) W1 = tf.Variable(tf.zeros([100, 10])) b1 = tf.Variable(tf.zeros([10])) h_b = tf.nn.relu(tf.matmul(z, W1) + b1) Question: What would be a good way to merge these two layers into one on the next layer? I mean something like: h_master = tf.nn.relu(tf.matmul(concat(h_a, h_b), W_master) + b_master) However I can't seem to find a suitable function for this. Edit: Please note: if I do this: h_master = tf.nn.tanh(tf.matmul(np.concatenate((h_a,h_b)),W_master) + b_master), I get the following error: ValueError: zero-dimensional arrays cannot be concatenated (My guess is that it happens because the placeholder is seen by the numpy as an empty array, hence h_a and h_b are zero-dimensional.) A: I found a way: h_master = tf.nn.tanh(tf.matmul(tf.concat((h_a, h_b), axis=1), W_master) + b_master) where: W_master = tf.Variable(tf.random_uniform([110, 10], -0.01, 0.01)) b_master = tf.Variable(tf.zeros([10]))
stackoverflow
{ "language": "en", "length": 157, "provenance": "stackexchange_0000F.jsonl.gz:884780", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604190" }
41cbf5f52207dec6d5ba5c6e8ab7261e95df07a4
Stackoverflow Stackexchange Q: Save files inside app folder When app save photos, it will be shown in Photos app. But I want to save photos inside app folder and other apps don't able to access it. I get the path to save files as below: let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) How can I do it? Someone told me about using secure storage. Can it be my solution? A: Save an image to the App document folder like this: func saveImageDocumentDirectory(image: UIImage, name:String){ let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(name) let imageData = UIImageJPEGRepresentation(image, 0.5) FileManager.default.createFile(atPath: paths as String, contents: imageData, attributes: nil) } There is no reason to use a secure store (unless you also want to protect data from hacking etc), as the App document folder is only accessable to your App. Also, take a look at this blog: https://iosdevcenters.blogspot.com/2016/04/save-and-get-image-from-document.html
Q: Save files inside app folder When app save photos, it will be shown in Photos app. But I want to save photos inside app folder and other apps don't able to access it. I get the path to save files as below: let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) How can I do it? Someone told me about using secure storage. Can it be my solution? A: Save an image to the App document folder like this: func saveImageDocumentDirectory(image: UIImage, name:String){ let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(name) let imageData = UIImageJPEGRepresentation(image, 0.5) FileManager.default.createFile(atPath: paths as String, contents: imageData, attributes: nil) } There is no reason to use a secure store (unless you also want to protect data from hacking etc), as the App document folder is only accessable to your App. Also, take a look at this blog: https://iosdevcenters.blogspot.com/2016/04/save-and-get-image-from-document.html
stackoverflow
{ "language": "en", "length": 142, "provenance": "stackexchange_0000F.jsonl.gz:884820", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604313" }
2b24ebc1b5317761fe4f2248ac9ed5567b924d6e
Stackoverflow Stackexchange Q: Forex historical data in Python I need solutions to get historical Forex data in Python. For stocks it is easy: import pandas as pd import pandas_datareader as pdr start = dt.date.today() - dt.timedelta(days=30) end = dt.date.today() df = pdr.DataReader('AAPL', 'google', start, end) print(df.head()) I have tried Google, Yahoo, Fred and Oanda. Nothing seems to work. Please give a code example of how to request the data. (In most cases one line should be fine). A: The retail broker feed is always skewed but I don't agree that there is no good historical feed. The industry standard for FX is EBS feed. However, it is an expensive option. The FXMarketAPI offers a feed that closely matches this. It is not affiliated to any broker. The API has a pandas endpoint which helps you pull data. Though there is a limit of 1000 request for free users. you can see an example below. URL = "https://fxmarketapi.com/apipandas" params = {'currency' : 'EURUSD', 'start_date' : '2018-07-02', 'end_date':'2018-12-06', 'api_key':'**************'} response = requests.get("https://fxmarketapi.com/apipandas", params=params) df= pd.read_json(response.text)
Q: Forex historical data in Python I need solutions to get historical Forex data in Python. For stocks it is easy: import pandas as pd import pandas_datareader as pdr start = dt.date.today() - dt.timedelta(days=30) end = dt.date.today() df = pdr.DataReader('AAPL', 'google', start, end) print(df.head()) I have tried Google, Yahoo, Fred and Oanda. Nothing seems to work. Please give a code example of how to request the data. (In most cases one line should be fine). A: The retail broker feed is always skewed but I don't agree that there is no good historical feed. The industry standard for FX is EBS feed. However, it is an expensive option. The FXMarketAPI offers a feed that closely matches this. It is not affiliated to any broker. The API has a pandas endpoint which helps you pull data. Though there is a limit of 1000 request for free users. you can see an example below. URL = "https://fxmarketapi.com/apipandas" params = {'currency' : 'EURUSD', 'start_date' : '2018-07-02', 'end_date':'2018-12-06', 'api_key':'**************'} response = requests.get("https://fxmarketapi.com/apipandas", params=params) df= pd.read_json(response.text) A: Maybe you are not looking hard enough :) A very good looking chap published this a few months ago. Admittedly this is not the best code (first open source project), however, it is currently under development and continuously improving. The next version will be much more efficient and cleaner. fx_collect Designed to store all of FXCM's historical data locally in Mariadb like so. +---------------------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+--------+ | date | bidopen | bidhigh | bidlow | bidclose | askopen | askhigh | asklow | askclose | volume | +---------------------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+--------+ | 2017-04-27 10:01:00 | 17.294000 | 17.296000 | 17.289000 | 17.290000 | 17.340000 | 17.340000 | 17.334000 | 17.335000 | 113 | | 2017-04-27 10:02:00 | 17.290000 | 17.298000 | 17.285000 | 17.295000 | 17.335000 | 17.342000 | 17.330000 | 17.340000 | 114 | | 2017-04-27 10:03:00 | 17.295000 | 17.301000 | 17.289000 | 17.299000 | 17.340000 | 17.347000 | 17.340000 | 17.344000 | 98 | | 2017-04-27 10:04:00 | 17.299000 | 17.300000 | 17.286000 | 17.295000 | 17.344000 | 17.345000 | 17.330000 | 17.340000 | 124 | | 2017-04-27 10:05:00 | 17.295000 | 17.295000 | 17.285000 | 17.292000 | 17.340000 | 17.340000 | 17.330000 | 17.336000 | 130 | | 2017-04-27 10:06:00 | 17.292000 | 17.292000 | 17.279000 | 17.292000 | 17.336000 | 17.336000 | 17.328000 | 17.332000 | 65 | | 2017-04-27 10:07:00 | 17.292000 | 17.304000 | 17.287000 | 17.298000 | 17.332000 | 17.348000 | 17.332000 | 17.345000 | 144 | | 2017-04-27 10:08:00 | 17.298000 | 17.306000 | 17.297000 | 17.302000 | 17.345000 | 17.350000 | 17.343000 | 17.346000 | 96 | | 2017-04-27 10:09:00 | 17.302000 | 17.303000 | 17.294000 | 17.294000 | 17.346000 | 17.346000 | 17.338000 | 17.338000 | 50 | | 2017-04-27 10:10:00 | 17.294000 | 17.296000 | 17.281000 | 17.291000 | 17.338000 | 17.338000 | 17.328000 | 17.333000 | 50 | or if you just want the basic tools to get you started and build your own. python-forexconnect A Demo or Live FXCM account is required to obtain the data. They provide free 10-year historical data, in different timeframes (fxcm). A: FXCM recently released an official python wrapper for forexconnect. There is a support forum: http://www.fxcodebase.com/code/viewforum.php?f=51&sid=e2b414c06f9714c605f117f74d689a9b There is a code snippet from an article about getting history: from forexconnect import fxcorepy, ForexConnect with ForexConnect() as fx: try: fx.login("user_id", "password", "fxcorporate.com/Hosts.jsp", "Demo", session_status_callback=session_status_changed) history = fx.get_history("EUR/USD", "H1", datetime.datetime.strptime("MM.DD.YYYY HH:MM:SS", '%m.%d.%Y %H:%M:%S').replace(tzinfo=datetime.timezone.utc), datetime.datetime.strptime("MM.DD.YYYY HH:MM:SS", '%m.%d.%Y %H:%M:%S').replace(tzinfo=datetime.timezone.utc)) A: There is free tick based historical data from pepperstone in monthly csv format starting from 2009 (visit: https://www.truefx.com/?page=downloads) for most popular pairs, i have wrote python code using selenium to download all csv files(the script will download all csv files into folder name forex): import datetime, time, os from dateutil.relativedelta import relativedelta from selenium import webdriver tmp_dir = os.path.join(os.getcwd(), 'forex') if not os.path.isdir(tmp_dir): os.makedirs(tmp_dir) options = webdriver.ChromeOptions(); options.add_argument("--window-size=1300,900") options.add_experimental_option("prefs", { "download.default_directory": tmp_dir, "download.prompt_for_download": False, "download.directory_upgrade": True, "safebrowsing.enabled": False, "safebrowsing.disable_download_protection": True }) options.add_argument("--disable-gpu") options.add_argument("--disable-extensions") options.add_argument('--disable-logging') options.add_argument('--ignore-certificate-errors') options.add_argument('--ignore-certificate-errors-spki-list') options.add_argument('--no-sandbox') browser = webdriver.Chrome(options=options) pairs = ['AUDJPY', 'AUDNZD', 'AUDUSD', 'CADJPY', 'CHFJPY', 'EURCHF', 'EURGBP', 'EURJPY', 'EURUSD', 'GBPJPY', 'GBPUSD', 'NZDUSD', 'USDCAD', 'USDCHF', 'USDJPY'] for pair in pairs: curr_date = datetime.datetime(2015, 1, 1) while curr_date + relativedelta(months=1) < datetime.datetime.now(): file_name = '{p}-{ym2}.zip'.format(p=pair, ym2=curr_date.strftime('%Y-%m')) url = 'http://www.truefx.com/dev/data/{y}/{ym1}/{p}-{ym2}.zip'.format( y=curr_date.strftime('%Y'), ym1=curr_date.strftime('%B').upper()+'-'+curr_date.strftime('%Y') if curr_date <= datetime.datetime(2017, 3, 1) else curr_date.strftime('%Y-%m'), p=pair, ym2=curr_date.strftime('%Y-%m') ) file_found = False for root, dirs, files in os.walk(tmp_dir): for file in files: if file_name in file: file_found = True if not file_found: time.sleep(5) browser.get (url) file_downloaded = False while not file_downloaded: time.sleep(1) for root, dirs, files in os.walk(tmp_dir): for file in files: if file_name in file and not '.crdownload' in file: file_downloaded = True print(file_name, 'downloaded from', url) curr_date = curr_date + relativedelta(months=1) print('completed') gist source: https://gist.github.com/mamedshahmaliyev/bca9242b7ea6a13b3f76dee7a5aa111a A: Do you just need historical currency values? Try using the forex_python module with the datetime class ( from the datetime module ). I'm using python 3 but I doubt that matters too much. These exchange rates are the 3pm (CET) data from the European Central Bank, since 1999. >>> from datetime import datetime >>> from forex_python.converter import get_rate >>> t = datetime(2001, 10, 18) # the 18th of October, 2001 >>> get_rate("USD", "GBP", t) 0.69233 >>> get_rate("GBP", "USD", t) 1.4444 >>> 1 / 1.4444 # check 0.6923289947382997 >>> t = datetime(2006, 6, 26) # June 26th, 2006 >>> get_rate("GBP", "USD", t) 1.8202 So on 18/10/01, 1 USD == 0.69 GBP, on 26th June, 2006, 1 GBP == 1.82 USD. A: you could use fxcmpy. http://fxcmpy.tpq.io/ here's a quick example : import matplotlib.pyplot as plt import datetime as dt import fxcmpy con = fxcmpy.fxcmpy(config_file='fxcm.cfg') # must optain API Token, see link for details. start = dt.datetime(2018, 7, 6,8,0,0) end = dt.datetime(2018, 7, 7,18,0,0) c = con.get_candles('XAU/USD', period='m1', columns=['bidclose','tickqty'], start=start, end=end ) # Basic plotting of close and volumne data fig, ax = plt.subplots(figsize=(11,8)) ax.plot(c.index,c['bidclose'], lw=1, color='B',label="Close") ax2= ax.twinx() ax2.plot(c.index,c['tickqty'], lw=1, color='G',label="Volume") plot.show() A: from datetime import datetime import MetaTrader5 as mt5 # display data on the MetaTrader 5 package print("MetaTrader5 package author: ",mt5.__author__) print("MetaTrader5 package version: ",mt5.__version__) # import the 'pandas' module for displaying data obtained in the tabular form import pandas as pd pd.set_option('display.max_columns', 500) # number of columns to be displayed pd.set_option('display.width', 1500) # max table width to display # import pytz module for working with time zone import pytz # establish connection to MetaTrader 5 terminal if not mt5.initialize(): print("initialize() failed, error code =",mt5.last_error()) quit() # set time zone to UTC timezone = pytz.timezone("Etc/UTC") # create 'datetime' objects in UTC time zone to avoid the implementation of a local time zone offset utc_from = datetime(2020, 1, 10, tzinfo=timezone) utc_to = datetime(2020, 1, 11, hour = 13, tzinfo=timezone) # get bars from USDJPY M5 within the interval of 2020.01.10 00:00 - 2020.01.11 13:00 in UTC time zone rates = mt5.copy_rates_range("USDJPY", mt5.TIMEFRAME_M5, utc_from, utc_to) # shut down connection to the MetaTrader 5 terminal mt5.shutdown() # display each element of obtained data in a new line print("Display obtained data 'as is'") counter=0 for rate in rates: counter+=1 if counter<=10: print(rate) # create DataFrame out of the obtained data rates_frame = pd.DataFrame(rates) # convert time in seconds into the 'datetime' format rates_frame['time']=pd.to_datetime(rates_frame['time'], unit='s') # display data print("\nDisplay dataframe with data") print(rates_frame.head(10)) A: You can use Tradermade Python SDK which provides daily historical data and represents an aggregated feed from banks and brokers. As its independent data provider, you are unlikely to see skewed rates. You can compare this to your broker feed to check the skew. pip install tradermade import tradermade as tm # set api key tm.set_rest_api_key("api_key") # get timeseries data tm.timeseries(currency='EURUSD', start="2022-04-20",end="2022-04-22",interval="daily",fields=["open", "high", "low","close"]) A: (cit.: ) In most cases one line should be fine ? One cannot be more wrong in this. There is nothing as FOREX historical data. Each FX trading mediator ( Broker ) creates their own trading Terms & Conditions. Even the same Broker may provide several different ( or inconsistent if one wishes ) price-feeds for the same currency-pair trading, so that each "product's" T&C could be met. FOREX eco-system is a decentralised, multi-agent / multi-role, principally distributed, global market. So rather forget to have a SLOC, a magic one-liner to get a universally valid response from some nonexistent divine API. There is none such. Yes, can receive FX data - but each Broker provides a different picture: Yes, one may integrate localhost process against a distinct API service from one particular Broker, for one particular type of trading account ( ref. the respective T&C for detailed context of such a data-feed ). Some Brokers publish their local tick-data, some do not. Some research agencies may help you in some research-motivated efforts and share selected segments of the tick-data for a particular CCY pair. But there is zero global consolidation. It simply has no reason to aggregate such service, that has zero value added. If one's quantitative modelling in-vitro ought make any sense, that model ought be validated with respect to the very same marketplace, where the trading is expected to take place in-vivo. So you need that one particular Market access Mediator's data ( the Broker to ask for this ), where your service is heading to operate in-vivo.
stackoverflow
{ "language": "en", "length": 1518, "provenance": "stackexchange_0000F.jsonl.gz:884861", "question_score": "14", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604440" }
61755eccd6ff56aaa4f43c0dd6aa5f6cdcaa994f
Stackoverflow Stackexchange Q: Change Git Account in VSCode I accidentally entered the credentials form an old github account the first time VSCode tried to connect when synchronizing my changes (the credentials were right for the old account, but i would like to use the new account). Now I cannot find a way to change my account. Already tried uninstall/install, but VSCode keeps remeberming my login. Any ideas how to refresh the given account? A: git config --global --unset credential.helper this will unset the git credentials for your system, Now you can use your new credentials and then enable the cache for git git config --global credential.helper wincred git config --system credential.helper wincred this will again enable the cache for saving git password
Q: Change Git Account in VSCode I accidentally entered the credentials form an old github account the first time VSCode tried to connect when synchronizing my changes (the credentials were right for the old account, but i would like to use the new account). Now I cannot find a way to change my account. Already tried uninstall/install, but VSCode keeps remeberming my login. Any ideas how to refresh the given account? A: git config --global --unset credential.helper this will unset the git credentials for your system, Now you can use your new credentials and then enable the cache for git git config --global credential.helper wincred git config --system credential.helper wincred this will again enable the cache for saving git password
stackoverflow
{ "language": "en", "length": 120, "provenance": "stackexchange_0000F.jsonl.gz:884863", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604446" }
60fb24a9ba03139f8d424bab4b5a293c7e859d57
Stackoverflow Stackexchange Q: Declaring Byte in Kotlin does compile-time error 'The integer literal does not conform to the expected type Byte' As seen another question in 0xFF0000FF An integer literal does not conform to the expected type kotlin.Int I declaring value 0xFF as Byte val b:Byte = 0xFF receiving The integer literal does not conform to the expected type Byte compile error Since I have clue about kotlin.Byte is signed byte How to declaring Byte in Kotlin with 0x00 - 0xFF unsigned byte just like .net Byte b = 0xFF ? . . If you want instant compiler for testing and answer: rextester , try.kotlinlang.org A: Kotlin doesn't automatically convert between number types. If you do val b:Byte = 0xFF.toByte() then it compiles and results in a byte with value -1. If you want to hold the unsigned byte value then you need to store it as a Char, but you will need to convert it to another type to print it as a number: val b = 0xFF.toChar() println(b.toInt())
Q: Declaring Byte in Kotlin does compile-time error 'The integer literal does not conform to the expected type Byte' As seen another question in 0xFF0000FF An integer literal does not conform to the expected type kotlin.Int I declaring value 0xFF as Byte val b:Byte = 0xFF receiving The integer literal does not conform to the expected type Byte compile error Since I have clue about kotlin.Byte is signed byte How to declaring Byte in Kotlin with 0x00 - 0xFF unsigned byte just like .net Byte b = 0xFF ? . . If you want instant compiler for testing and answer: rextester , try.kotlinlang.org A: Kotlin doesn't automatically convert between number types. If you do val b:Byte = 0xFF.toByte() then it compiles and results in a byte with value -1. If you want to hold the unsigned byte value then you need to store it as a Char, but you will need to convert it to another type to print it as a number: val b = 0xFF.toChar() println(b.toInt()) A: Kotlin now supports unsigned integer types: val b: UByte = 255u val c: UByte = 0xFFu
stackoverflow
{ "language": "en", "length": 185, "provenance": "stackexchange_0000F.jsonl.gz:884896", "question_score": "14", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604555" }
813205811d10f6b9cb89d781d136f26a0aac932b
Stackoverflow Stackexchange Q: Unexpected Operator error in shell script This is the shell code I am running: #!bin/bash while true do req=$(curl http://localhost/devcalls/camerarequest.php) if [ "$req" == "1" ] then sudo bash /home/ckoy-admin/HAS_system/camera/cam.sh fi done and this is the error I get when I execute: % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 1 100 1 0 0 56 0 --:--:-- --:--:-- --:--:-- 58 CAM.sh: 7: [: 1: unexpected operator Please let me know what is wrong here. A: if [ "$req" = 1 ] or even better if [ "$req" -eq 1 ] See the syntax and operators in man test.
Q: Unexpected Operator error in shell script This is the shell code I am running: #!bin/bash while true do req=$(curl http://localhost/devcalls/camerarequest.php) if [ "$req" == "1" ] then sudo bash /home/ckoy-admin/HAS_system/camera/cam.sh fi done and this is the error I get when I execute: % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 1 100 1 0 0 56 0 --:--:-- --:--:-- --:--:-- 58 CAM.sh: 7: [: 1: unexpected operator Please let me know what is wrong here. A: if [ "$req" = 1 ] or even better if [ "$req" -eq 1 ] See the syntax and operators in man test. A: To compare INTEGER if [ "$req" -eq 1 ] To compare STRING if [ "$req" = "string" ] A: if [ "expr n%2 -eq 0" ] if [ "expr n%2=0" ] or if [ 'expr n%2=0' ] if [ 'expr n%2 -eq 0' ] you can use any 4 method above mentioned i have tried all other answers but including every thing inside the "" gave me the output A: using bash run.sh instead of sh run.sh worked for me.
stackoverflow
{ "language": "en", "length": 192, "provenance": "stackexchange_0000F.jsonl.gz:884926", "question_score": "14", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604637" }
b3766205b91a117e290bedf536b683233c0ec48c
Stackoverflow Stackexchange Q: Is it possible to use ChaCha20 and Poly1305 in nodejs? I would like to enable ChaCha20 and Poly1305 for TLS in nodejs, but if I run tls.getCiphers() on nodejs v6.10.3 running on Ubuntu 16.04.2 LTS , they are not there. So is this possible without building a custom nodejs on my own? Can I maybe drop in these ciphers by using pure JavaScript? Any information would be highly appreciated. I need this because I am communicating with an IoT-device that does not have support for HW-accelerated AES and using ChaCha20 would probably improve performance quite a bit. A: Answering this myself on 10/19/2017. There is no available support in Node 6, 7, 8 or even in the upcoming 9. The last message seen from TSC (regarding this matter) is a protocol from this meeting: https://github.com/nodejs/TSC/pull/387/files So it looks like there might be support for ChaCha20 and Poly1305 in node.js 10, if they can sort out the FIPS issues for OpenSSL 1.1.
Q: Is it possible to use ChaCha20 and Poly1305 in nodejs? I would like to enable ChaCha20 and Poly1305 for TLS in nodejs, but if I run tls.getCiphers() on nodejs v6.10.3 running on Ubuntu 16.04.2 LTS , they are not there. So is this possible without building a custom nodejs on my own? Can I maybe drop in these ciphers by using pure JavaScript? Any information would be highly appreciated. I need this because I am communicating with an IoT-device that does not have support for HW-accelerated AES and using ChaCha20 would probably improve performance quite a bit. A: Answering this myself on 10/19/2017. There is no available support in Node 6, 7, 8 or even in the upcoming 9. The last message seen from TSC (regarding this matter) is a protocol from this meeting: https://github.com/nodejs/TSC/pull/387/files So it looks like there might be support for ChaCha20 and Poly1305 in node.js 10, if they can sort out the FIPS issues for OpenSSL 1.1.
stackoverflow
{ "language": "en", "length": 162, "provenance": "stackexchange_0000F.jsonl.gz:884937", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604669" }
6e8f3744b55d297402d5f8801868fdccc7bf2f79
Stackoverflow Stackexchange Q: how to test a model that has a foreign key in django? I'm using python 3.5 and Django 1.10 and trying to test my app in tests.py, but an error appeared, it said: ValueError: Cannot assign "1": "NewsLetter.UserID" must be a "User" instance. so how to test a fk value here? here is the code: class NewsletterModelTest(TestCase): @classmethod def setUpTestData(cls): #Set up non-modified objects used by all test methods NewsLetter.objects.create(NewsLetterID=1, Email='test@test.com', Connected=False,UserID=1) class NewsLetter(models.Model): NewsLetterID = models.AutoField(primary_key=True) Email = models.CharField(max_length=255) Connected = models.BooleanField(default=False) UserID = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: db_table = 'NewsLetter' A: For those who land here. To write a test for a model that has a ForeignKey field, you need to create an instance of the model that the ForeignKey points to and then call save() on the ForeignKey instance, before applying it to the creation of your target model for the test. eg. (simplified for brevity) class BookTestCase(TestCase): def test_fields_author_name(self): author = Author(name="Mazuki Sekida") author.save() book = Book(name="Zen Training", author=author) book.save() # assertion example ... record = Book.objects.get(id=1) self.assertEqual(record.author.name, "Mazuki Sekida")
Q: how to test a model that has a foreign key in django? I'm using python 3.5 and Django 1.10 and trying to test my app in tests.py, but an error appeared, it said: ValueError: Cannot assign "1": "NewsLetter.UserID" must be a "User" instance. so how to test a fk value here? here is the code: class NewsletterModelTest(TestCase): @classmethod def setUpTestData(cls): #Set up non-modified objects used by all test methods NewsLetter.objects.create(NewsLetterID=1, Email='test@test.com', Connected=False,UserID=1) class NewsLetter(models.Model): NewsLetterID = models.AutoField(primary_key=True) Email = models.CharField(max_length=255) Connected = models.BooleanField(default=False) UserID = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: db_table = 'NewsLetter' A: For those who land here. To write a test for a model that has a ForeignKey field, you need to create an instance of the model that the ForeignKey points to and then call save() on the ForeignKey instance, before applying it to the creation of your target model for the test. eg. (simplified for brevity) class BookTestCase(TestCase): def test_fields_author_name(self): author = Author(name="Mazuki Sekida") author.save() book = Book(name="Zen Training", author=author) book.save() # assertion example ... record = Book.objects.get(id=1) self.assertEqual(record.author.name, "Mazuki Sekida") A: In your setupTestData method you have to create a User object, and pass it into the NewsLetter object create method. @classmethod def setUpTestData(cls): #Set up non-modified objects used by all test methods user = User.objects.create(<fill params here>) NewsLetter.objects.create(NewsLetterID=1, Email='test@test.com', Connected=False,UserID=user) A: Very similar to what @Arpit Solanki answered, here's what I did: from datetime import date from django.test import TestCase from ..models import Post, Author class PostModelTest(TestCase): @classmethod def setUpTestData(cls): cls.author_ = 'Rambo' cls.author = Author.objects.create(name=cls.author_) cls.post = Post.objects.create( title='A test', author=cls.author, content='This is a test.', date=date(2021, 6, 16)) def test_if_post_has_required_author(self): self.assertEqual(self.post.author.name, self.author_)
stackoverflow
{ "language": "en", "length": 269, "provenance": "stackexchange_0000F.jsonl.gz:884942", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604686" }
573ca308540850d201463f76dd776ad9dfdfbc04
Stackoverflow Stackexchange Q: Pycharm error "Process finished with exit code -1073740791 (0xC0000409)" I have a script testing on Pycharm, script working fine around 3-4 mins, then it says "Python stopped working" and the script is stop running. On the Pycharm output segment, it says Process finished with exit code -1073740791 (0xC0000409). Is this a bug or something wrong with my computer/Pycharm? A: fixed the same problem by upgrading driver for nvidia to 398.36. i was having problems running code using pyqt5 and matplotlib through pycharm but the driver update solved it. was not expecting this to be the issue but it fixed it!
Q: Pycharm error "Process finished with exit code -1073740791 (0xC0000409)" I have a script testing on Pycharm, script working fine around 3-4 mins, then it says "Python stopped working" and the script is stop running. On the Pycharm output segment, it says Process finished with exit code -1073740791 (0xC0000409). Is this a bug or something wrong with my computer/Pycharm? A: fixed the same problem by upgrading driver for nvidia to 398.36. i was having problems running code using pyqt5 and matplotlib through pycharm but the driver update solved it. was not expecting this to be the issue but it fixed it! A: Let me talk for a case with Android emulator- gemu-system_86_64. Have experienced the same error that “Process finished with exit code -1073740791 (0xC0000409)” Have played with bios settings, path to java, memory and disk speed enhansments, rolling back old original card drivers, Nvidia supports - no result. Then I returned all default settings to above ones and: Right clicked on Desktop and selected 'Nvidia control panel' -> 3d settings -> Manage 3d settings. You can see there two tab: global settings. Put all of them as clamp, off or '1'. And in 'programm settings' tab navigated to emulator app and also disabled all what s possible. Now all work just fine. If any in future you can change them for a specific application. Perhaps this will help somebody.
stackoverflow
{ "language": "en", "length": 230, "provenance": "stackexchange_0000F.jsonl.gz:884943", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604689" }
b4a14b8d019b1bfea16172d43a915894f29e1b3e
Stackoverflow Stackexchange Q: using Zxing.Net Mobile for forms does is not recognize I am new in Xamarin.Forms and I want use the bar code scaner by Zxing. however I install the plugin form nuget: 1)ZXing.Net.Mobile for Forms 2) ZXing.Net.Mobile. -> install it since I read somewhere it would help my problem but its not. as far as I understood I need to add this line: to the Android project in main Activity However alotugh I install the packages I am still getting an error of: The type or namespace name 'Andorid' does not exist in the namespace 'ZXing.Net.Mobile.Forms' (are you missing an assembly reference?) ScannerZXing.Android what can I do? (perofrm clean and rebuild for the project didn't help) also would like to add that it is added in the referecnes of the projects. Thanks for the ansewrs. A: In my case the reason was that I installed only ZXing.Net.Mobile.Forms. After installing ZXing.Net.Mobile it`s gone. (two libraries need to be installed)
Q: using Zxing.Net Mobile for forms does is not recognize I am new in Xamarin.Forms and I want use the bar code scaner by Zxing. however I install the plugin form nuget: 1)ZXing.Net.Mobile for Forms 2) ZXing.Net.Mobile. -> install it since I read somewhere it would help my problem but its not. as far as I understood I need to add this line: to the Android project in main Activity However alotugh I install the packages I am still getting an error of: The type or namespace name 'Andorid' does not exist in the namespace 'ZXing.Net.Mobile.Forms' (are you missing an assembly reference?) ScannerZXing.Android what can I do? (perofrm clean and rebuild for the project didn't help) also would like to add that it is added in the referecnes of the projects. Thanks for the ansewrs. A: In my case the reason was that I installed only ZXing.Net.Mobile.Forms. After installing ZXing.Net.Mobile it`s gone. (two libraries need to be installed) A: UPDATE: After trying to run the project I discovered that you actually need both Nuget Packages Previous: Just in case anyone had the same issue as me there are actually two ZXing.Net.Mobile packages both of which by Redth. They both have the exact same description as well unfortunately. I tried the first one which at the time of this writing had the most downloads... however it produced the error as described. By uninstalling and reinstalling the second I resolved the issue:
stackoverflow
{ "language": "en", "length": 240, "provenance": "stackexchange_0000F.jsonl.gz:884945", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604694" }
01a4ee41db58541f0d4b0547ca3ebf0a2a0afb52
Stackoverflow Stackexchange Q: Haskell - exit a program with a specified error code In Haskell, is there a way to exit a program with a specified error code? The resources I've been reading typically point to the error function for exiting a program with an error, but it seems to always terminate the program with an error code of 1. [martin@localhost Haskell]$ cat error.hs main = do error "My English language error message" [martin@localhost Haskell]$ ghc error.hs [1 of 1] Compiling Main ( error.hs, error.o ) Linking error ... [martin@localhost Haskell]$ ./error error: My English language error message [martin@localhost Haskell]$ echo $? 1 A: An alternative that allows an error message only is die import System.Exit tests = ... -- some value from the program testsResult = ... -- Bool value overall status main :: IO () main = do if testsResult then print "Tests passed" else die (show tests) The accepted answer allows setting the exit error code though, so it's closer to the exact phrasing of the question.
Q: Haskell - exit a program with a specified error code In Haskell, is there a way to exit a program with a specified error code? The resources I've been reading typically point to the error function for exiting a program with an error, but it seems to always terminate the program with an error code of 1. [martin@localhost Haskell]$ cat error.hs main = do error "My English language error message" [martin@localhost Haskell]$ ghc error.hs [1 of 1] Compiling Main ( error.hs, error.o ) Linking error ... [martin@localhost Haskell]$ ./error error: My English language error message [martin@localhost Haskell]$ echo $? 1 A: An alternative that allows an error message only is die import System.Exit tests = ... -- some value from the program testsResult = ... -- Bool value overall status main :: IO () main = do if testsResult then print "Tests passed" else die (show tests) The accepted answer allows setting the exit error code though, so it's closer to the exact phrasing of the question. A: Use exitWith from System.Exit: main = exitWith (ExitFailure 2) I would add some helpers for convenience: exitWithErrorMessage :: String -> ExitCode -> IO a exitWithErrorMessage str e = hPutStrLn stderr str >> exitWith e exitResourceMissing :: IO a exitResourceMissing = exitWithErrorMessage "Resource missing" (ExitFailure 2)
stackoverflow
{ "language": "en", "length": 214, "provenance": "stackexchange_0000F.jsonl.gz:884949", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604701" }
ed8c99322ac125fb3b1c19a23e3e08e7d519c36d
Stackoverflow Stackexchange Q: Error:Minifying the variant used for tests is not supported when using Jack I am getting this error in Android studio when i enable jackOptions in build.gradle Error:Minifying the variant used for tests is not supported when using Jack android { ... defaultConfig { ... jackOptions { enabled true } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } A: The Jack toolchain is deprecated. Use the new gradle plugin, and you'll also get rid of this error. Follow this tutorial to migrate your app.
Q: Error:Minifying the variant used for tests is not supported when using Jack I am getting this error in Android studio when i enable jackOptions in build.gradle Error:Minifying the variant used for tests is not supported when using Jack android { ... defaultConfig { ... jackOptions { enabled true } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } A: The Jack toolchain is deprecated. Use the new gradle plugin, and you'll also get rid of this error. Follow this tutorial to migrate your app. A: jackOptions is not required longer. Java 8 is supported on Android Studio 3.0 Jack is no longer supported, and you should first disable Jack to use the improved Java 8 support built into the default toolchain. Reference
stackoverflow
{ "language": "en", "length": 123, "provenance": "stackexchange_0000F.jsonl.gz:884969", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604749" }
2b9778ca6223fb97a02d2dc1ac4a8d7991dd7a3b
Stackoverflow Stackexchange Q: Why does apt-get install r-base install 3.2.3 instead of 3.4.0 in R? I am trying to install the latest version of R (3.4.0) due to some incompatibility issues with dowloading of a package called "Slam". I have downloaded the tar.gz file of 3.4.0 but there are some issues with the make file for installation. I have uninstalled the r-base of 3.2.3. Now when I'm installing R again, I get the same version instead of the upgrade version. I even ran the sudo apt-get update command but in vain. A: you need to install from the CRAN repos not the ubuntu ones. add the key, then the repository, update and the apt-get sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9 sudo add-apt-repository 'deb [arch=amd64,i386] https://cran.rstudio.com/bin/linux/ubuntu xenial/' sudo apt-get update sudo apt-get install r-base
Q: Why does apt-get install r-base install 3.2.3 instead of 3.4.0 in R? I am trying to install the latest version of R (3.4.0) due to some incompatibility issues with dowloading of a package called "Slam". I have downloaded the tar.gz file of 3.4.0 but there are some issues with the make file for installation. I have uninstalled the r-base of 3.2.3. Now when I'm installing R again, I get the same version instead of the upgrade version. I even ran the sudo apt-get update command but in vain. A: you need to install from the CRAN repos not the ubuntu ones. add the key, then the repository, update and the apt-get sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9 sudo add-apt-repository 'deb [arch=amd64,i386] https://cran.rstudio.com/bin/linux/ubuntu xenial/' sudo apt-get update sudo apt-get install r-base
stackoverflow
{ "language": "en", "length": 132, "provenance": "stackexchange_0000F.jsonl.gz:884975", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604757" }
07d12b6ea5b16fd9124ff1ac938850c9dbd6aeb5
Stackoverflow Stackexchange Q: Android Studio 3 - It is possible to take a screenshot or record screen? In latest version of Android Studio android monitor was changed to android profiler. Android profiler it's great but I don't see any option to take a screenshots or record device screen. So my question is where are now capturing options? A: You can still access them through the LogCat tab.
Q: Android Studio 3 - It is possible to take a screenshot or record screen? In latest version of Android Studio android monitor was changed to android profiler. Android profiler it's great but I don't see any option to take a screenshots or record device screen. So my question is where are now capturing options? A: You can still access them through the LogCat tab. A: It's still in LogCat but below. You can click a ">>" button to reveal a list of hidden buttons. A: If Android Studio's recording video feature is not available and you are a MacOS user you can use QuickTime Player File -> New Screen Recording To make screenshots Command + Shift + 4
stackoverflow
{ "language": "en", "length": 119, "provenance": "stackexchange_0000F.jsonl.gz:884985", "question_score": "24", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604791" }
fc15410f60a1d8cf0e0713f200d5790103de9283
Stackoverflow Stackexchange Q: Searching for words in string I'm trying to make a function that finds the string that contains all words from an array. I have tried this: function multiSearchOr(text, searchWords){ var searchExp = new RegExp(searchWords.join("|"),"gi"); return (searchExp.test(text))?"Found!":"Not found!"; } alert(multiSearchOr("Hello my name sam", ["Hello", "is"])) But this only alert "Found" when one of the words have been found. I need it to alert me when all the words are in the string. An example: var sentence = "I love cake" var words = ["I", "cake"]; I want the application to alert me when it finds all of the words from the array in the string sentence. Not when it only found one of the words. A: If you're interested in using only a single regular expression, then you need to use a positive lookahead when constructing your expression. It will look something like that: '(?=\\b' + word + '\\b)' Given this construction, you can then create your regular expression and test for the match: function multiSearchOr(text, searchWords){ var regex = searchWords .map(word => "(?=.*\\b" + word + "\\b)") .join(''); var searchExp = new RegExp(regex, "gi"); return (searchExp.test(text))? "Found!" : "Not found!"; }
Q: Searching for words in string I'm trying to make a function that finds the string that contains all words from an array. I have tried this: function multiSearchOr(text, searchWords){ var searchExp = new RegExp(searchWords.join("|"),"gi"); return (searchExp.test(text))?"Found!":"Not found!"; } alert(multiSearchOr("Hello my name sam", ["Hello", "is"])) But this only alert "Found" when one of the words have been found. I need it to alert me when all the words are in the string. An example: var sentence = "I love cake" var words = ["I", "cake"]; I want the application to alert me when it finds all of the words from the array in the string sentence. Not when it only found one of the words. A: If you're interested in using only a single regular expression, then you need to use a positive lookahead when constructing your expression. It will look something like that: '(?=\\b' + word + '\\b)' Given this construction, you can then create your regular expression and test for the match: function multiSearchOr(text, searchWords){ var regex = searchWords .map(word => "(?=.*\\b" + word + "\\b)") .join(''); var searchExp = new RegExp(regex, "gi"); return (searchExp.test(text))? "Found!" : "Not found!"; } A: Here's a working example. You simply need to iterate over the array and compare if the words are present in the string or not using indexOf(). if it is not equal then alert Not found otherwise alert Found. function multiSearchOr(text, searchWords){ for(var i=0; i<searchWords.length; i++) { if(text.indexOf(searchWords[i]) == -1) return('Not Found!'); } return('Found!'); } alert(multiSearchOr("Hello my name sam", ["Hello", "is"])); A: Is this what are you looking for ? In this way, you can use more complex sentences that contain non-alphanumeric characters. var sentence = "Hello, how are you ?" var test1 = ["Hello", "how", "test"]; var test2 = ["hello", "How"]; function multiSearchOr(text, searchWords){ if (text && searchWords) { var filteredText = text.match(/[^_\W]+/g); if (filteredText !== null) { var lowerCaseText = filteredText.map(function(word) { return word.toLowerCase(); }); for (var i = 0; i < searchWords.length; i++) { if (lowerCaseText.indexOf(searchWords[i].toLowerCase()) === -1) { return "Not found!"; } } return "Found!" } return "Error: the text provided doesn't contain any words!" } return "Error: Props are missing"; } console.log(multiSearchOr(sentence, test1)); console.log(multiSearchOr(sentence, test2)); A: if all(word in text for word in searchWords): print('found all') if any(word in text for word in searchWords): print('found at least one') all() if you want that all the word in the list searchWords are in the text any() if it's enough that one list word is in the text A: Here is a version that will split the sentense you pass and check each word const matchAllEntries = (arr, target) => target.every(v => arr.includes(v)); const arr = ['lorem', 'ipsum', 'dolor']; const strs = ['lorem blue dolor sky ipsum', 'sky loremdoloripsum blue', 'lorem dolor ipsum']; strs.forEach(str => { // split on non alphabet and numbers (includes whitespace and puntuation) parts = str.split(/\W/); console.log(matchAllEntries(arr, parts)); })
stackoverflow
{ "language": "en", "length": 478, "provenance": "stackexchange_0000F.jsonl.gz:884986", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604794" }