qid
int64
1
74.7M
question
stringlengths
1
70k
date
stringlengths
10
10
metadata
sequencelengths
3
3
response_j
stringlengths
0
115k
response_k
stringlengths
0
60.5k
score_j
int64
0
14
score_k
int64
-1
10
47,539,905
I am very new to CSS and javascript, so take it easy on me. I am trying to remove the class `disable-stream` from each of the div elements under the div class="stream-notifications". (See image, below) I have tried the following in Tampermonkey, but it doesn't seem to work: ``` (function() { 'use strict'; disable-stream.classList.remove("disable-stream");})(); ``` [![screen shot of page structure](https://i.stack.imgur.com/FNFGz.jpg)](https://i.stack.imgur.com/FNFGz.jpg)
2017/11/28
[ "https://Stackoverflow.com/questions/47539905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6632302/" ]
``` var divs =document.getElementsByClassName("stream-notifications"); divs=Array.from(divs); divs.forEach(function(div){ div.classList.remove('disable-stream'); }); ```
Use something like this using jQuery ``` $(".disable-stream div").removeClass("disable-stream"); ``` [Plunker demo](https://plnkr.co/edit/hP4IyF64trUEjTmZpwBK?p=preview)
2
0
47,539,905
I am very new to CSS and javascript, so take it easy on me. I am trying to remove the class `disable-stream` from each of the div elements under the div class="stream-notifications". (See image, below) I have tried the following in Tampermonkey, but it doesn't seem to work: ``` (function() { 'use strict'; disable-stream.classList.remove("disable-stream");})(); ``` [![screen shot of page structure](https://i.stack.imgur.com/FNFGz.jpg)](https://i.stack.imgur.com/FNFGz.jpg)
2017/11/28
[ "https://Stackoverflow.com/questions/47539905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6632302/" ]
That looks to be an AJAX-driven web page, so you need to use AJAX-aware techniques to deal with it. EG [waitForKeyElements](https://gist.github.com/2625891), or `MutationObserver`, or similar. Here's **a complete script** that should work: ``` // ==UserScript== // @name _Remove a select class from nodes // @match *://app.hubspot.com/reports-dashboard/* // @match *://app.hubspot.com/sales-notifications-embedded/* // @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js // @require https://gist.github.com/raw/2625891/waitForKeyElements.js // @grant GM_addStyle // ==/UserScript== //- The @grant directive is needed to restore the proper sandbox. console.log ("Do you see this?"); waitForKeyElements (".disable-stream", removeDSclass); function removeDSclass (jNode) { console.log ("Cleaned node: ", jNode); jNode.removeClass ("disable-stream"); } ``` --- Note that there are two `@match` statements because the nodes, that the OP cared about, turned out to be in an iframe.
Use something like this using jQuery ``` $(".disable-stream div").removeClass("disable-stream"); ``` [Plunker demo](https://plnkr.co/edit/hP4IyF64trUEjTmZpwBK?p=preview)
3
0
47,539,905
I am very new to CSS and javascript, so take it easy on me. I am trying to remove the class `disable-stream` from each of the div elements under the div class="stream-notifications". (See image, below) I have tried the following in Tampermonkey, but it doesn't seem to work: ``` (function() { 'use strict'; disable-stream.classList.remove("disable-stream");})(); ``` [![screen shot of page structure](https://i.stack.imgur.com/FNFGz.jpg)](https://i.stack.imgur.com/FNFGz.jpg)
2017/11/28
[ "https://Stackoverflow.com/questions/47539905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6632302/" ]
That looks to be an AJAX-driven web page, so you need to use AJAX-aware techniques to deal with it. EG [waitForKeyElements](https://gist.github.com/2625891), or `MutationObserver`, or similar. Here's **a complete script** that should work: ``` // ==UserScript== // @name _Remove a select class from nodes // @match *://app.hubspot.com/reports-dashboard/* // @match *://app.hubspot.com/sales-notifications-embedded/* // @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js // @require https://gist.github.com/raw/2625891/waitForKeyElements.js // @grant GM_addStyle // ==/UserScript== //- The @grant directive is needed to restore the proper sandbox. console.log ("Do you see this?"); waitForKeyElements (".disable-stream", removeDSclass); function removeDSclass (jNode) { console.log ("Cleaned node: ", jNode); jNode.removeClass ("disable-stream"); } ``` --- Note that there are two `@match` statements because the nodes, that the OP cared about, turned out to be in an iframe.
``` var divs =document.getElementsByClassName("stream-notifications"); divs=Array.from(divs); divs.forEach(function(div){ div.classList.remove('disable-stream'); }); ```
3
2
13,769,762
Our UX asks for a button to start multi-choice mode. this would do the same thing as long-pressing on an item, but would have nothing selected initially. What I'm seeing in the code is that I cannot enter multi-choice mode mode unless I have something selected, and if I unselect that item, multi-choice mode exits (contextual action bar closes). I've also tried this in other apps (gmail), and it works the same way. Is there a way to be in multi-select mode, with no items selected?
2012/12/07
[ "https://Stackoverflow.com/questions/13769762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337455/" ]
It's very hacky, but I've done this by having an item selected, but making it look like it's not selected, by making the background temporarily transparent. When an item is then selected by the user, the secretly-selected item is deselected and the background restored to normal. Or, if it's the secretly-selected item which is selected (thus deselecting it), I reselect it, then set a boolean to stop it happening again. I also had to use a counter in onItemCheckedStateChanged, as I was changing the checked state of the secret item from within that callback, resulting in a loop. Probably not an ideal solution for all cases, but I don't think there's another way to do it at the moment, since [AbsListView can't easily be extended.](https://stackoverflow.com/questions/9637759/is-it-possible-to-extend-abslistview-to-make-new-listview-implementations) Edit: if the screen orientation changes while the selected state of the selected item is hidden, it will suddenly be shown as being selected, so you have to make sure to save the fact that it should be hidden, and restore it after the listview is recreated. I had to use the View post() method to ensure the restoration happened after the listview had finished redrawing all its child items after the configuration change. Edit: another potential issue is if the user tries to carry out an action while there are supposedly no items selected. As far as the application knows there *is* an item selected so it will carry out the action on that item, unless you make sure it doesn't.
You just have to use : ``` listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); ```
2
0
13,769,762
Our UX asks for a button to start multi-choice mode. this would do the same thing as long-pressing on an item, but would have nothing selected initially. What I'm seeing in the code is that I cannot enter multi-choice mode mode unless I have something selected, and if I unselect that item, multi-choice mode exits (contextual action bar closes). I've also tried this in other apps (gmail), and it works the same way. Is there a way to be in multi-select mode, with no items selected?
2012/12/07
[ "https://Stackoverflow.com/questions/13769762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337455/" ]
Just call: ``` mListView.setItemChecked(-1, true); ``` ListView's actionMode will be started without selecting any list element. Make sure you've properly set your ListView before call: ``` mListView.setMultiChoiceModeListener( ... ) mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); or mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); ```
You just have to use : ``` listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); ```
1
0
13,769,762
Our UX asks for a button to start multi-choice mode. this would do the same thing as long-pressing on an item, but would have nothing selected initially. What I'm seeing in the code is that I cannot enter multi-choice mode mode unless I have something selected, and if I unselect that item, multi-choice mode exits (contextual action bar closes). I've also tried this in other apps (gmail), and it works the same way. Is there a way to be in multi-select mode, with no items selected?
2012/12/07
[ "https://Stackoverflow.com/questions/13769762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337455/" ]
It's very hacky, but I've done this by having an item selected, but making it look like it's not selected, by making the background temporarily transparent. When an item is then selected by the user, the secretly-selected item is deselected and the background restored to normal. Or, if it's the secretly-selected item which is selected (thus deselecting it), I reselect it, then set a boolean to stop it happening again. I also had to use a counter in onItemCheckedStateChanged, as I was changing the checked state of the secret item from within that callback, resulting in a loop. Probably not an ideal solution for all cases, but I don't think there's another way to do it at the moment, since [AbsListView can't easily be extended.](https://stackoverflow.com/questions/9637759/is-it-possible-to-extend-abslistview-to-make-new-listview-implementations) Edit: if the screen orientation changes while the selected state of the selected item is hidden, it will suddenly be shown as being selected, so you have to make sure to save the fact that it should be hidden, and restore it after the listview is recreated. I had to use the View post() method to ensure the restoration happened after the listview had finished redrawing all its child items after the configuration change. Edit: another potential issue is if the user tries to carry out an action while there are supposedly no items selected. As far as the application knows there *is* an item selected so it will carry out the action on that item, unless you make sure it doesn't.
If you want to change the action bar, call this from your activity: > startActionMode(new ActionMode.Callback { > > > > ``` > @Override > public boolean onCreateActionMode(ActionMode mode, Menu menu) { > return false; > } > > @Override > public boolean onPrepareActionMode(ActionMode mode, Menu menu) { > return false; > } > > @Override > public void onDestroyActionMode(ActionMode mode) { > > } > > @Override > public boolean onActionItemClicked(ActionMode mode, MenuItem item) { > return false; > } > }); > > ```
2
0
13,769,762
Our UX asks for a button to start multi-choice mode. this would do the same thing as long-pressing on an item, but would have nothing selected initially. What I'm seeing in the code is that I cannot enter multi-choice mode mode unless I have something selected, and if I unselect that item, multi-choice mode exits (contextual action bar closes). I've also tried this in other apps (gmail), and it works the same way. Is there a way to be in multi-select mode, with no items selected?
2012/12/07
[ "https://Stackoverflow.com/questions/13769762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337455/" ]
Just call: ``` mListView.setItemChecked(-1, true); ``` ListView's actionMode will be started without selecting any list element. Make sure you've properly set your ListView before call: ``` mListView.setMultiChoiceModeListener( ... ) mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); or mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); ```
If you want to change the action bar, call this from your activity: > startActionMode(new ActionMode.Callback { > > > > ``` > @Override > public boolean onCreateActionMode(ActionMode mode, Menu menu) { > return false; > } > > @Override > public boolean onPrepareActionMode(ActionMode mode, Menu menu) { > return false; > } > > @Override > public void onDestroyActionMode(ActionMode mode) { > > } > > @Override > public boolean onActionItemClicked(ActionMode mode, MenuItem item) { > return false; > } > }); > > ```
1
0
13,769,762
Our UX asks for a button to start multi-choice mode. this would do the same thing as long-pressing on an item, but would have nothing selected initially. What I'm seeing in the code is that I cannot enter multi-choice mode mode unless I have something selected, and if I unselect that item, multi-choice mode exits (contextual action bar closes). I've also tried this in other apps (gmail), and it works the same way. Is there a way to be in multi-select mode, with no items selected?
2012/12/07
[ "https://Stackoverflow.com/questions/13769762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337455/" ]
It's very hacky, but I've done this by having an item selected, but making it look like it's not selected, by making the background temporarily transparent. When an item is then selected by the user, the secretly-selected item is deselected and the background restored to normal. Or, if it's the secretly-selected item which is selected (thus deselecting it), I reselect it, then set a boolean to stop it happening again. I also had to use a counter in onItemCheckedStateChanged, as I was changing the checked state of the secret item from within that callback, resulting in a loop. Probably not an ideal solution for all cases, but I don't think there's another way to do it at the moment, since [AbsListView can't easily be extended.](https://stackoverflow.com/questions/9637759/is-it-possible-to-extend-abslistview-to-make-new-listview-implementations) Edit: if the screen orientation changes while the selected state of the selected item is hidden, it will suddenly be shown as being selected, so you have to make sure to save the fact that it should be hidden, and restore it after the listview is recreated. I had to use the View post() method to ensure the restoration happened after the listview had finished redrawing all its child items after the configuration change. Edit: another potential issue is if the user tries to carry out an action while there are supposedly no items selected. As far as the application knows there *is* an item selected so it will carry out the action on that item, unless you make sure it doesn't.
Just call: ``` mListView.setItemChecked(-1, true); ``` ListView's actionMode will be started without selecting any list element. Make sure you've properly set your ListView before call: ``` mListView.setMultiChoiceModeListener( ... ) mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); or mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); ```
2
1
62,287,390
I am working on a web application at the moment that has a an api at the top level domain (mydomain.com) and an SPA at subdomain (spa.mydomain.com). In the SPA I have added, `axios.defaults.withCredentials = true` To login in I run the following code, ``` axios.get('/sanctum/csrf-cookie').then(response => { axios.post('/login', {email: this.email, password: this.password}).then(response => { this.$router.push({ name: 'Account' }); }); }); ``` The get request responds with a 204 as expected and the post request to login responds successfully too, at this point I get redirected and another GET is sent to /api/users/me at this point the server responds with a 401 unauthorized response. I would have assumed that seen as though I can login everything would be working as expected but sadly not, the key bits of my `.env` file from my api are below to see if I am missing anything obvious. `SESSION_DRIVER=cookie SESSION_LIFETIME=120 SESSION_DOMAIN=.mydomain.com SANCTUM_STATEFUL_DOMAINS=spa.mydomain.com` My request headers look like this, `Accept: application/json, text/plain, */* Accept-Encoding: gzip, deflate Accept-Language: en-GB,en-US;q=0.9,en;q=0.8 Connection: keep-alive Cookie: XSRF-TOKEN=eyJpdiI6InZDRTAvenNlRGhwdVNzY2p5VUFQeFE9PSIsInZhbHVlIjoiVzBLT0wyNTI2Vk5la3hiQ1M1TXpRU2pRQ3pXeGk1Nkc1eW5QN0F5ZjNFUmdIVmlaWGNqdXZVcU9UYUNVTzhXbiIsIm1hYyI6IjJmMmIyMjc4MzNkODA4ZDdlZjRhZTJhM2RlMTQ5NDg1MWM2MjdhMzdkMTFjZGNiMzdkMDM3YjNjNzM1ZmY5NjAifQ%3D%3D; at_home_club_session=eyJpdiI6ImxLYjlRNHplcGh1d2RVSEtnakxJNmc9PSIsInZhbHVlIjoiWnBjN0xheWlaNDdDUWZnZGxMUzlsM0VzbjZaZVdUSTBZL0R1WXRTTGp5emY0S2NodGZNN25hQmF1ajYzZzU3MiIsIm1hYyI6ImNlMWRmNWJhYmE1ODU3MzM1Y2Q4ZDI0MDIzNTU1OWQ4MDE3MGRiNTJjY2NjNmFmZDU5YzhjZTM4NGJlOGU5ZTkifQ%3D%3D; XSRF-TOKEN=eyJpdiI6ImhadVF0eHlEY3l4RWtnZk45MmVxZ2c9PSIsInZhbHVlIjoiRCs4QkNMRjBodzJKaFIvRVQwZUZlM3BzYmlJMGp0Y0E5RXdHdkYrblVzSzNPQTJZbE42ZlhlYllmWlg2a0ltMSIsIm1hYyI6IjA1NWU0ZjFiNDFjN2VkNjNiMzJiNjFlNTFiMjBmNWE3MzA4Yzk1YmJiNzdmZGUyZmZhNjcwYmQxZTYxYTBmY2QifQ%3D%3D; at_home_club_session=eyJpdiI6IjZxWXZSYjdGWXU5SHBKSFFRdGQycWc9PSIsInZhbHVlIjoiU3RyTDdoNGJBUW93ck9CTmFjVFpjRTRxMVVwQzZmcjJJTXJUNFU0UUZVcnkzcWdBbzZxWjNvTWZrZmFuMXBrbSIsIm1hYyI6IjFkOTFiNDg5YmZjYmE0NGZiZDg3ZGY5ZDQyMDg2MGZjNzFlMmI0OTA1OGY2MzdkMmFmOGI0ZTlkOTE4ZDM0NWUifQ%3D%3D; XLtgHBp79G2IlVzFPoHViq4wcAV1TMveovlNr1V4=eyJpdiI6ImZiRThmNUpBb3N0Z21MVHJRMVIvRFE9PSIsInZhbHVlIjoiVDV5S2tDOTFNcElqc1NINVpsdi9Ibk04cFVSekkvSytvY01YUDFIbENhZkV3VnVTaHpOTjlwUjROVnFlMk96SWgwUlByZFU3MlA0YVhTelFDaEVTdndkQnczUFZ3bXJlVHpUTkZwb3Z2d1Z1VUI1STJkeG1ZMm13N0h3S282V2l3MmlvUmFrQXY4SXFFaHcrNjBucktJcmRmSk81UUtFcUFlOCtNaUZHelJpRmxkY2gyZVFOWWRUWTdqZ2NFYi85WlVBeFJ2bm5xU05IU3F1aE0ybXlzUnltRUh6eG1qZklaVW9GSDRsU3RMWmRrL242WjJ5VFZVa3dDTWtIN051SThUa0FjZDFsSXp6SmNSTWFWTDl5dk5IczFKcEpSWS9qZUZiMGVENTdKcjVrTlBITWRjV2dUY1RmcElNL0FUSzQxS0JGZFBzUWVha3ZIOVh6YWpTZnNZa202bHB1akQvakVHWTRZU1Z1WWFZZmxIcDN2bDZrek9JRHkybE01b3BlTWErYmhKK2xQN0FmTzhZS3M3bTBHUVJaSzhIdzBGWlc4Vjd1QVJCSFovZz0iLCJtYWMiOiI2ZWZlYWIwYzhlZjMyZjlkNTI0ZWJmYjFhMzExYTIxZTkyNDM1ODM3ODg1YjlmM2ZiOTVhMTMwYTAwYjk4NjhiIn0%3D Host: mydomain.com Origin: http://spa.mydomain.com Referer: http://spa.mydomain.info/account User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 X-XSRF-TOKEN: eyJpdiI6ImhadVF0eHlEY3l4RWtnZk45MmVxZ2c9PSIsInZhbHVlIjoiRCs4QkNMRjBodzJKaFIvRVQwZUZlM3BzYmlJMGp0Y0E5RXdHdkYrblVzSzNPQTJZbE42ZlhlYllmWlg2a0ltMSIsIm1hYyI6IjA1NWU0ZjFiNDFjN2VkNjNiMzJiNjFlNTFiMjBmNWE3MzA4Yzk1YmJiNzdmZGUyZmZhNjcwYmQxZTYxYTBmY2QifQ==` and my cors, ``` 'paths' => ['api/*', 'sanctum/csrf-cookie', 'login'], 'allowed_methods' => ['*'], 'allowed_origins' => ['*'], 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => true, ``` Everything works perfectly on localhost.
2020/06/09
[ "https://Stackoverflow.com/questions/62287390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57872/" ]
Turns out when our Azure DevOps instance was first set up, all our users set up Microsoft accounts with their company emails. Later when we finally stood up Azure AD but before we connected it to DevOps we added a new project and set the permissions for a few existing employees. For some reason the user permissions on the new DevOps project were listed as "aaduser" type instead of the standard "user" type (ms account) that all the users in other projects in DevOps had. In other words duplicate UPNs but different accounts (but sort of the same). What's weird is that DevOps managed to find the Azure AD user account before we even connected the two together services together. We removed the offending users with the standard "user" type and re-added them so they were now all listed as "aaduser." We were then able to connect Azure AD. To be clear, this was all done on the DevOps side and had nothing to do with AD. Not sure why it was finding Azure AD users when we weren't even connected to it yet.
It sounds like you have multiple users in your azure ad tenant with the same UPN. maybe you created a cloud account with the same UPN before sync'ing the on premise with azure ad connect? or something else of that nature. try to go to graph explorer <https://developer.microsoft.com/en-us/graph/graph-explorer> log in with a azure ad admin account and type in a query like this ``` https://graph.microsoft.com/v1.0/users?$filter=startswith(UserPrincipalName,'##UPNHavingIssues##') ``` That should get you users with a UPN of whatever it having problems. There should only be entry, but if there are multiple, then that's where the problem is. The other option is to remove the user having issues from devops completely, then try to connect, then re-add him. because when you try to connect devops to an azure ad domain it will try to match the UPNs of users in your devops with users in your tenant.
3
1
62,287,390
I am working on a web application at the moment that has a an api at the top level domain (mydomain.com) and an SPA at subdomain (spa.mydomain.com). In the SPA I have added, `axios.defaults.withCredentials = true` To login in I run the following code, ``` axios.get('/sanctum/csrf-cookie').then(response => { axios.post('/login', {email: this.email, password: this.password}).then(response => { this.$router.push({ name: 'Account' }); }); }); ``` The get request responds with a 204 as expected and the post request to login responds successfully too, at this point I get redirected and another GET is sent to /api/users/me at this point the server responds with a 401 unauthorized response. I would have assumed that seen as though I can login everything would be working as expected but sadly not, the key bits of my `.env` file from my api are below to see if I am missing anything obvious. `SESSION_DRIVER=cookie SESSION_LIFETIME=120 SESSION_DOMAIN=.mydomain.com SANCTUM_STATEFUL_DOMAINS=spa.mydomain.com` My request headers look like this, `Accept: application/json, text/plain, */* Accept-Encoding: gzip, deflate Accept-Language: en-GB,en-US;q=0.9,en;q=0.8 Connection: keep-alive Cookie: XSRF-TOKEN=eyJpdiI6InZDRTAvenNlRGhwdVNzY2p5VUFQeFE9PSIsInZhbHVlIjoiVzBLT0wyNTI2Vk5la3hiQ1M1TXpRU2pRQ3pXeGk1Nkc1eW5QN0F5ZjNFUmdIVmlaWGNqdXZVcU9UYUNVTzhXbiIsIm1hYyI6IjJmMmIyMjc4MzNkODA4ZDdlZjRhZTJhM2RlMTQ5NDg1MWM2MjdhMzdkMTFjZGNiMzdkMDM3YjNjNzM1ZmY5NjAifQ%3D%3D; at_home_club_session=eyJpdiI6ImxLYjlRNHplcGh1d2RVSEtnakxJNmc9PSIsInZhbHVlIjoiWnBjN0xheWlaNDdDUWZnZGxMUzlsM0VzbjZaZVdUSTBZL0R1WXRTTGp5emY0S2NodGZNN25hQmF1ajYzZzU3MiIsIm1hYyI6ImNlMWRmNWJhYmE1ODU3MzM1Y2Q4ZDI0MDIzNTU1OWQ4MDE3MGRiNTJjY2NjNmFmZDU5YzhjZTM4NGJlOGU5ZTkifQ%3D%3D; XSRF-TOKEN=eyJpdiI6ImhadVF0eHlEY3l4RWtnZk45MmVxZ2c9PSIsInZhbHVlIjoiRCs4QkNMRjBodzJKaFIvRVQwZUZlM3BzYmlJMGp0Y0E5RXdHdkYrblVzSzNPQTJZbE42ZlhlYllmWlg2a0ltMSIsIm1hYyI6IjA1NWU0ZjFiNDFjN2VkNjNiMzJiNjFlNTFiMjBmNWE3MzA4Yzk1YmJiNzdmZGUyZmZhNjcwYmQxZTYxYTBmY2QifQ%3D%3D; at_home_club_session=eyJpdiI6IjZxWXZSYjdGWXU5SHBKSFFRdGQycWc9PSIsInZhbHVlIjoiU3RyTDdoNGJBUW93ck9CTmFjVFpjRTRxMVVwQzZmcjJJTXJUNFU0UUZVcnkzcWdBbzZxWjNvTWZrZmFuMXBrbSIsIm1hYyI6IjFkOTFiNDg5YmZjYmE0NGZiZDg3ZGY5ZDQyMDg2MGZjNzFlMmI0OTA1OGY2MzdkMmFmOGI0ZTlkOTE4ZDM0NWUifQ%3D%3D; XLtgHBp79G2IlVzFPoHViq4wcAV1TMveovlNr1V4=eyJpdiI6ImZiRThmNUpBb3N0Z21MVHJRMVIvRFE9PSIsInZhbHVlIjoiVDV5S2tDOTFNcElqc1NINVpsdi9Ibk04cFVSekkvSytvY01YUDFIbENhZkV3VnVTaHpOTjlwUjROVnFlMk96SWgwUlByZFU3MlA0YVhTelFDaEVTdndkQnczUFZ3bXJlVHpUTkZwb3Z2d1Z1VUI1STJkeG1ZMm13N0h3S282V2l3MmlvUmFrQXY4SXFFaHcrNjBucktJcmRmSk81UUtFcUFlOCtNaUZHelJpRmxkY2gyZVFOWWRUWTdqZ2NFYi85WlVBeFJ2bm5xU05IU3F1aE0ybXlzUnltRUh6eG1qZklaVW9GSDRsU3RMWmRrL242WjJ5VFZVa3dDTWtIN051SThUa0FjZDFsSXp6SmNSTWFWTDl5dk5IczFKcEpSWS9qZUZiMGVENTdKcjVrTlBITWRjV2dUY1RmcElNL0FUSzQxS0JGZFBzUWVha3ZIOVh6YWpTZnNZa202bHB1akQvakVHWTRZU1Z1WWFZZmxIcDN2bDZrek9JRHkybE01b3BlTWErYmhKK2xQN0FmTzhZS3M3bTBHUVJaSzhIdzBGWlc4Vjd1QVJCSFovZz0iLCJtYWMiOiI2ZWZlYWIwYzhlZjMyZjlkNTI0ZWJmYjFhMzExYTIxZTkyNDM1ODM3ODg1YjlmM2ZiOTVhMTMwYTAwYjk4NjhiIn0%3D Host: mydomain.com Origin: http://spa.mydomain.com Referer: http://spa.mydomain.info/account User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 X-XSRF-TOKEN: eyJpdiI6ImhadVF0eHlEY3l4RWtnZk45MmVxZ2c9PSIsInZhbHVlIjoiRCs4QkNMRjBodzJKaFIvRVQwZUZlM3BzYmlJMGp0Y0E5RXdHdkYrblVzSzNPQTJZbE42ZlhlYllmWlg2a0ltMSIsIm1hYyI6IjA1NWU0ZjFiNDFjN2VkNjNiMzJiNjFlNTFiMjBmNWE3MzA4Yzk1YmJiNzdmZGUyZmZhNjcwYmQxZTYxYTBmY2QifQ==` and my cors, ``` 'paths' => ['api/*', 'sanctum/csrf-cookie', 'login'], 'allowed_methods' => ['*'], 'allowed_origins' => ['*'], 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => true, ``` Everything works perfectly on localhost.
2020/06/09
[ "https://Stackoverflow.com/questions/62287390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57872/" ]
Turns out when our Azure DevOps instance was first set up, all our users set up Microsoft accounts with their company emails. Later when we finally stood up Azure AD but before we connected it to DevOps we added a new project and set the permissions for a few existing employees. For some reason the user permissions on the new DevOps project were listed as "aaduser" type instead of the standard "user" type (ms account) that all the users in other projects in DevOps had. In other words duplicate UPNs but different accounts (but sort of the same). What's weird is that DevOps managed to find the Azure AD user account before we even connected the two together services together. We removed the offending users with the standard "user" type and re-added them so they were now all listed as "aaduser." We were then able to connect Azure AD. To be clear, this was all done on the DevOps side and had nothing to do with AD. Not sure why it was finding Azure AD users when we weren't even connected to it yet.
According to [this doc](https://learn.microsoft.com/en-us/azure/devops/organizations/accounts/faq-azure-access?view=azure-devops#q-why-did-i-get-an-error-stating-that-my-organization-has-multiple-active-identities-with-the-same-upn): > During the connect process, we map existing users to members of the Azure AD tenant, based on their UPN, which is often known as sign-in address. If we detect multiple users with the same UPN, we don't know how to map these users. The cause of this issue is that the target user has the same UPN as other user. A UPN must be unique among all security principal objects within a directory forest. The UPN contains UPN prefix (the user account name) and a UPN suffix (a DNS domain name). For example:`someone@example.com` You can compare the target account with other user accounts. Then you could find the duplicate UPN. You could try to remove the duplicate one or [change the UPN](https://learn.microsoft.com/en-us/azure/active-directory/hybrid/howto-troubleshoot-upn-changes#learn-about-upns-and-upn-changes) as unique. Hope this helps.
3
1
31,079,002
I have a solution with a C# project of 'library' and a project 'JavaScript' after that compiled it generates a .winmd file being taken to another project. But this project is built on x86 and I need to compile for x64, to run the application in order x64 get the following error: ``` 'WWAHost.exe' (Script): Loaded 'Script Code (MSAppHost/2.0)'. Unhandled exception at line 25, column 13 in ms-appx://2c341884-5957-41b1-bb32-10e13dd434ba/js/default.js 0x8007000b - JavaScript runtime error: An attempt was made to load a program with an incorrect format. System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at System.Runtime.InteropServices.WindowsRuntime.ManagedActivationFactory.ActivateInstance() WinRT information: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at System.Runtime.InteropServices.WindowsRuntime.ManagedActivationFactory.ActivateInstance() The program '[5776] WWAHost.exe' has exited with code -1 (0xffffffff). ```
2015/06/26
[ "https://Stackoverflow.com/questions/31079002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It looks like you were making calls with no Access Token at all, to data that's publicly visible on Facebook.com v1.0 of Facebook's Graph API was deprecated in April 2014 and scheduled for removal after 2015-04-30 - one of the changes between v1.0 and v2.0 was that in v2.0 all calls require an Access Token - the deprecation of v1.0 was phased and one of the last things to be removed was the ability to make tokenless calls - it's possible that's why you didn't notice this until recently More info on the changelog here: <https://developers.facebook.com/docs/apps/changelog#v2_0> - under "Changes from v1.0 to v2.0" You'll need to rewrite your app to make its API calls using an access token from a user who can see the content you're trying to create, or (possibly) using your app's access token (and given you had no token at all, you may also need to create an app ID for that purpose)
I finally realized that since May 1, it is **necessary** to create an app and then generate a token and use it in my JSON call URL. So this: ``` $.getJSON('https://graph.facebook.com/616894958361877/photos?limit=100&callback=? ``` Became this: ``` $.getJSON('https://graph.facebook.com/616894958361877/photos?access_token=123456789123456789|ajdkajdlajfldkeieflejejf&limit=100&callback=? ``` I've replaced my actual token with random numbers, but it's basically a giant string of numbers and letters with a pipe in the middle. For me the confusing part was needing an "app" when I'm not using a mobile device. I also didn't realize that Facebook had actually deprecated the old methond. Creating an app is simple... go here and follow the steps: <https://developers.facebook.com/apps/> Leave the "NameSpace" field blank... not sure what that is exactly and it's not required. Generating the token string took a few more steps which a friend from work walked me through... I can't remember off the top of my head, but once you get the string and insert it into your JSON call, it will definitely work. The REASON for this is so when Facebook receives a data request from some random website, the request comes with a built-in ID so Facebook knows who is asking for the data.
1
0
31,079,002
I have a solution with a C# project of 'library' and a project 'JavaScript' after that compiled it generates a .winmd file being taken to another project. But this project is built on x86 and I need to compile for x64, to run the application in order x64 get the following error: ``` 'WWAHost.exe' (Script): Loaded 'Script Code (MSAppHost/2.0)'. Unhandled exception at line 25, column 13 in ms-appx://2c341884-5957-41b1-bb32-10e13dd434ba/js/default.js 0x8007000b - JavaScript runtime error: An attempt was made to load a program with an incorrect format. System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at System.Runtime.InteropServices.WindowsRuntime.ManagedActivationFactory.ActivateInstance() WinRT information: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at System.Runtime.InteropServices.WindowsRuntime.ManagedActivationFactory.ActivateInstance() The program '[5776] WWAHost.exe' has exited with code -1 (0xffffffff). ```
2015/06/26
[ "https://Stackoverflow.com/questions/31079002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It looks like you were making calls with no Access Token at all, to data that's publicly visible on Facebook.com v1.0 of Facebook's Graph API was deprecated in April 2014 and scheduled for removal after 2015-04-30 - one of the changes between v1.0 and v2.0 was that in v2.0 all calls require an Access Token - the deprecation of v1.0 was phased and one of the last things to be removed was the ability to make tokenless calls - it's possible that's why you didn't notice this until recently More info on the changelog here: <https://developers.facebook.com/docs/apps/changelog#v2_0> - under "Changes from v1.0 to v2.0" You'll need to rewrite your app to make its API calls using an access token from a user who can see the content you're trying to create, or (possibly) using your app's access token (and given you had no token at all, you may also need to create an app ID for that purpose)
You need an App Access Token. Go to <http://developers.facebook.com/apps/> and create an app for the client's Facebook page. When you're presented with the options, select the "Website" type of app. You can skip the configuration option using the "Skip and Create App ID" button in the top right corner. Give it a Display Name, don't worry about the Namespace, and give it a applicable category. Once the app is created, go to "Tools & Support" > "Access Token Tool" in the top menu. You should see an App Token listed in green text. Copy that into your JSON call, and it should work. ``` $.getJSON('https://graph.facebook.com/616894958361877/photos?access_token=PASTE_APP_TOKEN_HERE&limit=100&callback=?', function(json) { $.each(json.data, function(i, photo) { $('<li></li>').append('<span class="thumb" style="background: url(' + ((photo.images[1]) ? photo.images[1].source : '') + ') center center no-repeat; background-size: cover;"><a href=' + ((photo.images[0]) ? photo.images[0].source : '') + ' rel="gallery"></a></span>').appendTo('#timeline'); }); ``` });
1
0
334,167
I am late game Alien Crossfire, attacking with gravitons aremed with [string disruptor](https://strategywiki.org/wiki/Sid_Meier%27s_Alpha_Centauri/Weapon#String_Disruptor). Unfortunately, the others have gotten wise and are building everything [AAA](https://strategywiki.org/wiki/Sid_Meier%27s_Alpha_Centauri/Special_Ability#AAA_Tracking). In a way, that's good, as it is expensive, and diverts their resources. However, I can no longer "one hit kill", and am losing gravitons. Should I replace the weapons with [Psi attack](https://strategywiki.org/wiki/Sid_Meier%27s_Alpha_Centauri/Weapon#Psi_Attack)?
2018/06/24
[ "https://gaming.stackexchange.com/questions/334167", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/92813/" ]
Psi attack/defense is orthogonal to conventional weapons. Its result depends on *Morale* levels of attacking/defending units. If an attacker/defender is a *Mind Worm*, they have their own class, plus both faction's *Planet (Green)* scores/attitudes largely affect the outcome of the fight. **Answer:** see what's your faction's Morale and/or Green score. You may also trick the system by changing your *Government/Economy* type before the attack. Say, if you possess some *Mind Worms* and you are planning to give them a victorious ride, switch to *Green* several turns before the planned invasion. Or to *Fundamentalist + Power* if you are planning Psi attacks with conventional units. --- Personally, I *love* Green because if you are lucky enough, you can capture native life forms, making a considerable amount of your units Mind Worms **(Independent)** which means it requires no support from a home base, still performing as police in "at least one unit defending each Base" paradigm.
If you have dominant weapons, mixing in hovertanks and even air-dropped infantry will let you continue leveraging those dominant weapons. Psi-combat is mostly useful when facing technologically superior enemies that your weapons cannot defeat. Switching from overwhelming firepower to psi-attack will make you lose as many (if not more) units, since psi-combat is less lopsided in general. I'd say consider changing your gravs to transports and using their mobility to deploy slower, ground-based units that ignore AAA. At least until your opponents stop putting all of their eggs in one basket.
3
1
43,377,941
**Goal**: I aim to use t-SNE (t-distributed Stochastic Neighbor Embedding) in R for dimensionality reduction of my training data (with *N* observations and *K* variables, where *K>>N*) and subsequently aim to come up with the t-SNE representation for my test data. **Example**: Suppose I aim to reduce the K variables to *D=2* dimensions (often, *D=2* or *D=3* for t-SNE). There are two R packages: `Rtsne` and `tsne`, while I use the former here. ``` # load packages library(Rtsne) # Generate Training Data: random standard normal matrix with J=400 variables and N=100 observations x.train <- matrix(nrom(n=40000, mean=0, sd=1), nrow=100, ncol=400) # Generate Test Data: random standard normal vector with N=1 observation for J=400 variables x.test <- rnorm(n=400, mean=0, sd=1) # perform t-SNE set.seed(1) fit.tsne <- Rtsne(X=x.train, dims=2) ``` where the command `fit.tsne$Y` will return the (100x2)-dimensional object containing the t-SNE representation of the data; can also be plotted via `plot(fit.tsne$Y)`. **Problem**: Now, what I am looking for is a function that returns a prediction `pred` of dimension (1x2) for my test data based on the trained t-SNE model. Something like, ``` # The function I am looking for (but doesn't exist yet): pred <- predict(object=fit.tsne, newdata=x.test) ``` (How) Is this possible? Can you help me out with this?
2017/04/12
[ "https://Stackoverflow.com/questions/43377941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5634399/" ]
From the author himself (<https://lvdmaaten.github.io/tsne/>): > Once I have a t-SNE map, how can I embed incoming test points in that > map? > > > t-SNE learns a non-parametric mapping, which means that it does not > learn an explicit function that maps data from the input space to the > map. Therefore, it is not possible to embed test points in an existing > map (although you could re-run t-SNE on the full dataset). A potential > approach to deal with this would be to train a multivariate regressor > to predict the map location from the input data. Alternatively, you > could also make such a regressor minimize the t-SNE loss directly, > which is what I did in this paper (<https://lvdmaaten.github.io/publications/papers/AISTATS_2009.pdf>). So you can't directly apply new data points. However, you can fit a multivariate regression model between your data and the embedded dimensions. The author recognizes that it's a limitation of the method and suggests this way to get around it.
t-SNE fundamentally does not do what you want. t-SNE is designed only for visualizing a dataset in a low (2 or 3) dimension space. You give it all the data you want to visualize all at once. It is not a general purpose dimensionality reduction tool. If you are trying to apply t-SNE to "new" data, you are probably not thinking about your problem correctly, or perhaps simply did not understand the purpose of t-SNE.
3
0
43,377,941
**Goal**: I aim to use t-SNE (t-distributed Stochastic Neighbor Embedding) in R for dimensionality reduction of my training data (with *N* observations and *K* variables, where *K>>N*) and subsequently aim to come up with the t-SNE representation for my test data. **Example**: Suppose I aim to reduce the K variables to *D=2* dimensions (often, *D=2* or *D=3* for t-SNE). There are two R packages: `Rtsne` and `tsne`, while I use the former here. ``` # load packages library(Rtsne) # Generate Training Data: random standard normal matrix with J=400 variables and N=100 observations x.train <- matrix(nrom(n=40000, mean=0, sd=1), nrow=100, ncol=400) # Generate Test Data: random standard normal vector with N=1 observation for J=400 variables x.test <- rnorm(n=400, mean=0, sd=1) # perform t-SNE set.seed(1) fit.tsne <- Rtsne(X=x.train, dims=2) ``` where the command `fit.tsne$Y` will return the (100x2)-dimensional object containing the t-SNE representation of the data; can also be plotted via `plot(fit.tsne$Y)`. **Problem**: Now, what I am looking for is a function that returns a prediction `pred` of dimension (1x2) for my test data based on the trained t-SNE model. Something like, ``` # The function I am looking for (but doesn't exist yet): pred <- predict(object=fit.tsne, newdata=x.test) ``` (How) Is this possible? Can you help me out with this?
2017/04/12
[ "https://Stackoverflow.com/questions/43377941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5634399/" ]
t-SNE does not really work this way: The following is an expert from the t-SNE author's website (<https://lvdmaaten.github.io/tsne/>): > Once I have a t-SNE map, how can I embed incoming test points in that > map? > > > t-SNE learns a non-parametric mapping, which means that it does not > learn an explicit function that maps data from the input space to the > map. Therefore, it is not possible to embed test points in an existing > map (although you could re-run t-SNE on the full dataset). A potential > approach to deal with this would be to train a multivariate regressor > to predict the map location from the input data. Alternatively, you > could also make such a regressor minimize the t-SNE loss directly, > which is what I did in this paper. You may be interested in his paper: <https://lvdmaaten.github.io/publications/papers/AISTATS_2009.pdf> This website in addition to being really cool offers a wealth of info about t-SNE: <http://distill.pub/2016/misread-tsne/> On Kaggle I have also seen people do things like this which may also be of intrest: <https://www.kaggle.com/cherzy/d/dalpozz/creditcardfraud/visualization-on-a-2d-map-with-t-sne>
t-SNE fundamentally does not do what you want. t-SNE is designed only for visualizing a dataset in a low (2 or 3) dimension space. You give it all the data you want to visualize all at once. It is not a general purpose dimensionality reduction tool. If you are trying to apply t-SNE to "new" data, you are probably not thinking about your problem correctly, or perhaps simply did not understand the purpose of t-SNE.
3
0
43,377,941
**Goal**: I aim to use t-SNE (t-distributed Stochastic Neighbor Embedding) in R for dimensionality reduction of my training data (with *N* observations and *K* variables, where *K>>N*) and subsequently aim to come up with the t-SNE representation for my test data. **Example**: Suppose I aim to reduce the K variables to *D=2* dimensions (often, *D=2* or *D=3* for t-SNE). There are two R packages: `Rtsne` and `tsne`, while I use the former here. ``` # load packages library(Rtsne) # Generate Training Data: random standard normal matrix with J=400 variables and N=100 observations x.train <- matrix(nrom(n=40000, mean=0, sd=1), nrow=100, ncol=400) # Generate Test Data: random standard normal vector with N=1 observation for J=400 variables x.test <- rnorm(n=400, mean=0, sd=1) # perform t-SNE set.seed(1) fit.tsne <- Rtsne(X=x.train, dims=2) ``` where the command `fit.tsne$Y` will return the (100x2)-dimensional object containing the t-SNE representation of the data; can also be plotted via `plot(fit.tsne$Y)`. **Problem**: Now, what I am looking for is a function that returns a prediction `pred` of dimension (1x2) for my test data based on the trained t-SNE model. Something like, ``` # The function I am looking for (but doesn't exist yet): pred <- predict(object=fit.tsne, newdata=x.test) ``` (How) Is this possible? Can you help me out with this?
2017/04/12
[ "https://Stackoverflow.com/questions/43377941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5634399/" ]
This the mail answer from the author (Jesse Krijthe) of the Rtsne package: > Thank you for the very specific question. I had an earlier request for > this and it is noted as an open issue on GitHub > (<https://github.com/jkrijthe/Rtsne/issues/6>). The main reason I am > hesitant to implement something like this is that, in a sense, there > is no 'natural' way explain what a prediction means in terms of tsne. > To me, tsne is a way to visualize a distance matrix. As such, a new > sample would lead to a new distance matrix and hence a new > visualization. So, my current thinking is that the only sensible way > would be to rerun the tsne procedure on the train and test set > combined. > > > Having said that, other people do think it makes sense to define > predictions, for instance by keeping the train objects fixed in the > map and finding good locations for the test objects (as was suggested > in the issue). An approach I would personally prefer over this would > be something like parametric tsne, which Laurens van der Maaten (the > author of the tsne paper) explored a paper. However, this would best > be implemented using something else than my package, because the > parametric model is likely most effective if it is selected by the > user. > > > So my suggestion would be to 1) refit the mapping using all data or 2) > see if you can find an implementation of parametric tsne, the only one > I know of would be Laurens's Matlab implementation. > > > Sorry I can not be of more help. If you come up with any other/better > solutions, please let me know.
t-SNE fundamentally does not do what you want. t-SNE is designed only for visualizing a dataset in a low (2 or 3) dimension space. You give it all the data you want to visualize all at once. It is not a general purpose dimensionality reduction tool. If you are trying to apply t-SNE to "new" data, you are probably not thinking about your problem correctly, or perhaps simply did not understand the purpose of t-SNE.
4
0
43,377,941
**Goal**: I aim to use t-SNE (t-distributed Stochastic Neighbor Embedding) in R for dimensionality reduction of my training data (with *N* observations and *K* variables, where *K>>N*) and subsequently aim to come up with the t-SNE representation for my test data. **Example**: Suppose I aim to reduce the K variables to *D=2* dimensions (often, *D=2* or *D=3* for t-SNE). There are two R packages: `Rtsne` and `tsne`, while I use the former here. ``` # load packages library(Rtsne) # Generate Training Data: random standard normal matrix with J=400 variables and N=100 observations x.train <- matrix(nrom(n=40000, mean=0, sd=1), nrow=100, ncol=400) # Generate Test Data: random standard normal vector with N=1 observation for J=400 variables x.test <- rnorm(n=400, mean=0, sd=1) # perform t-SNE set.seed(1) fit.tsne <- Rtsne(X=x.train, dims=2) ``` where the command `fit.tsne$Y` will return the (100x2)-dimensional object containing the t-SNE representation of the data; can also be plotted via `plot(fit.tsne$Y)`. **Problem**: Now, what I am looking for is a function that returns a prediction `pred` of dimension (1x2) for my test data based on the trained t-SNE model. Something like, ``` # The function I am looking for (but doesn't exist yet): pred <- predict(object=fit.tsne, newdata=x.test) ``` (How) Is this possible? Can you help me out with this?
2017/04/12
[ "https://Stackoverflow.com/questions/43377941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5634399/" ]
This the mail answer from the author (Jesse Krijthe) of the Rtsne package: > Thank you for the very specific question. I had an earlier request for > this and it is noted as an open issue on GitHub > (<https://github.com/jkrijthe/Rtsne/issues/6>). The main reason I am > hesitant to implement something like this is that, in a sense, there > is no 'natural' way explain what a prediction means in terms of tsne. > To me, tsne is a way to visualize a distance matrix. As such, a new > sample would lead to a new distance matrix and hence a new > visualization. So, my current thinking is that the only sensible way > would be to rerun the tsne procedure on the train and test set > combined. > > > Having said that, other people do think it makes sense to define > predictions, for instance by keeping the train objects fixed in the > map and finding good locations for the test objects (as was suggested > in the issue). An approach I would personally prefer over this would > be something like parametric tsne, which Laurens van der Maaten (the > author of the tsne paper) explored a paper. However, this would best > be implemented using something else than my package, because the > parametric model is likely most effective if it is selected by the > user. > > > So my suggestion would be to 1) refit the mapping using all data or 2) > see if you can find an implementation of parametric tsne, the only one > I know of would be Laurens's Matlab implementation. > > > Sorry I can not be of more help. If you come up with any other/better > solutions, please let me know.
From the author himself (<https://lvdmaaten.github.io/tsne/>): > Once I have a t-SNE map, how can I embed incoming test points in that > map? > > > t-SNE learns a non-parametric mapping, which means that it does not > learn an explicit function that maps data from the input space to the > map. Therefore, it is not possible to embed test points in an existing > map (although you could re-run t-SNE on the full dataset). A potential > approach to deal with this would be to train a multivariate regressor > to predict the map location from the input data. Alternatively, you > could also make such a regressor minimize the t-SNE loss directly, > which is what I did in this paper (<https://lvdmaaten.github.io/publications/papers/AISTATS_2009.pdf>). So you can't directly apply new data points. However, you can fit a multivariate regression model between your data and the embedded dimensions. The author recognizes that it's a limitation of the method and suggests this way to get around it.
4
3
43,377,941
**Goal**: I aim to use t-SNE (t-distributed Stochastic Neighbor Embedding) in R for dimensionality reduction of my training data (with *N* observations and *K* variables, where *K>>N*) and subsequently aim to come up with the t-SNE representation for my test data. **Example**: Suppose I aim to reduce the K variables to *D=2* dimensions (often, *D=2* or *D=3* for t-SNE). There are two R packages: `Rtsne` and `tsne`, while I use the former here. ``` # load packages library(Rtsne) # Generate Training Data: random standard normal matrix with J=400 variables and N=100 observations x.train <- matrix(nrom(n=40000, mean=0, sd=1), nrow=100, ncol=400) # Generate Test Data: random standard normal vector with N=1 observation for J=400 variables x.test <- rnorm(n=400, mean=0, sd=1) # perform t-SNE set.seed(1) fit.tsne <- Rtsne(X=x.train, dims=2) ``` where the command `fit.tsne$Y` will return the (100x2)-dimensional object containing the t-SNE representation of the data; can also be plotted via `plot(fit.tsne$Y)`. **Problem**: Now, what I am looking for is a function that returns a prediction `pred` of dimension (1x2) for my test data based on the trained t-SNE model. Something like, ``` # The function I am looking for (but doesn't exist yet): pred <- predict(object=fit.tsne, newdata=x.test) ``` (How) Is this possible? Can you help me out with this?
2017/04/12
[ "https://Stackoverflow.com/questions/43377941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5634399/" ]
This the mail answer from the author (Jesse Krijthe) of the Rtsne package: > Thank you for the very specific question. I had an earlier request for > this and it is noted as an open issue on GitHub > (<https://github.com/jkrijthe/Rtsne/issues/6>). The main reason I am > hesitant to implement something like this is that, in a sense, there > is no 'natural' way explain what a prediction means in terms of tsne. > To me, tsne is a way to visualize a distance matrix. As such, a new > sample would lead to a new distance matrix and hence a new > visualization. So, my current thinking is that the only sensible way > would be to rerun the tsne procedure on the train and test set > combined. > > > Having said that, other people do think it makes sense to define > predictions, for instance by keeping the train objects fixed in the > map and finding good locations for the test objects (as was suggested > in the issue). An approach I would personally prefer over this would > be something like parametric tsne, which Laurens van der Maaten (the > author of the tsne paper) explored a paper. However, this would best > be implemented using something else than my package, because the > parametric model is likely most effective if it is selected by the > user. > > > So my suggestion would be to 1) refit the mapping using all data or 2) > see if you can find an implementation of parametric tsne, the only one > I know of would be Laurens's Matlab implementation. > > > Sorry I can not be of more help. If you come up with any other/better > solutions, please let me know.
t-SNE does not really work this way: The following is an expert from the t-SNE author's website (<https://lvdmaaten.github.io/tsne/>): > Once I have a t-SNE map, how can I embed incoming test points in that > map? > > > t-SNE learns a non-parametric mapping, which means that it does not > learn an explicit function that maps data from the input space to the > map. Therefore, it is not possible to embed test points in an existing > map (although you could re-run t-SNE on the full dataset). A potential > approach to deal with this would be to train a multivariate regressor > to predict the map location from the input data. Alternatively, you > could also make such a regressor minimize the t-SNE loss directly, > which is what I did in this paper. You may be interested in his paper: <https://lvdmaaten.github.io/publications/papers/AISTATS_2009.pdf> This website in addition to being really cool offers a wealth of info about t-SNE: <http://distill.pub/2016/misread-tsne/> On Kaggle I have also seen people do things like this which may also be of intrest: <https://www.kaggle.com/cherzy/d/dalpozz/creditcardfraud/visualization-on-a-2d-map-with-t-sne>
4
3
62,380,246
As the title says is there a way to programmatically render (into a DOM element) a component in angular? For example, in React I can use `ReactDOM.render` to turn a component into a DOM element. I am wondering if it's possible to something similar in Angular?
2020/06/15
[ "https://Stackoverflow.com/questions/62380246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6009213/" ]
At first you'll need to have a template in your HTML file at the position where you'll want to place the dynamically loaded component. ```html <ng-template #placeholder></ng-template> ``` In the component you can inject the `DynamicFactoryResolver` inside the constructor. Once you'll execute the `loadComponent()` function, the `DynamicComponent` will be visible in the template. `DynamicComponent` can be whatever component you would like to display. ```js import { Component, VERSION, ComponentFactoryResolver, ViewChild, ElementRef, ViewContainerRef } from '@angular/core'; import { DynamicComponent } from './dynamic.component'; @Component({ selector: 'my-app', templateUrl: './app.component.html' }) export class AppComponent { @ViewChild('placeholder', {read: ViewContainerRef}) private viewRef: ViewContainerRef; constructor(private cfr: ComponentFactoryResolver) {} loadComponent() { this.viewRef.clear(); const componentFactory = this.cfr.resolveComponentFactory(DynamicComponent); const componentRef = this.viewRef.createComponent(componentFactory); } } ``` Here is a [Stackblitz](https://stackblitz.com/edit/angular-ivy-dynamic-components?file=src%2Fapp%2Fapp.component.ts). What the `loadComponent` function does is: 1. It clears the host 2. It creates a so called factory object of your component. (`resolveComponentFactory`) 3. It creates an instance of your factory object and inserts it in the host reference (`createComponent`) 4. You can use the `componentRef` to, for example, modify public properties or trigger public functions of that components instance.
If you want to render the angular component into a Dom element which is not compiled by angular, Then we can't obtain a ViewContainerRef. Then you can use Angular cdk portal and portal host concepts to achieve this. Create portal host with any DOMElememt, injector, applicationRef, componentFactoryResolver. Create portal with the component class. And attach the portal to host. <https://medium.com/angular-in-depth/angular-cdk-portals-b02f66dd020c>
5
0
12,881
No matter how I rearrange this, the increment compare always returns false.... I have even taken it out of the if, and put it in its own if: ``` int buttonFSM(button *ptrButton) { int i; i = digitalRead(ptrButton->pin); switch(ptrButton->buttonState) { case SW_UP: if(i==0 && ++ptrButton->debounceTics == DBNC_TICS) //swtich went down { ptrButton->buttonState = SW_DOWN; ptrButton->debounceTics = 0; return SW_TRANS_UD; } ptrButton->debounceTics = 0; return SW_UP; case SW_DOWN: if(i==1 && ++ptrButton->debounceTics == DBNC_TICS) //switch is back up { ptrButton->buttonState = SW_UP; ptrButton->debounceTics = 0; return SW_TRANS_DU; } ptrButton->debounceTics = 0; return SW_DOWN; } } ```
2015/06/24
[ "https://arduino.stackexchange.com/questions/12881", "https://arduino.stackexchange.com", "https://arduino.stackexchange.com/users/10817/" ]
Looks to me like the path where the if doesn't happen are getting you. You don't show what DBNC\_TICS is set to, but I'm assuming it's > 1. ptrButton->debounceTics will never be greater than 1 because you always: ``` ptrButton->debounceTics = 0; ```
The error is due to wrong expectations on operators precedence: ++ and -> have the same precedence, so they are evaluated left to right. See <http://en.cppreference.com/w/c/language/operator_precedence> . Overall, the lack of parenthesis makes the readability poor. The code can be improved by dropping the switch and simply checking that the current value is equal to the previous value through the duration of the sampling period. Then read the value and decide if it's high or low. But even this might be a poor choice, because it simply samples the value periodically and can miss changes that are not intercepted by the sampling. Depending on the application, it might be preferrable (certainly it is more precise) to use interrupts on both edges (rising and falling) and a timeout: reset the timer at every interrupt. If the timer expires undisturbed, use the level read at the last interrupt.
1
0
12,881
No matter how I rearrange this, the increment compare always returns false.... I have even taken it out of the if, and put it in its own if: ``` int buttonFSM(button *ptrButton) { int i; i = digitalRead(ptrButton->pin); switch(ptrButton->buttonState) { case SW_UP: if(i==0 && ++ptrButton->debounceTics == DBNC_TICS) //swtich went down { ptrButton->buttonState = SW_DOWN; ptrButton->debounceTics = 0; return SW_TRANS_UD; } ptrButton->debounceTics = 0; return SW_UP; case SW_DOWN: if(i==1 && ++ptrButton->debounceTics == DBNC_TICS) //switch is back up { ptrButton->buttonState = SW_UP; ptrButton->debounceTics = 0; return SW_TRANS_DU; } ptrButton->debounceTics = 0; return SW_DOWN; } } ```
2015/06/24
[ "https://arduino.stackexchange.com/questions/12881", "https://arduino.stackexchange.com", "https://arduino.stackexchange.com/users/10817/" ]
Looks to me like the path where the if doesn't happen are getting you. You don't show what DBNC\_TICS is set to, but I'm assuming it's > 1. ptrButton->debounceTics will never be greater than 1 because you always: ``` ptrButton->debounceTics = 0; ```
```C++ if(i==0 && ++ptrButton->debounceTics == DBNC_TICS) //swtich went down { ptrButton->buttonState = SW_DOWN; ptrButton->debounceTics = 0; return SW_TRANS_UD; } ptrButton->debounceTics = 0; ``` I'm going to agree with user3877595 but explain why, as his/her answer got a downvote. `DBNC_TICS` has to be > 1, right? Otherwise what is the point? We want to debounce after "x" ticks, and let's assume that the number of ticks is initially zero. If `DBNC_TICS` is == 1 then this is always true: ```C++ ++ptrButton->debounceTics == DBNC_TICS ``` Therefore that test is useless. If `DBNC_TICS` > 1 then it will not execute the "if" block and execute this instead: ```C++ ptrButton->debounceTics = 0; ``` So `ptrButton->debounceTics` is back to zero, and we are back to square 1. Therefore the test will always be false. > No matter how I rearrange this, the increment compare always returns false.... As stated in the question.
1
0
64,999,490
Hi I'm learning right now how to upload images to database, but I'm getting this error/notice. ``` </select> <input type="text" name="nama" class="input-control" placeholder="Nama Produk" required> <input type="text" name="harga" class="input-control" placeholder="Harga Produk" required> <input type="file" name="img" class="input-control" required> <textarea class="input-control" name="deskripsi" placeholder="Desrkipsi"></textarea> <select class="input-control" name="status"> <option value="">--Pilih--</option> <option value="1">Aktif</option> <option value="0">Tidak Aktif</option> </select> <input type="submit" name="submit" value="Submit" class="btn-login"> </form> <?php if(isset($_POST['submit'])){ $kategori = $_POST['kategori']; $nama = $_POST['nama']; $harga = $_POST['harga']; $deskripsi = $_POST['deskripsi']; $status = $_POST['status']; $filename = $_FILES['img']['name']; $tmp_name = $_FILES['img']['tmp_name']; } ``` the error output ``` Notice: Undefined index: img in C:\xampp\htdocs\pa_web\tambah_produk.php on line 66 ```
2020/11/25
[ "https://Stackoverflow.com/questions/64999490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14704128/" ]
You need to add `enctype="multipart/form-data"` to your form <https://www.php.net/manual/en/features.file-upload.post-method.php> > **Note:** > Be sure your file upload form has attribute > enctype="multipart/form-data" otherwise the file upload will not work.
When you want to submit file from form you should put "enctype="multipart/form-data". ``` <form "enctype="multipart/form-data" ...> </form> ``` Do you put it?
1
0
21,657,910
Can we change the color of the text based on the color of the background image? I have a background image which i have appended it to body. When you reload the page every time the background image gets changed. But i have my menus which are positioned on the image having text color as black. If the background image is black, menus wont be visible. Any solutions for my problem? Thanks in advance.
2014/02/09
[ "https://Stackoverflow.com/questions/21657910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1999172/" ]
use switch case to handle ``` switch(backgroundimage){ case "black.jpg": document.body.color = "white"; break; case "white.jpg": document.body.color = "black"; break; case "green.jpg": document.body.color = "gray"; break; } ```
If you know what will be the image that will be loaded you can create a dictionary with the image name and the css class that will be appended to the text for it. then on page load attach the class to the body classes. If you dont know the image that will be loaded there are some solutions but they are not complete. look at this [answer](https://stackoverflow.com/a/2541680/395890)
2
0
2,274,695
My colleague has been using "new function()" with a lower case "f" to define new objects in JavaScript. It seems to work well in all major browsers and it also seems to be fairly effective at hiding private variables. Here's an example: ``` var someObj = new function () { var inner = 'some value'; this.foo = 'blah'; this.get_inner = function () { return inner; }; this.set_inner = function (s) { inner = s; }; }; ``` As soon as "this" is used, it becomes a public property of someObj. So someObj.foo, someObj.get\_inner() and someObj.set\_inner() are all available publicly. In addition, set\_inner() and get\_inner() are privileged methods, so they have access to "inner" through closures. However, I haven't seen any reference to this technique anywhere. Even Douglas Crockford's JSLint complains about it: > * weird construction. Delete 'new' We're using this technique in production and it seems to be working well, but I'm a bit anxious about it because it's not documented anywhere. Does anyone know if this is a valid technique?
2010/02/16
[ "https://Stackoverflow.com/questions/2274695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/188740/" ]
I've seen that technique before, it's valid, you are using a function expression as if it were a [Constructor Function](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function). But IMHO, you can achieve the same with an auto-invoking function expression, I don't really see the point of using the `new` operator in that way: ``` var someObj = (function () { var instance = {}, inner = 'some value'; instance.foo = 'blah'; instance.get_inner = function () { return inner; }; instance.set_inner = function (s) { inner = s; }; return instance; })(); ``` The purpose of the `new` operator is to create new object instances, setting up the `[[Prototype]]` internal property, you can see how this is made by the [`[Construct]`](http://bclary.com/2004/11/07/#a-13.2.2) internal property. The above code will produce an equivalent result.
Your code is just similar to the less weird construct ``` function Foo () { var inner = 'some value'; this.foo = 'blah'; ... }; var someObj = new Foo; ```
7
4
2,274,695
My colleague has been using "new function()" with a lower case "f" to define new objects in JavaScript. It seems to work well in all major browsers and it also seems to be fairly effective at hiding private variables. Here's an example: ``` var someObj = new function () { var inner = 'some value'; this.foo = 'blah'; this.get_inner = function () { return inner; }; this.set_inner = function (s) { inner = s; }; }; ``` As soon as "this" is used, it becomes a public property of someObj. So someObj.foo, someObj.get\_inner() and someObj.set\_inner() are all available publicly. In addition, set\_inner() and get\_inner() are privileged methods, so they have access to "inner" through closures. However, I haven't seen any reference to this technique anywhere. Even Douglas Crockford's JSLint complains about it: > * weird construction. Delete 'new' We're using this technique in production and it seems to be working well, but I'm a bit anxious about it because it's not documented anywhere. Does anyone know if this is a valid technique?
2010/02/16
[ "https://Stackoverflow.com/questions/2274695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/188740/" ]
I've seen that technique before, it's valid, you are using a function expression as if it were a [Constructor Function](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function). But IMHO, you can achieve the same with an auto-invoking function expression, I don't really see the point of using the `new` operator in that way: ``` var someObj = (function () { var instance = {}, inner = 'some value'; instance.foo = 'blah'; instance.get_inner = function () { return inner; }; instance.set_inner = function (s) { inner = s; }; return instance; })(); ``` The purpose of the `new` operator is to create new object instances, setting up the `[[Prototype]]` internal property, you can see how this is made by the [`[Construct]`](http://bclary.com/2004/11/07/#a-13.2.2) internal property. The above code will produce an equivalent result.
To clarify some aspects and make Douglas Crockford's JSLint not to complain about your code here are some examples of instantiation: ```javascript 1. o = new Object(); // normal call of a constructor 2. o = new Object; // accepted call of a constructor 3. var someObj = new (function () { var inner = 'some value'; this.foo = 'blah'; this.get_inner = function () { return inner; }; this.set_inner = function (s) { inner = s; }; })(); // normal call of a constructor 4. var someObj = new (function () { var inner = 'some value'; this.foo = 'blah'; this.get_inner = function () { return inner; }; this.set_inner = function (s) { inner = s; }; }); // accepted call of a constructor ``` In example 3. expression in (...) as value is a function/constructor. It looks like this: new (function (){...})(). So if we omit ending brackets as in example 2, the expression is still a valid constructor call and looks like example 4. Douglas Crockford's JSLint "thinks" you wanted to assign the function to someObj, not its instance. And after all it's just an warning, not an error.
7
4
1,806,990
Since nothing so far is working I started a new project with ``` python scrapy-ctl.py startproject Nu ``` I followed the tutorial exactly, and created the folders, and a new spider ``` from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from Nu.items import NuItem from urls import u class NuSpider(CrawlSpider): domain_name = "wcase" start_urls = ['http://www.whitecase.com/aabbas/'] names = hxs.select('//td[@class="altRow"][1]/a/@href').re('/.a\w+') u = names.pop() rules = (Rule(SgmlLinkExtractor(allow=(u, )), callback='parse_item'),) def parse(self, response): self.log('Hi, this is an item page! %s' % response.url) hxs = HtmlXPathSelector(response) item = Item() item['school'] = hxs.select('//td[@class="mainColumnTDa"]').re('(?<=(JD,\s))(.*?)(\d+)') return item SPIDER = NuSpider() ``` and when I run ``` C:\Python26\Scripts\Nu>python scrapy-ctl.py crawl wcase ``` I get ``` [Nu] ERROR: Could not find spider for domain: wcase ``` The other spiders at least are recognized by Scrapy, this one is not. What am I doing wrong? Thanks for your help!
2009/11/27
[ "https://Stackoverflow.com/questions/1806990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215094/" ]
Please also check the version of scrapy. The latest version uses "name" instead of "domain\_name" attribute to uniquely identify a spider.
Have you included the spider in `SPIDER_MODULES` list in your scrapy\_settings.py? It's not written in the tutorial anywhere that you should to this, but you do have to.
3
2
1,806,990
Since nothing so far is working I started a new project with ``` python scrapy-ctl.py startproject Nu ``` I followed the tutorial exactly, and created the folders, and a new spider ``` from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from Nu.items import NuItem from urls import u class NuSpider(CrawlSpider): domain_name = "wcase" start_urls = ['http://www.whitecase.com/aabbas/'] names = hxs.select('//td[@class="altRow"][1]/a/@href').re('/.a\w+') u = names.pop() rules = (Rule(SgmlLinkExtractor(allow=(u, )), callback='parse_item'),) def parse(self, response): self.log('Hi, this is an item page! %s' % response.url) hxs = HtmlXPathSelector(response) item = Item() item['school'] = hxs.select('//td[@class="mainColumnTDa"]').re('(?<=(JD,\s))(.*?)(\d+)') return item SPIDER = NuSpider() ``` and when I run ``` C:\Python26\Scripts\Nu>python scrapy-ctl.py crawl wcase ``` I get ``` [Nu] ERROR: Could not find spider for domain: wcase ``` The other spiders at least are recognized by Scrapy, this one is not. What am I doing wrong? Thanks for your help!
2009/11/27
[ "https://Stackoverflow.com/questions/1806990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215094/" ]
Please also check the version of scrapy. The latest version uses "name" instead of "domain\_name" attribute to uniquely identify a spider.
I believe you have syntax errors there. The `name = hxs...` will not work because you don't get defined before the `hxs` object. Try running `python yourproject/spiders/domain.py` to get syntax errors.
3
2
1,806,990
Since nothing so far is working I started a new project with ``` python scrapy-ctl.py startproject Nu ``` I followed the tutorial exactly, and created the folders, and a new spider ``` from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from Nu.items import NuItem from urls import u class NuSpider(CrawlSpider): domain_name = "wcase" start_urls = ['http://www.whitecase.com/aabbas/'] names = hxs.select('//td[@class="altRow"][1]/a/@href').re('/.a\w+') u = names.pop() rules = (Rule(SgmlLinkExtractor(allow=(u, )), callback='parse_item'),) def parse(self, response): self.log('Hi, this is an item page! %s' % response.url) hxs = HtmlXPathSelector(response) item = Item() item['school'] = hxs.select('//td[@class="mainColumnTDa"]').re('(?<=(JD,\s))(.*?)(\d+)') return item SPIDER = NuSpider() ``` and when I run ``` C:\Python26\Scripts\Nu>python scrapy-ctl.py crawl wcase ``` I get ``` [Nu] ERROR: Could not find spider for domain: wcase ``` The other spiders at least are recognized by Scrapy, this one is not. What am I doing wrong? Thanks for your help!
2009/11/27
[ "https://Stackoverflow.com/questions/1806990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215094/" ]
Please also check the version of scrapy. The latest version uses "name" instead of "domain\_name" attribute to uniquely identify a spider.
These two lines look like they're causing trouble: ``` u = names.pop() rules = (Rule(SgmlLinkExtractor(allow=(u, )), callback='parse_item'),) ``` * Only one rule will be followed each time the script is run. Consider creating a rule for each URL. * You haven't created a `parse_item` callback, which means that the rule does nothing. The only callback you've defined is `parse`, which changes the default behaviour of the spider. Also, here are some things that will be worth looking into. * `CrawlSpider` doesn't like having its default `parse` method overloaded. Search for `parse_start_url` in the documentation or the docstrings. You'll see that this is the preferred way to override the default `parse` method for your starting URLs. * `NuSpider.hxs` is called before it's defined.
3
2
1,806,990
Since nothing so far is working I started a new project with ``` python scrapy-ctl.py startproject Nu ``` I followed the tutorial exactly, and created the folders, and a new spider ``` from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from Nu.items import NuItem from urls import u class NuSpider(CrawlSpider): domain_name = "wcase" start_urls = ['http://www.whitecase.com/aabbas/'] names = hxs.select('//td[@class="altRow"][1]/a/@href').re('/.a\w+') u = names.pop() rules = (Rule(SgmlLinkExtractor(allow=(u, )), callback='parse_item'),) def parse(self, response): self.log('Hi, this is an item page! %s' % response.url) hxs = HtmlXPathSelector(response) item = Item() item['school'] = hxs.select('//td[@class="mainColumnTDa"]').re('(?<=(JD,\s))(.*?)(\d+)') return item SPIDER = NuSpider() ``` and when I run ``` C:\Python26\Scripts\Nu>python scrapy-ctl.py crawl wcase ``` I get ``` [Nu] ERROR: Could not find spider for domain: wcase ``` The other spiders at least are recognized by Scrapy, this one is not. What am I doing wrong? Thanks for your help!
2009/11/27
[ "https://Stackoverflow.com/questions/1806990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215094/" ]
Please also check the version of scrapy. The latest version uses "name" instead of "domain\_name" attribute to uniquely identify a spider.
You are overriding the `parse` method, instead of implementing a new `parse_item` method.
3
2
20,931,619
I got nearly 10 functions in class having similar pattern like following function ``` SQLiteDatabase database = this.getWritableDatabase(); try { //Some different code , all other code(try,catch,finally) is same in all functions } catch (SQLiteException e) { Log.e(this.getClass().getName(), e.getMessage()); return false; } finally { database.close(); } } ``` I want to remove that common code from all functions (try ,catch , finally) and move it to a single place How can I achieve this?
2014/01/05
[ "https://Stackoverflow.com/questions/20931619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1033305/" ]
There are a number of frameworks out there that drastically simplify database interaction that you can use, but if you want to do things on your own, and are interested in the Java way to do things like this, here's the idea: Make your "executor" like so: ``` public class Executor { public static void runOperation(Operation operation) { SQLiteDatabase database = this.getWritableDatabase(); try { operation.run(database); } catch (SQLiteException e) { Log.e(operation.getClass().getName(), e.getMessage()); return false; } finally { database.close(); } } ``` Now each of the 10 things you want to do will be operations: ``` public interface Operation { void run(SQLiteDatabase database) throws SQLiteException; } ``` Here is what a particular operation would look like: ``` Operation increaseSalary = new Operation() { public void run(SQLiteDatabase database) throws SQLiteException { // .... write the new increased salary to the database } }; ``` And you run it with: ``` . . Executor.runOperation(increaseSalary); . . ``` You can also make the implementation of the interface an anonymous inner class, but that may make it a little less readable. ``` . . Executor.runOperation(new Operation() { public void run(SQLiteDatabase database) throws SQLiteException { // put the increase salary database-code in here } }); . . ``` You can look through a list of classic Design Patterns to find out which one this is.
**To expand further on [Ray Toal's original answer](https://stackoverflow.com/a/20931708/1134080),** it is worth noting that using anonymous inner class will help avoid creating a separate class file for each operation. So the original class with 10 or so functions can remain the same way, except being refactored to use the `Executor` pattern. Also, when using the `Executor` pattern, you have to take care of the usage of `this` in the original code. Assume the original functions are as follows: ``` public boolean operation1() { SQLiteDatabase database = this.getWritableDatabase(); try { //Code for Operation 1 return true; } catch (SQLiteException e) { Log.e(this.getClass().getName(), e.getMessage()); return false; } finally { database.close(); } } public boolean operation2() { SQLiteDatabase database = this.getWritableDatabase(); try { //Code for Operation 2 return true; } catch (SQLiteException e) { Log.e(this.getClass().getName(), e.getMessage()); return false; } finally { database.close(); } } ``` With the `Executor` class defined as follows: ``` public class Executor { public static boolean runOperation(SQLiteOpenHelper helper, Operation operation) { SQLiteDatabase database = helper.getWritableDatabase(); try { operation.run(database); return true; } catch (SQLiteException e) { Log.e(helper.getClass().getName(), e.getMessage()); return false; } finally { database.close(); } } } ``` And the `Operation` interface defined as follows: ``` public interface Operation { public void run(SQLiteDatabase database) throws SQLiteException; } ``` The original functions can now be rewritten as follows: ``` public boolean operation1() { return Executor.runOperation(this, new Operation() { public void run(SQLiteDatabase database) throws SQLiteException { //Code for Operation 1 } }); } public boolean operation2() { return Executor.runOperation(this, new Operation() { public void run(SQLiteDatabase database) throws SQLiteException { //Code for Operation 2 } }); } ``` *This expansion also corrects mistakes Ray has overlooked in his original answer.*
3
1
32,580,318
Please help me for How to convert data from {"rOjbectId":["abc","def",ghi","ghikk"]} to "["abc", "def", "ghi", "ghikk"] using ajax
2015/09/15
[ "https://Stackoverflow.com/questions/32580318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4003128/" ]
You can load a placeholder image, but then you must *load* that image (when you're already loading another image). If you load something like a spinner via a `GET` request, that should be ok since you can set cache headers from the server so the browser does not actually make any additional requests for that loading image. A way that Pinterest gets around this is by loading a solid color and the title of each of their posts in the post boxes while the images are loading, but now we're getting into a design discussion. There are multiple ways to skin a cat. Regarding loading several images, you have to understand a couple considerations: 1. The time it takes to fetch and download an image. 2. The time it takes to decode this image. 3. The maximum number of concurrent sockets you may have open on a page. If you don't have a ton of images that need to be loaded up front, consideration 3 is typically not a problem since you can *optimistically* load images under the fold, but if you have 100s of images on the page that need to be loaded quickly for a good user experience, then you may need to find a better solution. Why? Because you're incurring 100s of additional round trips to your server just load each image which makes up a small portion of the total loading spectrum (the spectrum being 100s of images). Not only that, but you're getting choked by the browser limitation of having X number of concurrent requests to fetch these images. If you have many small images, you may want to go with an approach similar to what [Dropbox describes here](https://blogs.dropbox.com/tech/2014/01/retrieving-thumbnails/). The basic gist is that you make one giant request for multiple thumbnails and then get a chunked encoding response back. That means that each packet on the response will contain the payload of each thumbnail. Usually this means that you're getting back the base64-encoded version of the payload, which means that, although you are reducing the number of round trips to your server to potentially just one, you will have a greater amount of data to transfer to the client (browser) since the string representation of the payload will be larger than the binary representation. Another issue is that you can no longer safely cache this request on the browser without using something like [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API). You also incur a decode cost when you set the background image of each `img` tag to a base64 string since the browser now must convert the string to binary and then have the `img` tag decode that as whatever file format it is (instead of skipping the `base64`->`binary` step altogether when you request an image and get a binary response back).
you can use placeholder image, which is very light weight and use that in place of each image. same time while loading page, you can load all the images in hidden div. then on document ready you can replace all the images with jQuery. e.g. HTML ---- ``` <img src="tiny_placeholder_image" alt="" data-src="original_image_src"/> <!-- upto N images --> <!-- images are loading in background --> <div style="display:none"> <img src="original_image_src" alt=""/> <!-- upto N images --> </div> ``` JavaScript ---------- ``` (function($){ // Now replace all data-src with src in images. })(jQuery); ```
2
0
32,580,318
Please help me for How to convert data from {"rOjbectId":["abc","def",ghi","ghikk"]} to "["abc", "def", "ghi", "ghikk"] using ajax
2015/09/15
[ "https://Stackoverflow.com/questions/32580318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4003128/" ]
I found a good solution on GitHub. Just use the **CSS** code below: ```css img[src=""], img:not([src]) { visibility: hidden; } ``` Link: <https://github.com/wp-media/rocket-lazy-load/issues/60>
you can use placeholder image, which is very light weight and use that in place of each image. same time while loading page, you can load all the images in hidden div. then on document ready you can replace all the images with jQuery. e.g. HTML ---- ``` <img src="tiny_placeholder_image" alt="" data-src="original_image_src"/> <!-- upto N images --> <!-- images are loading in background --> <div style="display:none"> <img src="original_image_src" alt=""/> <!-- upto N images --> </div> ``` JavaScript ---------- ``` (function($){ // Now replace all data-src with src in images. })(jQuery); ```
2
0
9,458,253
Perhaps I am worrying over nothing. I desire for data members to closely follow the RAII idiom. How can I initialise a protected pointer member in an abstract base class to null? I know it should be null, but wouldn't it be nicer to ensure that is universally understood? Putting initialization code outside of the initializer list has the potential to not be run. Thinking in terms of the assembly operations to allocate this pointer onto the stack, couldn't they be interrupted in much the same way (as the c'tor body) in multithreading environments or is stack expansion guaranteed to be atomic? If the destructor is guaranteed to run then might not the stack expansion have such a guarantee even if the processor doesn't perform it atomically? How did such a simple question get so expansive? Thanks. If I could avoid the std:: library that would be great, I am in a minimilist environment.
2012/02/26
[ "https://Stackoverflow.com/questions/9458253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/866333/" ]
I have had this problem in the past - and fixed it. The images you're displaying are much too large. I love using html or css to resize my images (because who wants to do it manually), but the fact remains that most browsers will hiccup when moving them around. I'm not sure why. With the exception of Opera, which usually sacrifices resolution and turns websites into garbage. Resize the largest images, and see if that helps.
Performance in JavaScript is slow, as you're going through many layers of abstraction to get any work done, and many manipulations with objects on the screen are happening in the background. Performance cannot be guaranteed from system to system. You'll find that with all jQuery animation, you will get a higher "frame rate" (not the right term here, but I can't think of a better one) on faster machines and better-performing browsers (such as Chrome) than you will on slower machines. If you are curious what all happens in the background when you set a scroll position, or other property, use one of the many tools for profiling your code. Google Chrome comes with one built-in, and for Firefox, you can use Firebug to give you some insight. See also this question: [What is the best way to profile javascript execution?](https://stackoverflow.com/questions/855126/what-is-the-best-way-to-profile-javascript-execution)
2
0
34,211,201
I have a Python script that uploads a Database file to my website every 5 minutes. My website lets the user query the Database using PHP. If a user tries to run a query while the database is being uploaded, they will get an error message > PHP Warning: SQLite3::prepare(): Unable to prepare statement: 11, database disk image is malformed in XXX on line 127 where line 127 is just the `prepare` function ``` $result = $db->prepare("SELECT * FROM table WHERE page_url_match = :pageurlmatch"); ``` Is there a way to test for this and retry the users request once the database is done uploading?
2015/12/10
[ "https://Stackoverflow.com/questions/34211201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2893712/" ]
First of all there is a weird thing with your implementation: you use a parameter `n` that you never use, but simply keep passing and you never modify. Secondly the second recursive call is incorrect: ``` else: m = y*power(y, x//2, n) #Print statement only used as check print(x, m) return m*m ``` If you do the math, you will see that you return: *(y yx//2)2=y2\*(x//2+1)* (mind the `//` instead of `/`) which is thus one *y* too much. In order to do this correctly, you should thus rewrite it as: ``` else: m = power(y, x//2, n) #Print statement only used as check print(x, m) return y*m*m ``` (so removing the `y*` from the `m` part and add it to the `return` statement, such that it is not squared). Doing this will make your implementation at least semantically sound. But it will not solve the performance/memory aspect. Your [comment](https://stackoverflow.com/questions/34211198/using-recursion-to-calculate-powers-of-large-digit-numbers#comment56167183_34211198) makes it clear that you want to do a modulo on the result, so this is probably *Project Euler*? The strategy is to make use of the fact that modulo is closed under multiplication. In other words the following holds: *(a b) mod c = ((a mod c) \* (b mod c)) mod c* You can use this in your program to prevent generating **huge numbers** and thus work with small numbers that require little computational effort to run. Another optimization is that you can simply use the square in your argument. So a faster implementation is something like: ``` def power(y, x, n): if x == 0: #base case return 1 elif (x%2==0): #x even return power((y*y)%n,x//2,n)%n else: #x odd return (y*power((y*y)%n,x//2,n))%n ``` If we do a small test with this function, we see that the two results are identical for small numbers (where the `pow()` can be processed in reasonable time/memory): `(12347**2742)%1009` returns `787L` and `power(12347,2742,1009)` `787`, so they generate the same result (of course this is no *proof*), that both are equivalent, it's just a short test that filters out obvious mistakes.
here is my approach accornding to the c version of this problem it works with both positives and negatives exposents: ``` def power(a,b): """this function will raise a to the power b but recursivelly""" #first of all we need to verify the input if isinstance(a,(int,float)) and isinstance(b,int): if a==0: #to gain time return 0 if b==0: return 1 if b >0: if (b%2==0): #this will reduce time by 2 when number are even and it just calculate the power of one part and then multiply if b==2: return a*a else: return power(power(a,b/2),2) else: #the main case when the number is odd return a * power(a, b- 1) elif not b >0: #this is for negatives exposents return 1./float(power(a,-b)) else: raise TypeError('Argument must be interfer or float') ```
2
0
38,921,847
I want to remove the card from the `@hand` array if it has the same rank as the given input. I'm looping through the entire array, why doesn't it get rid of the last card? Any help is greatly appreciated! Output: ``` 2 of Clubs 2 of Spades 2 of Hearts 2 of Diamonds 3 of Clubs 3 of Spades ------------ 2 of Clubs 2 of Spades 2 of Hearts 2 of Diamonds 3 of Spades ``` Code: ``` deck = Deck.new hand = Hand.new(deck.deal, deck.deal, deck.deal, deck.deal, deck.deal, deck.deal) puts hand.to_s hand.remove_cards("3") puts "------------" puts hand.to_s ``` Hand class: ``` class Hand def initialize(*cards) @hand = cards end def remove_cards(value) @hand.each_with_index do |hand_card, i| if hand_card.rank == value @hand.delete_at(i) end end end def to_s output = "" @hand.each do |card| output += card.to_s + "\n" end return output end end ``` Card class: ``` class Card attr_reader :rank, :suit def initialize(rank, suit) @rank = rank @suit = suit end def to_s "#{@rank} of #{@suit}" end end ```
2016/08/12
[ "https://Stackoverflow.com/questions/38921847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5140582/" ]
`remove_cards(value)` has an issue: one should not `delete` during iteration. The correct way would be to [`Array#reject!`](http://ruby-doc.org/core-2.3.1/Array.html#method-i-reject-21) cards from a hand: ``` def remove_cards(value) @hands.reject! { |hand_card| hand_card.rank == value } end ```
Your issue is in this line ``` @hands.each_with_index do |hand_card, i| ``` You have an instance variable `@hand`, not `@hands`
2
0
13,540,903
TextView.setAllCaps() started as of API 14. What is its equivalent for older APIs (e.g. 13 and lowers)? I cannot find such method on lower APIs. Is maybe setTransformationMethod() responsible for this on older APIs? If yes, how should I use it? `TextView.setTransformationMethod(new TransformationMethod() {...` is a bit confusing.
2012/11/24
[ "https://Stackoverflow.com/questions/13540903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/437039/" ]
Try this: ``` textView.setText(textToBeSet.toUpperCase()); ```
What about oldskool `strtoupper()`?
4
2
13,540,903
TextView.setAllCaps() started as of API 14. What is its equivalent for older APIs (e.g. 13 and lowers)? I cannot find such method on lower APIs. Is maybe setTransformationMethod() responsible for this on older APIs? If yes, how should I use it? `TextView.setTransformationMethod(new TransformationMethod() {...` is a bit confusing.
2012/11/24
[ "https://Stackoverflow.com/questions/13540903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/437039/" ]
What about oldskool `strtoupper()`?
Bottom line is that `toUpperCase()` is the solution. I can't object that. If you prefer doing the `setAllCaps()` with `TransformationMethod`, take a look at my [answer](https://stackoverflow.com/a/24025691/557179).
2
0
13,540,903
TextView.setAllCaps() started as of API 14. What is its equivalent for older APIs (e.g. 13 and lowers)? I cannot find such method on lower APIs. Is maybe setTransformationMethod() responsible for this on older APIs? If yes, how should I use it? `TextView.setTransformationMethod(new TransformationMethod() {...` is a bit confusing.
2012/11/24
[ "https://Stackoverflow.com/questions/13540903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/437039/" ]
Try this: ``` textView.setText(textToBeSet.toUpperCase()); ```
Bottom line is that `toUpperCase()` is the solution. I can't object that. If you prefer doing the `setAllCaps()` with `TransformationMethod`, take a look at my [answer](https://stackoverflow.com/a/24025691/557179).
4
0
6,126,126
If you declare an inheritance hierarchy where both the parent and child class have a static method of the same name and parameters\*, Visual Studio will raise warning [CS0108](http://msdn.microsoft.com/en-us/library/3s8070fc.aspx): Example: ``` public class BaseClass { public static void DoSomething() { } } public class SubClass : BaseClass { public static void DoSomething() { } } ``` `: warning CS0108: 'SubClass.DoSomething()' hides inherited member 'BaseClass.DoSomething()'. Use the new keyword if hiding was intended.` Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name: ``` BaseClass.DoSomething(); SubClass.DoSomething(); ``` or, unqualified in the class itself. In either case, there is no ambiguity as to which method is being called (i.e., no 'hiding'). \*Interestingly enough, the methods can differ by return type and still generate the same warning. However, if the method parameter types differ, the warning is not generated. Please note that I am not trying to create an argument for or discuss static inheritance or any other such nonsense.
2011/05/25
[ "https://Stackoverflow.com/questions/6126126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/533907/" ]
Members of the SubClass will not be able to access the DoSomething from BaseClass without explicitly indicating the class name. So it is effectively "hidden" to members of SubClass, but still accessible. For example: ``` public class SubClass : BaseClass { public static void DoSomething() { } public static void DoSomethingElse() { DoSomething(); // Calls SubClass BaseClass.DoSomething(); // Calls BaseClass } } ```
It's just a warning. The compiler just wants to make sure you intentionally used the same method name.
3
0
6,126,126
If you declare an inheritance hierarchy where both the parent and child class have a static method of the same name and parameters\*, Visual Studio will raise warning [CS0108](http://msdn.microsoft.com/en-us/library/3s8070fc.aspx): Example: ``` public class BaseClass { public static void DoSomething() { } } public class SubClass : BaseClass { public static void DoSomething() { } } ``` `: warning CS0108: 'SubClass.DoSomething()' hides inherited member 'BaseClass.DoSomething()'. Use the new keyword if hiding was intended.` Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name: ``` BaseClass.DoSomething(); SubClass.DoSomething(); ``` or, unqualified in the class itself. In either case, there is no ambiguity as to which method is being called (i.e., no 'hiding'). \*Interestingly enough, the methods can differ by return type and still generate the same warning. However, if the method parameter types differ, the warning is not generated. Please note that I am not trying to create an argument for or discuss static inheritance or any other such nonsense.
2011/05/25
[ "https://Stackoverflow.com/questions/6126126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/533907/" ]
Members of the SubClass will not be able to access the DoSomething from BaseClass without explicitly indicating the class name. So it is effectively "hidden" to members of SubClass, but still accessible. For example: ``` public class SubClass : BaseClass { public static void DoSomething() { } public static void DoSomethingElse() { DoSomething(); // Calls SubClass BaseClass.DoSomething(); // Calls BaseClass } } ```
> Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name. That is not true. You can call DoSomething from any inherited class name: ``` public Class A { public static void C() {...} } public Class B: A { } B.C() // Valid call! ``` That is why you are hiding C() if you declare the method with the same signature in B. Hope this helps.
3
2
6,126,126
If you declare an inheritance hierarchy where both the parent and child class have a static method of the same name and parameters\*, Visual Studio will raise warning [CS0108](http://msdn.microsoft.com/en-us/library/3s8070fc.aspx): Example: ``` public class BaseClass { public static void DoSomething() { } } public class SubClass : BaseClass { public static void DoSomething() { } } ``` `: warning CS0108: 'SubClass.DoSomething()' hides inherited member 'BaseClass.DoSomething()'. Use the new keyword if hiding was intended.` Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name: ``` BaseClass.DoSomething(); SubClass.DoSomething(); ``` or, unqualified in the class itself. In either case, there is no ambiguity as to which method is being called (i.e., no 'hiding'). \*Interestingly enough, the methods can differ by return type and still generate the same warning. However, if the method parameter types differ, the warning is not generated. Please note that I am not trying to create an argument for or discuss static inheritance or any other such nonsense.
2011/05/25
[ "https://Stackoverflow.com/questions/6126126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/533907/" ]
Members of the SubClass will not be able to access the DoSomething from BaseClass without explicitly indicating the class name. So it is effectively "hidden" to members of SubClass, but still accessible. For example: ``` public class SubClass : BaseClass { public static void DoSomething() { } public static void DoSomethingElse() { DoSomething(); // Calls SubClass BaseClass.DoSomething(); // Calls BaseClass } } ```
Visual Studio, and Philippe, are saying it's a warning so your code will compile and run. However, 'CodeNaked' nicely demonstrates why it is hidden. This code compiles without throwing errors or warnings. Thanks to 'CodeNaked' ``` public class BaseClass { public virtual void DoSomething() { } } public class SubClass : BaseClass { public override void DoSomething() { } public void DoSomethingElse() { DoSomething(); // Calls SubClass base.DoSomething(); // Calls BaseClass } } ``` EDIT: With Travis's code I can do the following: BaseClass.DoSomething(); SubClass.DoSomething(); And it works fine. Thing is though you might wonder why SubClass is inheriting from BaseClass and both are implementing the same static methods. Actually that's not true, both classes are implementing methods that could be completely different but have the same name. That could be potential confusing.
3
0
6,126,126
If you declare an inheritance hierarchy where both the parent and child class have a static method of the same name and parameters\*, Visual Studio will raise warning [CS0108](http://msdn.microsoft.com/en-us/library/3s8070fc.aspx): Example: ``` public class BaseClass { public static void DoSomething() { } } public class SubClass : BaseClass { public static void DoSomething() { } } ``` `: warning CS0108: 'SubClass.DoSomething()' hides inherited member 'BaseClass.DoSomething()'. Use the new keyword if hiding was intended.` Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name: ``` BaseClass.DoSomething(); SubClass.DoSomething(); ``` or, unqualified in the class itself. In either case, there is no ambiguity as to which method is being called (i.e., no 'hiding'). \*Interestingly enough, the methods can differ by return type and still generate the same warning. However, if the method parameter types differ, the warning is not generated. Please note that I am not trying to create an argument for or discuss static inheritance or any other such nonsense.
2011/05/25
[ "https://Stackoverflow.com/questions/6126126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/533907/" ]
> Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name. That is not true. You can call DoSomething from any inherited class name: ``` public Class A { public static void C() {...} } public Class B: A { } B.C() // Valid call! ``` That is why you are hiding C() if you declare the method with the same signature in B. Hope this helps.
It's just a warning. The compiler just wants to make sure you intentionally used the same method name.
2
0
6,126,126
If you declare an inheritance hierarchy where both the parent and child class have a static method of the same name and parameters\*, Visual Studio will raise warning [CS0108](http://msdn.microsoft.com/en-us/library/3s8070fc.aspx): Example: ``` public class BaseClass { public static void DoSomething() { } } public class SubClass : BaseClass { public static void DoSomething() { } } ``` `: warning CS0108: 'SubClass.DoSomething()' hides inherited member 'BaseClass.DoSomething()'. Use the new keyword if hiding was intended.` Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name: ``` BaseClass.DoSomething(); SubClass.DoSomething(); ``` or, unqualified in the class itself. In either case, there is no ambiguity as to which method is being called (i.e., no 'hiding'). \*Interestingly enough, the methods can differ by return type and still generate the same warning. However, if the method parameter types differ, the warning is not generated. Please note that I am not trying to create an argument for or discuss static inheritance or any other such nonsense.
2011/05/25
[ "https://Stackoverflow.com/questions/6126126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/533907/" ]
> Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name. That is not true. You can call DoSomething from any inherited class name: ``` public Class A { public static void C() {...} } public Class B: A { } B.C() // Valid call! ``` That is why you are hiding C() if you declare the method with the same signature in B. Hope this helps.
Visual Studio, and Philippe, are saying it's a warning so your code will compile and run. However, 'CodeNaked' nicely demonstrates why it is hidden. This code compiles without throwing errors or warnings. Thanks to 'CodeNaked' ``` public class BaseClass { public virtual void DoSomething() { } } public class SubClass : BaseClass { public override void DoSomething() { } public void DoSomethingElse() { DoSomething(); // Calls SubClass base.DoSomething(); // Calls BaseClass } } ``` EDIT: With Travis's code I can do the following: BaseClass.DoSomething(); SubClass.DoSomething(); And it works fine. Thing is though you might wonder why SubClass is inheriting from BaseClass and both are implementing the same static methods. Actually that's not true, both classes are implementing methods that could be completely different but have the same name. That could be potential confusing.
2
0
14,847,913
I try to implement the zoom in/out by spread/pinch gesture and the drag and drop functions on a Relative Layout. This is the code of my OnPinchListener to handle the zoom effect. The **mainView** is the RelativeLayout defined in the layout xml file. I implement the touch listener in the **fakeview** which should be in front of all view. The touch event will change the **mainview** according to the code. **I want to ask if it is possible to get the actual left, top, width and height after the scale?** It always return 0,0 for left and top, and the original width and height after zoom. Thanks very much! ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linear_layout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <RelativeLayout android:id="@+id/zoomable_relative_layout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" > <ImageView android:id="@+id/imageView1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:src="@drawable/background" /> </RelativeLayout> <RelativeLayout android:id="@+id/relative_layout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:orientation="vertical" > </RelativeLayout> </RelativeLayout> public class MainActivity extends Activity { //ZoomableRelativeLayout mainView = null; RelativeLayout mainView = null; RelativeLayout rl = null; public static final String TAG = "ZoomText." + MainActivity.class.getSimpleName(); private int offset_x; private int offset_y; private boolean dragMutex = false; RelativeLayout fakeView = null; float width = 0, height = 0; private OnTouchListener listener = new OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent event) { // Log.e(TAG, event + ""); // Log.e(TAG, "Pointer Count = "+event.getPointerCount()); Log.e(TAG, event.getX() + "," + event.getY() + "|" + mainView.getX() + "(" + mainView.getWidth() + ")," + mainView.getY() + "(" + mainView.getHeight() + ")"); if (event.getX() >= mainView.getLeft() && event.getX() <= mainView.getLeft() + mainView.getWidth() && event.getY() >= mainView.getTop() && event.getY() <=mainView.getTop() + mainView.getHeight()) if (event.getPointerCount() > 1) { return scaleGestureDetector.onTouchEvent(event); } else { return llListener.onTouch(arg0, event); } return false; } }; private ScaleGestureDetector scaleGestureDetector; private OnTouchListener llListener = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub // Log.d(TAG, event + ",LL"); switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: offset_x = (int) event.getX(); offset_y = (int) event.getY(); // Log.e(TAG, offset_x + "," + offset_y); dragMutex = true; return true; case MotionEvent.ACTION_MOVE: // Log.e(TAG, "Finger down"); int x = (int) event.getX() - offset_x; int y = (int) event.getY() - offset_y; Log.e(TAG, event.getX() + "," + event.getY()); float _x = mainView.getX(); float _y = mainView.getY(); mainView.setX(_x + x); mainView.setY(_y + y); offset_x = (int) event.getX(); offset_y = (int) event.getY(); return true; case MotionEvent.ACTION_UP: dragMutex = false; return true; } return false; } }; private OnDragListener dragListener = new View.OnDragListener() { @Override public boolean onDrag(View arg0, DragEvent arg1) { Log.e(TAG, "DRAG Listener = " + arg1); return false; } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mainView = (RelativeLayout) findViewById(R.id.zoomable_relative_layout); // mainView.setOnTouchListener(new OnPinchListener()); // mainView.setOnTouchListener(listener); scaleGestureDetector = new ScaleGestureDetector(this, new OnPinchListener()); rl = (RelativeLayout) findViewById(R.id.linear_layout); mainView.setOnDragListener(dragListener); // mainView.setOnTouchListener(llListener); fakeView = (RelativeLayout) findViewById(R.id.relative_layout); fakeView.setOnTouchListener(listener); } class OnPinchListener extends SimpleOnScaleGestureListener { float startingSpan; float endSpan; float startFocusX; float startFocusY; public boolean onScaleBegin(ScaleGestureDetector detector) { startingSpan = detector.getCurrentSpan(); startFocusX = detector.getFocusX(); startFocusY = detector.getFocusY(); return true; } public boolean onScale(ScaleGestureDetector detector) { // mainView.scale(detector.getCurrentSpan() / startingSpan, // startFocusX, startFocusY); // if(width==0) // width = mainView.getWidth(); // if(height==0) // height = mainView.getHeight(); mainView.setPivotX(startFocusX); mainView.setPivotY(startFocusY); mainView.setScaleX(detector.getCurrentSpan() / startingSpan); mainView.setScaleY(detector.getCurrentSpan() / startingSpan); // LayoutParams para = mainView.getLayoutParams(); // width*=detector.getCurrentSpan() / startingSpan; // height*=detector.getCurrentSpan() / startingSpan; // para.width = (int)width; // para.height = (int)height; // mainView.setLayoutParams(para); return true; } public void onScaleEnd(ScaleGestureDetector detector) { //mainView.restore(); mainView.invalidate(); Log.e(TAG, mainView.getLeft()+","+mainView.getRight()); } } } ```
2013/02/13
[ "https://Stackoverflow.com/questions/14847913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2067294/" ]
you need to get the transformation matrix and use that to transform your original points. so something like this (after you do the scaling): ``` Matrix m = view.getMatrix(); //gives you the transform matrix m.mapPoints(newPoints, oldPoints); //transform the original points. ```
This is how I solved it in my case (`getViewRect` should be called after view was laid out, for example through `view.post(Runnable)`, so `view.getWidth()/getHeight()` returns actual values): ``` public static Rect getViewRect(View view) { Rect outRect = new Rect(); outRect.right = (int)(view.getWidth() * getScalelX(view)); outRect.bottom = (int)(view.getHeight() * getScalelY(view)); int[] location = new int[2]; view.getLocationOnScreen(location); outRect.offset(location[0], location[1]); return outRect; } public static float getScalelX(View view) { float scaleX = view.getScaleX(); view = getParent(view); while (view != null) { scaleX *= view.getScaleX(); view = getParent(view); } return scaleX; } public static float getScalelY(View view) { float scaleX = view.getScaleY(); view = getParent(view); while (view != null) { scaleX *= view.getScaleY(); view = getParent(view); } return scaleX; } public static ViewGroup getParent(View view) { if (view == null) { return null; } ViewParent parent = view.getParent(); if (parent instanceof View) { return (ViewGroup) parent; } return null; } ``` however it just turned out that android 3.1 (probably 3.0 also) doesn't take in account scale factor while dealing with `getLocationOnScreen` method. I'm gonna to manually scale the rect before returning it from my `getViewRect(View)` function in case of android 3.1 api like this: ``` public static void scaleRect(Rect rect, float scaleX, float scaleY, float pivotX, float pivotY) { rect.left = (int) ((rect.left - pivotX) * scaleX + pivotX); rect.right = (int) ((rect.right - pivotX) * scaleX + pivotX); rect.top = (int) ((rect.top - pivotY) * scaleY + pivotY); rect.bottom = (int) ((rect.bottom - pivotY) * scaleY + pivotY); } ``` However one should know a pivot coordinates for every view in the hierarchy from the current view to the root and corresponding zoom levels to handle this transformation correctly. If someone has any straightforward solution it will be appreciated **EDIT:** This is how I modified the `getViewRect(View)` method so it works on 3.1 also: ``` public static Rect getViewRect(View view) { Rect outRect = new Rect(); if(Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR2){ outRect.right = (int)(view.getWidth() * getScalelX(view)); outRect.bottom = (int)(view.getHeight() * getScalelY(view)); int[] location = new int[2]; view.getLocationOnScreen(location); outRect.offset(location[0], location[1]); } else { outRect.right = view.getWidth(); outRect.bottom = view.getHeight(); int[] location = new int[2]; view.getLocationOnScreen(location); outRect.offset(location[0], location[1]); View parent = view; while(parent != null){ parent.getLocationOnScreen(location); scaleRect(outRect, parent.getScaleX(), parent.getScaleY(), parent.getPivotX() + location[0], parent.getPivotY() + location[1]); parent = getParent(parent); } } return outRect; } ``` I think `if`- clause could be removed so that the second branch (`else`) should work for all versions. However I prefer to use straightforward solution (the first branch of the `if`) so that the second is just a workaround :)
1
0
3,851,022
$A^{2}-2A=\begin{bmatrix} 5 & -6 \\ -4 & 2 \end{bmatrix}$ Can someone help me solve this? I've been trying to solve it for a while, but no matter what I try, the only information that I manage to get about A is that if $A=\begin{bmatrix} a & b \\ c & d \end{bmatrix}$ then $c=\frac{2b}{3}$. Any help would be appreciated, thanks!
2020/10/04
[ "https://math.stackexchange.com/questions/3851022", "https://math.stackexchange.com", "https://math.stackexchange.com/users/832188/" ]
Denote by $I$ the identity matrix. Then, completing squares you can write $$A^2 - 2A = A^2 -2IA + I^2 -I^2 = (A-I)^2 -I^2.$$ Hence, your equation is equivalent to $$(A-I)^2 = X + I$$ since $I^2 = I$. Denote by $Y=X+I$ the new matrix (which is known). You want to find $B$ such that $B^2=Y.$ Here, I recommend to diagonalize $Y$, i.e. find $U$ and diagonal $D$ such that $$Y=UDU^{-1}.$$ Thus, $$B= Y^{1/2} = UD^{1/2}U^{-1}.$$ See [this link](https://en.wikipedia.org/wiki/Square_root_of_a_matrix#By_diagonalization) for more information. Once you have found $B$, $A$ is given by $$A=B+I.$$ Remember that you may have more than one square root of the matrix $Y$.
$$A^{2}-2A+I=\begin{bmatrix} 5 & -6 \\ -4 & 2 \end{bmatrix}+I \\ (A-I)^2=\begin{bmatrix} 6 & -6 \\ -4 & 3 \end{bmatrix} $$ We know that, if$$\begin{align}M&=PDP^{-1} \\ M^n&=PD^nP^{-1}\end{align}$$ Let $B=A-I$ then, $$B=\sqrt{\begin{bmatrix} 6 & -6 \\ -4 & 3 \end{bmatrix}}$$ Diagonalise $B^2$ as, $$\left(\begin{matrix} \frac{\sqrt{105}-3}{8} & \frac{-\sqrt{105}-3}{8} \\ 1 & 1 \end{matrix}\right).\left(\begin{matrix} \frac{-\sqrt{105}+9}{2} & 0 \\ 0 & \frac{\sqrt{105}+9}{2} \end{matrix}\right).\left(\begin{matrix} \frac{4\*\sqrt{105}}{105} & \frac{\sqrt{105}+35}{70} \\ \frac{-4\*\sqrt{105}}{105} & \frac{-\sqrt{105}+35}{70} \end{matrix}\right)$$ From this, $$B=\left(\begin{matrix} \frac{\sqrt{105}-3}{8} & \frac{-\sqrt{105}-3}{8} \\ 1 & 1 \end{matrix}\right).\left(\begin{matrix} \frac{-\sqrt{105}+9}{2} & 0 \\ 0 & \frac{\sqrt{105}+9}{2} \end{matrix}\right)^{\frac{1}{2}}.\left(\begin{matrix} \frac{4\*\sqrt{105}}{105} & \frac{\sqrt{105}+35}{70} \\ \frac{-4\*\sqrt{105}}{105} & \frac{-\sqrt{105}+35}{70} \end{matrix}\right)$$ From this $$A=\left(\begin{matrix} \frac{\sqrt{105}-3}{8} & \frac{-\sqrt{105}-3}{8} \\ 1 & 1 \end{matrix}\right).\left(\begin{matrix} \frac{-\sqrt{105}+9}{2} & 0 \\ 0 & \frac{\sqrt{105}+9}{2} \end{matrix}\right)^{\frac{1}{2}}.\left(\begin{matrix} \frac{4\*\sqrt{105}}{105} & \frac{\sqrt{105}+35}{70} \\ \frac{-4\*\sqrt{105}}{105} & \frac{-\sqrt{105}+35}{70} \end{matrix}\right)+\left(\begin{matrix} 1&0\\0&1\end{matrix}\right)$$ The required matrix is approximately $$\tiny{\left(\begin{matrix} \frac{\left(481173769149-31173769149\*i\right)\*\sqrt{105}+\left(20341081920215+1091081920215\*i\right)}{3500000000000} & \frac{\left(-481173769149+31173769149\*i\right)\*\sqrt{105}+875000000000}{875000000000} \\ \frac{\left(-160391256383+10391256383\*i\right)\*\sqrt{105}}{437500000000} & \frac{\left(-481173769149+31173769149\*i\right)\*\sqrt{105}+\left(20341081920215+1091081920215\*i\right)}{3500000000000} \end{matrix}\right)}$$
2
0
3,851,022
$A^{2}-2A=\begin{bmatrix} 5 & -6 \\ -4 & 2 \end{bmatrix}$ Can someone help me solve this? I've been trying to solve it for a while, but no matter what I try, the only information that I manage to get about A is that if $A=\begin{bmatrix} a & b \\ c & d \end{bmatrix}$ then $c=\frac{2b}{3}$. Any help would be appreciated, thanks!
2020/10/04
[ "https://math.stackexchange.com/questions/3851022", "https://math.stackexchange.com", "https://math.stackexchange.com/users/832188/" ]
Denote by $I$ the identity matrix. Then, completing squares you can write $$A^2 - 2A = A^2 -2IA + I^2 -I^2 = (A-I)^2 -I^2.$$ Hence, your equation is equivalent to $$(A-I)^2 = X + I$$ since $I^2 = I$. Denote by $Y=X+I$ the new matrix (which is known). You want to find $B$ such that $B^2=Y.$ Here, I recommend to diagonalize $Y$, i.e. find $U$ and diagonal $D$ such that $$Y=UDU^{-1}.$$ Thus, $$B= Y^{1/2} = UD^{1/2}U^{-1}.$$ See [this link](https://en.wikipedia.org/wiki/Square_root_of_a_matrix#By_diagonalization) for more information. Once you have found $B$, $A$ is given by $$A=B+I.$$ Remember that you may have more than one square root of the matrix $Y$.
$\newcommand{\Tr}{\mathrm{Tr}\,}$ Let $Y=A-I$, $X=B+I$, $B$ for the rhs matrix. Then $\Tr X = 9$, $\det X=-6$, and we need to solve $$Y^2=X$$ for $Y$. Write $\alpha=\Tr Y$, $\beta = \det Y$. Then $$Y^2-\alpha Y + \beta I=0$$ or $$\alpha Y = \beta I + X$$ so that finding allowed values of $\alpha$, $\beta$ solves the problem. Take the trace and determinant of both sides of $Y^2=X$. Then $$\begin{align} \alpha^2 - 2\beta &= \Tr X = 9 \\ \beta^2 &= \det X = -6 \end{align}$$ which means that $$\begin{align} \alpha A &= (\alpha+\beta +1)I + B \\ \alpha^2 & = 9 +2\beta \\ \beta^2 &= -6\text{.} \end{align}$$ Note that there are four solutions.
2
0
68,767,520
I have a discord bot that gets info from an API. The current issue I'm having is actually getting the information to be sent when the command is run. ``` const axios = require('axios'); axios.get('https://mcapi.us/server/status?ip=asean.my.to') .then(response => { console.log(response.data); }); module.exports = { name: 'serverstatus', description: 'USes an API to grab server status ', execute(message, args) { message.channel.send(); }, }; ```
2021/08/13
[ "https://Stackoverflow.com/questions/68767520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15076973/" ]
probably your page is refreshed, try to use preventDefault to prevent the refresh ``` $('#submit').click(function(event){ //your code here event.preventDefault(); } ```
You have a button with type `"submit"`. ```html <input type="submit" id="submit" value="Save"> ``` As the click-event occurs on this button, your form will be send to the server. You have no action attribute defined on your form, so it redirects after submit to the same URL. As [Sterko](https://stackoverflow.com/users/13474687/sterko) stated, you could use a event-handler to prevent the submission of your form due to the submit button.
3
0
238,163
I have Echo's buried in code all over my notebook, I'd like a flag to turn them all on or off globally. * Sure `Unprotect[Echo];Echo=Identity` would disable them, but then you can't re-enable them * A solution that works for all the various types of Echos (EchoName, EchoEvaluation, ...) would be nice * `QuietEcho` doesn't work because I'd have to write it add it around every blob of code
2021/01/13
[ "https://mathematica.stackexchange.com/questions/238163", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/403/" ]
[`Echo`](http://reference.wolfram.com/language/ref/Echo) has an autoload, so you need to make sure the symbol is autoloaded before you modify its values: ``` DisableEcho[] := (Unprotect[Echo]; Echo; Echo = #&; Protect[Echo];) EnableEcho[] := (Unprotect[Echo]; Echo=.; Protect[Echo];) ``` Test: ``` DisableEcho[] Echo[3] EnableEcho[] Echo[3, "EchoLabel"] ``` > 3 > EchoLabel 3 > 3
I would recommend using `QuietEcho` rather than redefining `Echo`: ``` In[62]:= $Pre = QuietEcho; In[63]:= Echo[3] Out[63]= 3 ``` This has the added benefit of disabling printing for all `Echo` functions, not just `Echo`.
5
2
29,922,241
Here is my Database: `bott_no_mgmt_data` ``` random_no ; company_id ; bottle_no ; date ; returned ; returned_to_stock ; username 30201 ; MY COMP ; 1 ; 2015-04-28 ; 10 ; NULL ; ANDREW 30202 ; MY COMP ; 2 ; 2015-04-28 ; 10 ; NULL ; ANDREW 30205 ; MY COMP ; 5 ; 2015-04-28 ; 10 ; NULL ; ANDREW 30208 ; MY COMP ; 8 ; 2015-04-28 ; 10 ; NULL ; ANDREW 30209 ; MY COMP ; 9 ; 2015-04-28 ; 10 ; NULL ; ANDREW 30210 ; MY COMP ; 10 ; 2015-04-28 ; 10 ; NULL ; ANDREW 30211 ; MY COMP ; 1 ; 2015-04-29 ; 20 ; NULL ; ANDREW 30212 ; MY COMP ; 2 ; 2015-04-29 ; 20 ; NULL ; ANDREW 30213 ; MY COMP ; 9 ; 2015-04-29 ; 30 ; NULL ; ANDREW 30214 ; MY COMP ; 10 ; 2015-04-29 ; 30 ; NULL ; ANDREW ``` I have successfully pulled all the entire unique rows from `bott_no_mgmt_data` where the field `random_no` is highest and `bottle_no` is unique with the following code: ``` select yt.* from bott_no_mgmt_data yt<br> inner join(select bottle_no, max(random_no) random_no from bott_no_mgmt_data WHERE username = 'ANDREW' group by bottle_no) ss on yt.bottle_no = ss.bottle_no and yt.random_no = ss.random_no where returned < 15 and date > '2015-04-01' ``` So for example one of the rows it returns will be ``` 30214;MY COMP;10;2015-04-29;30;NULL;ANDREW ``` and NOT ``` 30210;MY COMP;10;2015-04-28;10;NULL;ANDREW ``` because while their bottleno's are the same the former's random\_no is higher. My Problem: I now wish to compare each returned rows 'bottleno' with another table 'sample' which simply contains field 'bottleno' with a list of bottle numbers. I wish to compare them and only return those that match. I assume we would then 'LEFT JOIN' the results above with database 'sample' as below: ``` select yt.* from bott_no_mgmt_data yt<br> inner join(select bottle_no, max(random_no) random_no from bott_no_mgmt_data WHERE username = 'ANDREW' group by bottle_no) ss on yt.bottle_no = ss.bottle_no and yt.random_no = ss.random_no where returned < 15 and date > '2015-04-01' LEFT JOIN sample ON sample.bottleno = yt.bottle_no ``` The extra left join gives me an error > 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN sample ON sample.bottleno = yt.bottleno WHERE sample.bottleno IS NULL ' at line 7
2015/04/28
[ "https://Stackoverflow.com/questions/29922241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4842148/" ]
All joins should be written before Where clause as Daan mentions: ``` select yt.* from bott_no_mgmt_data yt inner join( select bottle_no, max(random_no) random_no from bott_no_mgmt_data WHERE username = 'ANDREW' group by bottle_no ) ss on yt.bottle_no = ss.bottle_no and yt.random_no = ss.random_no LEFT JOIN sample ON sample.bottleno = yt.bottle_no where returned < 15 and date > '2015-04-01' ```
A couple of things. You don't need that first inner join at all, it's pointless. Also, you said "I wish to compare them and only return those that match." - so that means you want INNER JOIN not LEFT JOIN. ``` SELECT MAX(random_no) AS random_no, company_id, yt.bottle_no, `date`, returned, username FROM bott_no_mgmt_data yt INNER JOIN sample ON sample.bottle_no=yt.bottle_no WHERE yt.username = 'ANDREW' AND yt.returned < 15 AND yt.date > '2015-04-01' GROUP BY company_id, yt.bottle_no, `date`, returned, username ```
0
-1
17,435,721
I have a project with multiple modules say "Application A" and "Application B" modules (these are separate module with its own pom file but are not related to each other). In the dev cycle, each of these modules have its own feature branch. Say, ``` Application A --- Master \ - Feature 1 Application B --- Master \ - Feature 1 ``` Say Application A is independent and has its own release cycle/version. Application B uses Application A as a jar. And is defined in its pom dependency. Now, both teams are working on a feature branch say "Feature 1". What is the best way to setup Jenkins build such that, Build job for Application B is able to use the latest jar from "Feature 1" branch of Application A. Given Feature 1 is not allowed to deploy its artifacts to maven repository. Somehow I want the jar from Application A's Feature 1 branch to be supplied as the correct dependency for Application B?
2013/07/02
[ "https://Stackoverflow.com/questions/17435721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/710802/" ]
You can do this with a before update trigger. You would use such a trigger to assign the value of `offer_nr` based on the historical values. The key code would be: ``` new.offer_nr = (select coalesce(1+max(offer_nr), 1) from offers o where o.company_id = new.company_id ) ``` You might also want to have `before update` and `after delete` triggers, if you want to keep the values in order. Another alternative is to assign the values when you query. You would generally do this using a variable to hold and increment the count.
Don't make it this way. Have autoincremented company ids as well as independent order ids. That's how it works. There is no such thing like "number" in database. Numbers appears only at the time of select.
1
-1
35,029,058
HTML CODE ``` <select class="form-control" name="min_select[]"> <option value="15">15</option> <option value="30">30</option> </select> ``` JQuery Code ``` var val1[]; $('select[name="min_select[]"] option:selected').each(function() { val1.push($(this).val()); }); ``` when i run this code I get empty val array
2016/01/27
[ "https://Stackoverflow.com/questions/35029058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4089992/" ]
The declaration array syntax is in correct.Please check the below code ``` var val1=[]; $('select[name="min_select[]"] option:selected').each(function() { val1.push($(this).val()); }); ```
You can try the following **HTML** ``` <select class="form-control min-select" name="min_select[]"> <option value="15">15</option> <option value="30">30</option> </select> ``` **JQUERY** ``` var values = []; $("select.min-select").each(function(i, sel){ var selectedVal = $(sel).val(); values.push(selectedVal); }); ``` Is min\_select[] a multiple choice select?
4
1
35,029,058
HTML CODE ``` <select class="form-control" name="min_select[]"> <option value="15">15</option> <option value="30">30</option> </select> ``` JQuery Code ``` var val1[]; $('select[name="min_select[]"] option:selected').each(function() { val1.push($(this).val()); }); ``` when i run this code I get empty val array
2016/01/27
[ "https://Stackoverflow.com/questions/35029058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4089992/" ]
The declaration array syntax is in correct.Please check the below code ``` var val1=[]; $('select[name="min_select[]"] option:selected').each(function() { val1.push($(this).val()); }); ```
To get the selected value, whether it is multiselect or single select, use jQuery [`.val()`](http://api.jquery.com/val/) method. If it is a multiselect, it will return an array of the selected values. See [jsfiddle for demo](https://jsfiddle.net/txk25c4c/). Check console log
4
1
35,029,058
HTML CODE ``` <select class="form-control" name="min_select[]"> <option value="15">15</option> <option value="30">30</option> </select> ``` JQuery Code ``` var val1[]; $('select[name="min_select[]"] option:selected').each(function() { val1.push($(this).val()); }); ``` when i run this code I get empty val array
2016/01/27
[ "https://Stackoverflow.com/questions/35029058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4089992/" ]
This will also work ``` var val1= $("select[name=\'min_select[]\']").map(function() { return $(this).val(); }).toArray(); ```
You can try the following **HTML** ``` <select class="form-control min-select" name="min_select[]"> <option value="15">15</option> <option value="30">30</option> </select> ``` **JQUERY** ``` var values = []; $("select.min-select").each(function(i, sel){ var selectedVal = $(sel).val(); values.push(selectedVal); }); ``` Is min\_select[] a multiple choice select?
4
1
35,029,058
HTML CODE ``` <select class="form-control" name="min_select[]"> <option value="15">15</option> <option value="30">30</option> </select> ``` JQuery Code ``` var val1[]; $('select[name="min_select[]"] option:selected').each(function() { val1.push($(this).val()); }); ``` when i run this code I get empty val array
2016/01/27
[ "https://Stackoverflow.com/questions/35029058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4089992/" ]
This will also work ``` var val1= $("select[name=\'min_select[]\']").map(function() { return $(this).val(); }).toArray(); ```
To get the selected value, whether it is multiselect or single select, use jQuery [`.val()`](http://api.jquery.com/val/) method. If it is a multiselect, it will return an array of the selected values. See [jsfiddle for demo](https://jsfiddle.net/txk25c4c/). Check console log
4
1
28,808,099
I am writing a script which will pick the last created file for the given process instance. The command I use in my script is ``` CONSOLE_FILE=`ls -1 "$ABP_AJTUH_ROOT/console/*${INSTANCE}*" | tail -1` ``` but while the script is getting executed, the above command changes to ``` ls -1 '....../console/*ABP*' ``` because of the single quotes, `*` is not being treated as a wildcard character and it is giving output like: ``` ls -1 $ABP_AJTUH_ROOT/console/*${INSTANCE}* | tail -1 + ls -1 '/tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/*UHMF_RT_1085*' + tail -1 ls: /tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/*UHMF_RT_1085*: No such file or directory + CONSOLE_FILE='' ``` --- it is working on command line after removing ' from the command but not working while using in script as mentioned above ``` tc1@gircap01!DEV:devtc1/Users/RB/AIMOS_CLEANUP_CANSUB> ls -l '/tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/*UHMF_RT_1085*' ls: /tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/*UHMF_RT_1085*: No such file or directory devtc1@gircap01!DEV:devtc1/Users/RB/AIMOS_CLEANUP_CANSUB> ls -l /tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/*UHMF_RT_1085* -rw-r--r-- 1 devtc1 aimsys 72622 Feb 17 20:55 /tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/ADJ1UHMINFUL_UHMF_RT_1085_console_20150217_205519.log -rw-r--r-- 1 devtc1 aimsys 177039 Feb 17 21:02 /tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/ADJ1UHMINFUL_UHMF_RT_1085_console_20150217_210203.log ```
2015/03/02
[ "https://Stackoverflow.com/questions/28808099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4623068/" ]
You cannot use double quotes around the wildcard, because that turns the asterisks into literal characters. ``` CONSOLE_FILE=`ls -1 "$ABP_AJTUH_ROOT"/console/*"$INSTANCE"* | tail -1` ``` should work, but see the caveats against <http://mywiki.wooledge.org/ParsingLs> and generally <http://mywiki.wooledge.org/BashPitfalls>
Try ``` CONSOLE_FILE=`eval ls -1 "$ABP_AJTUH_ROOT/console/*${INSTANCE}*" | tail -1` ``` Also, if you want the last created file, use `ls -1tr`
1
0
60,744,543
I'm trying to get the Download Folder to show on my file explorer. However on Android 9, when I use the getexternalstoragedirectory() method is showing self and emulated directories only and if I press "emulated" I cannot see more folders, it shows an empty folder. So this is how I'm getting the path, it's working fine in other Android versions but Android 9. Any guide would be appreciated ``` val dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath ```
2020/03/18
[ "https://Stackoverflow.com/questions/60744543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10871734/" ]
This is because [dictionaries](https://docs.julialang.org/en/v1/base/collections/#Dictionaries-1) in Julia (`Dict`) are not ordered: each dictionary maintains a *set* of keys. The order in which one gets keys when one iterates on this set is not defined, and can vary as one inserts new entries. There are two things that one can do to ensure that one iterates on dictionary entries in a specific order. The first method is to get the set of keys (using [`keys`](https://docs.julialang.org/en/v1/base/collections/#Base.keys)) and sort it yourself, as has been proposed in another answer: ``` julia> fruits = Dict("Mangoes" => 5, "Pomegranates" => 4, "Apples" => 8); julia> for key in sort!(collect(keys(fruits))) val = fruits[key] println("$key => $val") end Apples => 8 Mangoes => 5 Pomegranates => 4 ``` That being said, if the order of keys is important, one might want to reflect that fact in the type system by using an *ordered* dictionary ([OrderedDict](https://juliacollections.github.io/OrderedCollections.jl/latest/ordered_containers.html#OrderedDicts-and-OrderedSets-1)), which is a data structure in which the order of entries is meaningful. More precisely, an `OrderedDict` preserves the order in which its entries have been inserted. One can either create an `OrderedDict` from scratch, taking care of inserting keys in order, and the order will be preserved. Or one can create an `OrderedDict` from an existing `Dict` simply using `sort`, which will sort entries in ascending order of their key: ``` julia> using OrderedCollections julia> fruits = Dict("Mangoes" => 5, "Pomegranates" => 4, "Apples" => 8); julia> ordered_fruits = sort(fruits) OrderedDict{String,Int64} with 3 entries: "Apples" => 8 "Mangoes" => 5 "Pomegranates" => 4 julia> keys(ordered_fruits) Base.KeySet for a OrderedDict{String,Int64} with 3 entries. Keys: "Apples" "Mangoes" "Pomegranates" ```
Try this: ``` fruits = Dict("Mangoes" => 5, "Pomegranates" => 4, "Apples" => 8); for key in sort(collect(keys(fruits))) println("$key => $(fruits[key])") end ``` It gives this result: ``` Apples => 8 Mangoes => 5 Pomegranates => 4 ```
4
2
5,803,170
I have encountered a problem when trying to select data from a table in MySQL in Java by a text column that is in utf-8. The interesting thing is that with code in Python it works well, in Java it doesn't. The table looks as follows: ``` CREATE TABLE `x` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT, `text` varchar(255) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; ``` The query looks like this: ``` SELECT * FROM x WHERE text = 'ěščřž'" ``` The Java code that doesn't work as exptected is the following: ``` public class test { public static void main(String [] args) { java.sql.Connection conn = null; System.out.println("SQL Test"); try { Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = java.sql.DriverManager.getConnection( "jdbc:mysql://127.0.0.1/x?user=root&password=root&characterSet=utf8&useUnicode=true&characterEncoding=utf-8&characterSetResults=utf8"); } catch (Exception e) { System.out.println(e); System.exit(0); } System.out.println("Connection established"); try { java.sql.Statement s = conn.createStatement(); java.sql.ResultSet r = s.executeQuery("SELECT * FROM x WHERE text = 'ěščřž'"); while(r.next()) { System.out.println ( r.getString("id") + " " + r.getString("text") ); } } catch (Exception e) { System.out.println(e); System.exit(0); } } } ``` The Python code is: ``` # encoding: utf8 import MySQLdb conn = MySQLdb.connect (host = "127.0.0.1", port = 3307, user = "root", passwd = "root", db = "x") cursor = conn.cursor () cursor.execute ("SELECT * FROM x where text = 'ěščřž'") row = cursor.fetchone () print row cursor.close () conn.close () ``` Both are stored on the filesystem in utf8 encoding (checked with hexedit). I have tried different versions of mysql-connector (currently using 5.1.15). Mysqld is 5.1.54. Mysqld log for the Java code and Python code respectively: ``` 110427 12:45:07 1 Connect root@localhost on x 110427 12:45:08 1 Query /* mysql-connector-java-5.1.15 ( Revision: ${bzr.revision-id} ) */SHOW VARIABLES WHERE Variable_name ='language' OR Variable_name = 'net_write_timeout' OR Variable_name = 'interactive_timeout' OR Variable_name = 'wait_timeout' OR Variable_name = 'character_set_client' OR Variable_name = 'character_set_connection' OR Variable_name = 'character_set' OR Variable_name = 'character_set_server' OR Variable_name = 'tx_isolation' OR Variable_name = 'transaction_isolation' OR Variable_name = 'character_set_results' OR Variable_name = 'timezone' OR Variable_name = 'time_zone' OR Variable_name = 'system_time_zone' OR Variable_name = 'lower_case_table_names' OR Variable_name = 'max_allowed_packet' OR Variable_name = 'net_buffer_length' OR Variable_name = 'sql_mode' OR Variable_name = 'query_cache_type' OR Variable_name = 'query_cache_size' OR Variable_name = 'init_connect' 1 Query /* mysql-connector-java-5.1.15 ( Revision: ${bzr.revision-id} ) */SELECT @@session.auto_increment_increment 1 Query SHOW COLLATION 1 Query SET autocommit=1 1 Query SET sql_mode='STRICT_TRANS_TABLES' 1 Query SELECT * FROM x WHERE text = 'ěščřž' 110427 12:45:22 2 Connect root@localhost on x 2 Query set autocommit=0 2 Query SELECT * FROM x where text = 'ěščřž' 2 Quit ``` Does anybody have any suggestions what might be the cause why the Python code works and why the Java code does not? (by not working I mean not finding the desired data -- the connection works fine) Many thanks.
2011/04/27
[ "https://Stackoverflow.com/questions/5803170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/429274/" ]
Okay, my bad. The database was wrongly built. It was built through the mysql client that by default is latin1 so in the database the data were encoded by utf8 twice. The problem and the major difference between the two source codes is in that the Python code doesn't set the default charset (therefore it is latin1) whereas the Java code does (therefore it is utf8). So it was coincidence of many factors that made me think that something peculiar is actually going on. Thanks for your responses anyway.
Use PreparedStatement and set your search string as a positional parameter into that statement. Read this tutorial about PreparedStatements -> <http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html> Also, never create a String literal in Java code that contains non-ASCII characters. If you want to pass non-ASCII characters do a unicode escaping on them. This should give you an idea what I am talking about -> <http://en.wikibooks.org/wiki/Java_Programming/Syntax/Unicode_Escape_Sequences>
2
0
24,220,365
I have this SQL server instance which is shared by several client-processes. I want queries to finish taking as little time as possible. Say a call needs to read 1k to 10k records from this shared Sql Server. My natural choice would be to use ExecuteReaderAsync to take advantage of async benefits such as reusing threads. I started wondering whether async will pose some overhead since execution might stop and resume for every call to ExecuteReaderAsync. That being true, seems that overall time for query to complete would be longer if compared to a implementation that uses ExecuteReader. Does that make (any) sense?
2014/06/14
[ "https://Stackoverflow.com/questions/24220365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/298622/" ]
Whether you use sync or async to call SQL Server makes no difference for the work that SQL Server does and for the CPU-bound work that ADO.NET does to serialize and deserialize request and response. So no matter what you chose the difference will be small. Using async is not about saving CPU time. It is about saving memory (less thread stacks) and about having a nice programming model in UI apps. In fact async never saves CPU time as far as I'm aware. It adds overhead. If you want to save CPU time use a synchronous approach. On the server using async in low-concurrency workloads adds no value whatsoever. It adds development time and CPU cost.
The difference between the async approach and the sync approach is that the async call will cause the compiler to generate a state machine, whereas the sync call will simply block while the work agains't the database is being done. IRL, the best way to choose is to benchmark both approaches. As usr said, usually those differrences are neglectable compared to the time the query takes to execute. Async will shine brighter in places where it may save resources such as allocating a new thread There are many posts about async performance: 1. [*Async await performance*](https://stackoverflow.com/questions/23871806/async-await-performance) 2. [*The zen of async: best practices for best performance*](http://channel9.msdn.com/events/BUILD/BUILD2011/TOOL-829T) 3. [*Async Performance: Understanding the Costs of Async and Await*](http://msdn.microsoft.com/en-us/magazine/hh456402.aspx)
3
2
3,398,839
I'm trying to prove this by induction, but something doesn't add up. I see a solution given [here](https://www.algebra.com/algebra/homework/word/misc/Miscellaneous_Word_Problems.faq.question.29292.html), but it is actually proving that the expression is **greater** than $2\sqrt{n}$. I'd appreciate some insight.
2019/10/18
[ "https://math.stackexchange.com/questions/3398839", "https://math.stackexchange.com", "https://math.stackexchange.com/users/209695/" ]
Base step: 1<2. Inductive step: $$\sum\_{j=1}^{n+1}\frac1{\sqrt{j}} < 2\sqrt{n}+\frac1{\sqrt{n+1}}$$ So if we prove $$2\sqrt{n}+\frac1{\sqrt{n+1}}<2\sqrt{n+1}$$ we are done. Indeed, that holds true: just square the left hand side sides to get $$4n+2\frac{\sqrt{n}}{\sqrt{n+1}}+\frac1{n+1}<4n+3<4n+4$$ which is the square of the right end side. Errata: I forgot the double product in the square. The proof must be amended as follows: $$2\sqrt{n}<2\sqrt{n+1}-\frac1{\sqrt{n+1}}$$ since by squaring it we get $$4n<4n+4-4+\frac1{n+1}$$ which is trivially true.
Note that $$ 2\sqrt{n+1}-2\sqrt n=2\cdot\frac{(\sqrt{n+1}-\sqrt{n})(\sqrt{n+1}+\sqrt{n})}{\sqrt{n+1}+\sqrt{n}}=2\cdot \frac{(n+1)-n}{\sqrt{n+1}+\sqrt{n}}<\frac 2{\sqrt n+\sqrt n}$$
3
0
32,969,687
I have a scenario where I need to auto generate the value of a column if it is null. Ex: `employeeDetails`: ``` empName empId empExtension A 101 null B 102 987 C 103 986 D 104 null E 105 null ``` `employeeDepartment`: ``` deptName empId HR 101 ADMIN 102 IT 103 IT 104 IT 105 ``` Query ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Output: ``` empId deptName empExtension 101 HR null 102 ADMIN 987 103 IT 986 104 IT null 105 IT null ``` Now my question is I want to insert some dummy value which replaces null and auto-increments starting from a 5 digit INT number Expected output: ``` empId deptName empExtension 101 HR 12345 102 ADMIN 987 103 IT 986 104 IT 12346 105 IT 12347 ``` Constraints : I cannot change existing tables structure or any column's datatypes.
2015/10/06
[ "https://Stackoverflow.com/questions/32969687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3622730/" ]
You should be able to do that with a CTE to grab [ROW\_NUMBER](https://msdn.microsoft.com/en-us/library/ms186734.aspx), and then [COALESCE](https://msdn.microsoft.com/en-us/library/ms190349.aspx) to only use that number where the value is NULL: ``` WITH cte AS( SELECT empId, empExtension, ROW_NUMBER() OVER(ORDER BY empExtension, empId) rn FROM employeeDetails ) SELECT cte.empId, deptName, COALESCE(empExtension, rn + 12344) empExtension FROM cte LEFT JOIN employeeDepartment ON cte.empID = employeeDepartment.empID ORDER BY cte.empId ``` Here's an [SQLFiddle](http://sqlfiddle.com/#!3/142d1/5).
Just an idea, can you save result of that query into temp table ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension INTO #TempEmployee FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` And after that just do the update of #TempEmployee?
2
0
32,969,687
I have a scenario where I need to auto generate the value of a column if it is null. Ex: `employeeDetails`: ``` empName empId empExtension A 101 null B 102 987 C 103 986 D 104 null E 105 null ``` `employeeDepartment`: ``` deptName empId HR 101 ADMIN 102 IT 103 IT 104 IT 105 ``` Query ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Output: ``` empId deptName empExtension 101 HR null 102 ADMIN 987 103 IT 986 104 IT null 105 IT null ``` Now my question is I want to insert some dummy value which replaces null and auto-increments starting from a 5 digit INT number Expected output: ``` empId deptName empExtension 101 HR 12345 102 ADMIN 987 103 IT 986 104 IT 12346 105 IT 12347 ``` Constraints : I cannot change existing tables structure or any column's datatypes.
2015/10/06
[ "https://Stackoverflow.com/questions/32969687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3622730/" ]
If you just want to create a unique random 5 digit number for those `empExtension` column values are null, then **Query** ``` ;with cte as ( select rn = row_number() over ( order by empId ),* from employeeDetails ) select t1.empId,t2.deptName, case when t1.empExtension is null then t1.rn + (convert(numeric(5,0),rand() * 20000) + 10000) else t1.empExtension end as empExtension from cte t1 left join employeeDepartment t2 on t1.empId = t2.empId; ``` [**SQL Fiddle**](http://www.sqlfiddle.com/#!3/29acb/1)
Just an idea, can you save result of that query into temp table ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension INTO #TempEmployee FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` And after that just do the update of #TempEmployee?
1
0
32,969,687
I have a scenario where I need to auto generate the value of a column if it is null. Ex: `employeeDetails`: ``` empName empId empExtension A 101 null B 102 987 C 103 986 D 104 null E 105 null ``` `employeeDepartment`: ``` deptName empId HR 101 ADMIN 102 IT 103 IT 104 IT 105 ``` Query ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Output: ``` empId deptName empExtension 101 HR null 102 ADMIN 987 103 IT 986 104 IT null 105 IT null ``` Now my question is I want to insert some dummy value which replaces null and auto-increments starting from a 5 digit INT number Expected output: ``` empId deptName empExtension 101 HR 12345 102 ADMIN 987 103 IT 986 104 IT 12346 105 IT 12347 ``` Constraints : I cannot change existing tables structure or any column's datatypes.
2015/10/06
[ "https://Stackoverflow.com/questions/32969687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3622730/" ]
``` declare @rand int = (rand()* 12345); SELECT empdt.empId, empdprt.deptName, isnull(empdt.empExtension,row_number() over(order by empdt.empId)+@rand) FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Incase the empExtension, get the row\_number + a random number.
Just an idea, can you save result of that query into temp table ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension INTO #TempEmployee FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` And after that just do the update of #TempEmployee?
1
0
32,969,687
I have a scenario where I need to auto generate the value of a column if it is null. Ex: `employeeDetails`: ``` empName empId empExtension A 101 null B 102 987 C 103 986 D 104 null E 105 null ``` `employeeDepartment`: ``` deptName empId HR 101 ADMIN 102 IT 103 IT 104 IT 105 ``` Query ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Output: ``` empId deptName empExtension 101 HR null 102 ADMIN 987 103 IT 986 104 IT null 105 IT null ``` Now my question is I want to insert some dummy value which replaces null and auto-increments starting from a 5 digit INT number Expected output: ``` empId deptName empExtension 101 HR 12345 102 ADMIN 987 103 IT 986 104 IT 12346 105 IT 12347 ``` Constraints : I cannot change existing tables structure or any column's datatypes.
2015/10/06
[ "https://Stackoverflow.com/questions/32969687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3622730/" ]
You should be able to do that with a CTE to grab [ROW\_NUMBER](https://msdn.microsoft.com/en-us/library/ms186734.aspx), and then [COALESCE](https://msdn.microsoft.com/en-us/library/ms190349.aspx) to only use that number where the value is NULL: ``` WITH cte AS( SELECT empId, empExtension, ROW_NUMBER() OVER(ORDER BY empExtension, empId) rn FROM employeeDetails ) SELECT cte.empId, deptName, COALESCE(empExtension, rn + 12344) empExtension FROM cte LEFT JOIN employeeDepartment ON cte.empID = employeeDepartment.empID ORDER BY cte.empId ``` Here's an [SQLFiddle](http://sqlfiddle.com/#!3/142d1/5).
If you just want to create a unique random 5 digit number for those `empExtension` column values are null, then **Query** ``` ;with cte as ( select rn = row_number() over ( order by empId ),* from employeeDetails ) select t1.empId,t2.deptName, case when t1.empExtension is null then t1.rn + (convert(numeric(5,0),rand() * 20000) + 10000) else t1.empExtension end as empExtension from cte t1 left join employeeDepartment t2 on t1.empId = t2.empId; ``` [**SQL Fiddle**](http://www.sqlfiddle.com/#!3/29acb/1)
2
1
32,969,687
I have a scenario where I need to auto generate the value of a column if it is null. Ex: `employeeDetails`: ``` empName empId empExtension A 101 null B 102 987 C 103 986 D 104 null E 105 null ``` `employeeDepartment`: ``` deptName empId HR 101 ADMIN 102 IT 103 IT 104 IT 105 ``` Query ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Output: ``` empId deptName empExtension 101 HR null 102 ADMIN 987 103 IT 986 104 IT null 105 IT null ``` Now my question is I want to insert some dummy value which replaces null and auto-increments starting from a 5 digit INT number Expected output: ``` empId deptName empExtension 101 HR 12345 102 ADMIN 987 103 IT 986 104 IT 12346 105 IT 12347 ``` Constraints : I cannot change existing tables structure or any column's datatypes.
2015/10/06
[ "https://Stackoverflow.com/questions/32969687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3622730/" ]
You should be able to do that with a CTE to grab [ROW\_NUMBER](https://msdn.microsoft.com/en-us/library/ms186734.aspx), and then [COALESCE](https://msdn.microsoft.com/en-us/library/ms190349.aspx) to only use that number where the value is NULL: ``` WITH cte AS( SELECT empId, empExtension, ROW_NUMBER() OVER(ORDER BY empExtension, empId) rn FROM employeeDetails ) SELECT cte.empId, deptName, COALESCE(empExtension, rn + 12344) empExtension FROM cte LEFT JOIN employeeDepartment ON cte.empID = employeeDepartment.empID ORDER BY cte.empId ``` Here's an [SQLFiddle](http://sqlfiddle.com/#!3/142d1/5).
``` declare @rand int = (rand()* 12345); SELECT empdt.empId, empdprt.deptName, isnull(empdt.empExtension,row_number() over(order by empdt.empId)+@rand) FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Incase the empExtension, get the row\_number + a random number.
2
1
62,440,916
I'm brand new to python 3 & my google searches have been unproductive. Is there a way to write this: ``` for x in range(10): print(x) ``` as this: ``` print(x) for x in range(10) ``` I do not want to return a list as the `arr = [x for x in X]` list comprehension syntax does. EDIT: I'm not actually in that specific case involving `print()`, I'm interested in a generic pythonic syntactical construction for ``` method(element) for element in list ```
2020/06/18
[ "https://Stackoverflow.com/questions/62440916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4048592/" ]
No, there isn't. Unless you consider this a one liner: ``` for x in range(6): print(x) ``` but there's no reason to do that.
For your specific case to print a range of 6: ```py print(*range(6), sep='\n') ``` This is not a for loop however @Boris is correct.
3
0
62,440,916
I'm brand new to python 3 & my google searches have been unproductive. Is there a way to write this: ``` for x in range(10): print(x) ``` as this: ``` print(x) for x in range(10) ``` I do not want to return a list as the `arr = [x for x in X]` list comprehension syntax does. EDIT: I'm not actually in that specific case involving `print()`, I'm interested in a generic pythonic syntactical construction for ``` method(element) for element in list ```
2020/06/18
[ "https://Stackoverflow.com/questions/62440916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4048592/" ]
No, there isn't. Unless you consider this a one liner: ``` for x in range(6): print(x) ``` but there's no reason to do that.
Looks like you are looking for something like `map`. If the function you are calling returns `None`, then it won't be too expensive. Map will return an iterator, so you are just trying to consume it. One way is: ```py list(map(print, range(6))) ``` Or using a zero length deque if you don't want the actual list elements stored. ```py from collections import deque deque(map(print, range(6)), maxlen=0) ```
3
1
62,440,916
I'm brand new to python 3 & my google searches have been unproductive. Is there a way to write this: ``` for x in range(10): print(x) ``` as this: ``` print(x) for x in range(10) ``` I do not want to return a list as the `arr = [x for x in X]` list comprehension syntax does. EDIT: I'm not actually in that specific case involving `print()`, I'm interested in a generic pythonic syntactical construction for ``` method(element) for element in list ```
2020/06/18
[ "https://Stackoverflow.com/questions/62440916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4048592/" ]
No, there isn't. Unless you consider this a one liner: ``` for x in range(6): print(x) ``` but there's no reason to do that.
What you are looking for is a generator expression that returns a generator object. ```py print(i for i in range(10)) #<generator object <genexpr> at 0x7f3a5baacdb0> ``` To see the values ```py print(*(i for i in range(10))) # 0 1 2 3 4 5 6 7 8 9 ``` Pros: * Extremely Memory Efficient. * Lazy Evaluation - generates next element only on demand. Cons: * Can be iterated over till the stop iteration is hit, after that one cannot reiterate it. * Cannot be indexed like a list. Hope this helps!
3
0
62,440,916
I'm brand new to python 3 & my google searches have been unproductive. Is there a way to write this: ``` for x in range(10): print(x) ``` as this: ``` print(x) for x in range(10) ``` I do not want to return a list as the `arr = [x for x in X]` list comprehension syntax does. EDIT: I'm not actually in that specific case involving `print()`, I'm interested in a generic pythonic syntactical construction for ``` method(element) for element in list ```
2020/06/18
[ "https://Stackoverflow.com/questions/62440916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4048592/" ]
Looks like you are looking for something like `map`. If the function you are calling returns `None`, then it won't be too expensive. Map will return an iterator, so you are just trying to consume it. One way is: ```py list(map(print, range(6))) ``` Or using a zero length deque if you don't want the actual list elements stored. ```py from collections import deque deque(map(print, range(6)), maxlen=0) ```
For your specific case to print a range of 6: ```py print(*range(6), sep='\n') ``` This is not a for loop however @Boris is correct.
1
0
62,440,916
I'm brand new to python 3 & my google searches have been unproductive. Is there a way to write this: ``` for x in range(10): print(x) ``` as this: ``` print(x) for x in range(10) ``` I do not want to return a list as the `arr = [x for x in X]` list comprehension syntax does. EDIT: I'm not actually in that specific case involving `print()`, I'm interested in a generic pythonic syntactical construction for ``` method(element) for element in list ```
2020/06/18
[ "https://Stackoverflow.com/questions/62440916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4048592/" ]
Looks like you are looking for something like `map`. If the function you are calling returns `None`, then it won't be too expensive. Map will return an iterator, so you are just trying to consume it. One way is: ```py list(map(print, range(6))) ``` Or using a zero length deque if you don't want the actual list elements stored. ```py from collections import deque deque(map(print, range(6)), maxlen=0) ```
What you are looking for is a generator expression that returns a generator object. ```py print(i for i in range(10)) #<generator object <genexpr> at 0x7f3a5baacdb0> ``` To see the values ```py print(*(i for i in range(10))) # 0 1 2 3 4 5 6 7 8 9 ``` Pros: * Extremely Memory Efficient. * Lazy Evaluation - generates next element only on demand. Cons: * Can be iterated over till the stop iteration is hit, after that one cannot reiterate it. * Cannot be indexed like a list. Hope this helps!
1
0
37,455,599
When I run my project on my iphone or in the simulator it works fine. When I try to run it on an ipad I get the below error: *file was built for arm64 which is not the architecture being linked (armv7)* The devices it set to Universal. Does anybody have an idea about what else I should check?
2016/05/26
[ "https://Stackoverflow.com/questions/37455599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5367540/" ]
Just in case somebody has the same problem as me. Some of my target projects had different iOS Deployment target and that is why the linking failed. After moving them all to the same the problem was solved.
I should have added armv6 for iPad 2. Done that and it works now
3
1
2,315,242
I'm just starting a new project on ASP.NET MVC and this will be the first project actually using this technology. As I created my new project with Visual Studio 2010, it created to my sql server a bunch of tables with "aspnet\_" prefix. Part of them deal with the built-in user accounts and permission support. Now, I want to keep some specific information about my users. My question is "Is it a good practice changing the structure of this aspnet\_ tables, to meet my needs about user account's information?". And as i suppose the answer is "No." (Why exactly?), I intend to create my own "Users" table. What is a good approach to connect the records from aspnet\_Users table and my own custom Users table. I want the relationship to be 1:1 and the design in the database to be as transparent as possible in my c# code (I'm using linq to sql if it is important). Also, I don't want to replicate the usernames and passwords from the aspnet\_ tables to my table and maintain the data. I'm considering using a view to join them. Is this a good idea? Thanks in advance! EDIT: From the answer, I see that I may not be clear enough, what I want. The question is not IF to use the default asp.net provider, but how to adopt it, to my needs.
2010/02/23
[ "https://Stackoverflow.com/questions/2315242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/266159/" ]
If you are choosing to use the Membership API for your site, then this [link](http://www.asp.net/(S(pdfrohu0ajmwt445fanvj2r3))/learn/security/tutorial-08-cs.aspx) has information regarding how to add extra information to a user. I was faced with the same scenario recently and ended up ditching the membership functionality and rolled my own db solution in tandem with the DotNetOpenAuth library.
Using the membership system in asp.net has its advantages and drawbacks. It's easy to start, because you don't have to worry about validation, user registration, resetting passwords. (Be careful if you plan to modify the table structures, you will have to change them in the views/store procedures generated **However there are drawbacks to using Membership** You will have to maintain 2 separated systems, because the Membership API has restrictions, for example, you cannot perform operations inside a transaction with the membership api. (Unless you use TransactionScope i think, but you don't have other choices). A valid alternative would be to implement your own security validation routines, and using FormsAuthentication. This way you will have total control over your users tables, and remove dependency to the membership API.
2
-1
2,315,242
I'm just starting a new project on ASP.NET MVC and this will be the first project actually using this technology. As I created my new project with Visual Studio 2010, it created to my sql server a bunch of tables with "aspnet\_" prefix. Part of them deal with the built-in user accounts and permission support. Now, I want to keep some specific information about my users. My question is "Is it a good practice changing the structure of this aspnet\_ tables, to meet my needs about user account's information?". And as i suppose the answer is "No." (Why exactly?), I intend to create my own "Users" table. What is a good approach to connect the records from aspnet\_Users table and my own custom Users table. I want the relationship to be 1:1 and the design in the database to be as transparent as possible in my c# code (I'm using linq to sql if it is important). Also, I don't want to replicate the usernames and passwords from the aspnet\_ tables to my table and maintain the data. I'm considering using a view to join them. Is this a good idea? Thanks in advance! EDIT: From the answer, I see that I may not be clear enough, what I want. The question is not IF to use the default asp.net provider, but how to adopt it, to my needs.
2010/02/23
[ "https://Stackoverflow.com/questions/2315242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/266159/" ]
I would create [custom membership provider](http://www.15seconds.com/issue/050216.htm) and omit those `aspnet_x` tables completely. I've seen what happens when one `join`s these tables and custom ones with nhibernate mappings - pure nightmare.
Using the membership system in asp.net has its advantages and drawbacks. It's easy to start, because you don't have to worry about validation, user registration, resetting passwords. (Be careful if you plan to modify the table structures, you will have to change them in the views/store procedures generated **However there are drawbacks to using Membership** You will have to maintain 2 separated systems, because the Membership API has restrictions, for example, you cannot perform operations inside a transaction with the membership api. (Unless you use TransactionScope i think, but you don't have other choices). A valid alternative would be to implement your own security validation routines, and using FormsAuthentication. This way you will have total control over your users tables, and remove dependency to the membership API.
2
-1
7,710,639
I am modifying a regex validator control. The regex at the moment looks like this: ``` (\d*\,?\d{2}?){1}$ ``` As I can understand it allows for a number with 2 decimal places. I need to modify it like this: * The number must range from 0 - 1.000.000. (Zero to one million). * The number may or may not have 2 decimals. * The value can not be negative. * Comma (`,`) is the decimal separator. * Should not allow any thousand separators.
2011/10/10
[ "https://Stackoverflow.com/questions/7710639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/817455/" ]
Try this regex: ``` ^(((0|[1-9]\d{0,5})(\,\d{2})?)|(1000000(\,00)?))$ ``` It accepts numbers like: `"4", "4,23", "123456", "1000000", "1000000,00"`, but don't accepts: `",23", "4,7", "1000001", "4,234", "1000000,55"`. If you want accept only numbers with exactly two decimals, use this regex: ``` ^(((0|[1-9]\d{0,5})\,\d{2})|(1000000\,00))$ ```
What about this one ``` ^(?:\d{1,6}(?:\,\d{2})?|1000000)$ ``` See it [here on Regexr](http://regexr.com?2ut4u) It accepts between 1 and 6 digits and an optional fraction with 2 digits OR "1000000". And it allows the number to start with zeros! (001 would be accepted) `^` anchors the regex to the start of the string `$` anchors the regex to the end of the string `(?:)` is a non capturing group
2
0
7,710,639
I am modifying a regex validator control. The regex at the moment looks like this: ``` (\d*\,?\d{2}?){1}$ ``` As I can understand it allows for a number with 2 decimal places. I need to modify it like this: * The number must range from 0 - 1.000.000. (Zero to one million). * The number may or may not have 2 decimals. * The value can not be negative. * Comma (`,`) is the decimal separator. * Should not allow any thousand separators.
2011/10/10
[ "https://Stackoverflow.com/questions/7710639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/817455/" ]
Try this regex: ``` ^(((0|[1-9]\d{0,5})(\,\d{2})?)|(1000000(\,00)?))$ ``` It accepts numbers like: `"4", "4,23", "123456", "1000000", "1000000,00"`, but don't accepts: `",23", "4,7", "1000001", "4,234", "1000000,55"`. If you want accept only numbers with exactly two decimals, use this regex: ``` ^(((0|[1-9]\d{0,5})\,\d{2})|(1000000\,00))$ ```
``` ^(([0-9]|([1-9][0-9]{1,5}))(\.[0-9]{1,2})?)|1000000$ ```
2
0
24,444,188
can someone please tell me what is going wrong? I am trying to create a basic login page and that opens only when a correct password is written ``` <html> <head> <script> function validateForm() { var x=document.forms["myForm"]["fname"].value; if (x==null || x=="") { alert("First name must be filled out"); return false; } var x=document.forms["myForm"]["fname2"].value; if (x==null || x=="") { alert("password must be filled out"); return false; } } function isValid(myNorm){ var password = myNorm.value; if (password == "hello_me") { return true; } else {alert('Wrong Password') return false; } } </script> </head> <body> <form name="myForm" action="helloworld.html" onsubmit="return !!(validateForm()& isValid())" method="post"> Login ID: <input type="text" name="fname"> <br /> <br> Password: <input type="password" name="fname2" > <br /> <br /> <br /> <input type="submit" value="Submit"> <input type="Reset" value="clear"> </form> </body> </html> ```
2014/06/27
[ "https://Stackoverflow.com/questions/24444188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2771301/" ]
try this ``` BufferedWriter writer = new BufferedWriter(new FileWriter("result.txt")); for (String element : misspelledWords) { writer.write(element); writer.newLine(); } ``` Adding line separator at the end (like "\n") should work on most OS,but to be on safer side you should use **System.getProperty("line.separator")**
Open your file in append mode like this `FileWriter(String fileName, boolean append)` when you want to make an object of class `FileWrite` in constructor. ``` File file = new File("C:\\Users\\Izak\\Documents\\NetBeansProjects\\addNewLinetoTxtFile\\src\\addnewlinetotxtfile\\a.txt"); try (Writer newLine = new BufferedWriter(new FileWriter(file, true));) { newLine.write("New Line!"); newLine.write(System.getProperty( "line.separator" )); } catch (IOException e) { } ``` Note: > "**line.separator**" is a Sequence used by operating system to separate lines > in text files source: <http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html>
3
0
47,331,969
I'm trying to merge informations in two different data frames, but problem begins with uneven dimensions and trying to use not the column index but the information in the column. merge function in R or join's (dplyr) don't work with my data. I have to dataframes (One is subset of the others with updated info in the last column): `df1=data.frame(Name = print(LETTERS[1:9]), val = seq(1:3), Case = c("NA","1","NA","NA","1","NA","1","NA","NA"))` ``` Name val Case 1 A 1 NA 2 B 2 1 3 C 3 NA 4 D 1 NA 5 E 2 1 6 F 3 NA 7 G 1 1 8 H 2 NA 9 I 3 NA ``` Some rows in the `Case` column in `df1` have to be changed with the info in the `df2` below: `df2 = data.frame(Name = c("A","D","H"), val = seq(1:3), Case = "1")` ``` Name val Case 1 A 1 1 2 D 2 1 3 H 3 1 ``` So there's nothing important in the `val` column, however I added it into the examples since I want to indicate that I have more columns than two and also my real data is way bigger than the examples. Basically, I want to change specific rows by checking the information in the first columns (in this case, they're unique letters) and in the end I still want to have `df1` as a final data frame. for a better explanation, I want to see something like this: ``` Name val Case 1 A 1 1 2 B 2 1 3 C 3 NA 4 D 1 1 5 E 2 1 6 F 3 NA 7 G 1 1 8 H 2 1 9 I 3 NA ``` Note changed information for `A`,`D` and `H`. Thanks.
2017/11/16
[ "https://Stackoverflow.com/questions/47331969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8609239/" ]
`%in%` from base-r is there to rescue. ``` df1=data.frame(Name = print(LETTERS[1:9]), val = seq(1:3), Case = c("NA","1","NA","NA","1","NA","1","NA","NA"), stringsAsFactors = F) df2 = data.frame(Name = c("A","D","H"), val = seq(1:3), Case = "1", stringsAsFactors = F) df1$Case <- ifelse(df1$Name %in% df2$Name, df2$Case[df2$Name %in% df1$Name], df1$Case) df1 Output: > df1 Name val Case 1 A 1 1 2 B 2 1 3 C 3 NA 4 D 1 1 5 E 2 1 6 F 3 NA 7 G 1 1 8 H 2 1 9 I 3 NA ```
Here is what I would do using `dplyr`: ``` df1 %>% left_join(df2, by = c("Name")) %>% mutate(val = if_else(is.na(val.y), val.x, val.y), Case = if_else(is.na(Case.y), Case.x, Case.y)) %>% select(Name, val, Case) ```
3
1
5,669,878
I'm building a WSGI web app and I have a MySQL database. I'm using MySQLdb, which provides cursors for executing statements and getting results. **What is the standard practice for getting and closing cursors?** In particular, how long should my cursors last? Should I get a new cursor for each transaction? I believe you need to close the cursor before committing the connection. Is there any significant advantage to finding sets of transactions that don't require intermediate commits so that you don't have to get new cursors for each transaction? Is there a lot of overhead for getting new cursors, or is it just not a big deal?
2011/04/14
[ "https://Stackoverflow.com/questions/5669878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/484488/" ]
It's better to rewrite it using 'with' keyword. 'With' will take care about closing cursor (it's important because it's unmanaged resource) automatically. The benefit is it will close cursor in case of exception too. ``` from contextlib import closing import MySQLdb ''' At the beginning you open a DB connection. Particular moment when you open connection depends from your approach: - it can be inside the same function where you work with cursors - in the class constructor - etc ''' db = MySQLdb.connect("host", "user", "pass", "database") with closing(db.cursor()) as cur: cur.execute("somestuff") results = cur.fetchall() # do stuff with results cur.execute("insert operation") # call commit if you do INSERT, UPDATE or DELETE operations db.commit() cur.execute("someotherstuff") results2 = cur.fetchone() # do stuff with results2 # at some point when you decided that you do not need # the open connection anymore you close it db.close() ```
I suggest to do it like php and mysql. Start i at the beginning of your code before printing of the first data. So if you get a connect error you can display a `50x`(Don't remember what internal error is) error message. And keep it open for the whole session and close it when you know you wont need it anymore.
5
-1
5,669,878
I'm building a WSGI web app and I have a MySQL database. I'm using MySQLdb, which provides cursors for executing statements and getting results. **What is the standard practice for getting and closing cursors?** In particular, how long should my cursors last? Should I get a new cursor for each transaction? I believe you need to close the cursor before committing the connection. Is there any significant advantage to finding sets of transactions that don't require intermediate commits so that you don't have to get new cursors for each transaction? Is there a lot of overhead for getting new cursors, or is it just not a big deal?
2011/04/14
[ "https://Stackoverflow.com/questions/5669878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/484488/" ]
Note: this answer is for [PyMySQL](https://github.com/PyMySQL/PyMySQL), which is a drop-in replacement for MySQLdb and effectively the latest version of MySQLdb since MySQLdb stopped being maintained. I believe everything here is *also* true of the legacy MySQLdb, but haven't checked. First of all, some facts: * Python's [`with`](https://docs.python.org/library/stdtypes.html#context-manager-types) syntax calls the context manager's `__enter__` method before executing the body of the `with` block, and its `__exit__` method afterwards. * Connections have an [`__enter__`](https://github.com/PyMySQL/PyMySQL/blob/0.7.10/pymysql/connections.py#L831-L833) method that does nothing besides create and return a cursor, and an [`__exit__`](https://github.com/PyMySQL/PyMySQL/blob/0.7.10/pymysql/connections.py#L835-L840) method that either commits or rolls back (depending upon whether an exception was thrown). It *does not* close the connection. * Cursors in PyMySQL are purely an abstraction implemented in Python; there is no equivalent concept in MySQL itself.1 * Cursors have an [`__enter__`](https://github.com/PyMySQL/PyMySQL/blob/0.7.10/pymysql/cursors.py#L62-L63) method that doesn't do anything and an [`__exit__`](https://github.com/PyMySQL/PyMySQL/blob/0.7.10/pymysql/cursors.py#L65-L67) method which "closes" the cursor (which just means nulling the cursor's reference to its parent connection and throwing away any data stored on the cursor). * Cursors hold a reference to the connection that spawned them, but connections don't hold a reference to the cursors that they've created. * Connections have a [`__del__`](https://github.com/PyMySQL/PyMySQL/blob/0.7.10/pymysql/connections.py#L750) method which closes them * Per <https://docs.python.org/3/reference/datamodel.html>, CPython (the default Python implementation) uses reference counting and automatically deletes an object once the number of references to it hits zero. Putting these things together, we see that naive code like this is *in theory* problematic: ``` # Problematic code, at least in theory! import pymysql with pymysql.connect() as cursor: cursor.execute('SELECT 1') # ... happily carry on and do something unrelated ``` The problem is that nothing has closed the connection. Indeed, if you paste the code above into a Python shell and then run `SHOW FULL PROCESSLIST` at a MySQL shell, you'll be able to see the idle connection that you created. Since MySQL's default number of connections is [151](https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_max_connections), which isn't *huge*, you could theoretically start running into problems if you had many processes keeping these connections open. However, in CPython, there is a saving grace that ensures that code like my example above *probably* won't cause you to leave around loads of open connections. That saving grace is that as soon as `cursor` goes out of scope (e.g. the function in which it was created finishes, or `cursor` gets another value assigned to it), its reference count hits zero, which causes it to be deleted, dropping the connection's reference count to zero, causing the connection's `__del__` method to be called which force-closes the connection. If you already pasted the code above into your Python shell, then you can now simulate this by running `cursor = 'arbitrary value'`; as soon as you do this, the connection you opened will vanish from the `SHOW PROCESSLIST` output. However, relying upon this is inelegant, and theoretically might fail in Python implementations other than CPython. Cleaner, in theory, would be to explicitly `.close()` the connection (to free up a connection on the database without waiting for Python to destroy the object). This more robust code looks like this: ``` import contextlib import pymysql with contextlib.closing(pymysql.connect()) as conn: with conn as cursor: cursor.execute('SELECT 1') ``` This is ugly, but doesn't rely upon Python destructing your objects to free up your (finite available number of) database connections. Note that closing the *cursor*, if you're already closing the connection explicitly like this, is entirely pointless. Finally, to answer the secondary questions here: > Is there a lot of overhead for getting new cursors, or is it just not a big deal? Nope, instantiating a cursor doesn't hit MySQL at all and [basically does nothing](https://github.com/PyMySQL/PyMySQL/blob/0.7.10/pymysql/cursors.py#L34-L47). > Is there any significant advantage to finding sets of transactions that don't require intermediate commits so that you don't have to get new cursors for each transaction? This is situational and difficult to give a general answer to. As <https://dev.mysql.com/doc/refman/en/optimizing-innodb-transaction-management.html> puts it, *"an application might encounter performance issues if it commits thousands of times per second, and different performance issues if it commits only every 2-3 hours"*. You pay a performance overhead for every commit, but by leaving transactions open for longer, you increase the chance of other connections having to spend time waiting for locks, increase your risk of deadlocks, and potentially increase the cost of some lookups performed by other connections. --- 1 MySQL *does* have a construct it calls a [cursor](https://dev.mysql.com/doc/refman/en/cursors.html) but they only exist inside stored procedures; they're completely different to PyMySQL cursors and are not relevant here.
I suggest to do it like php and mysql. Start i at the beginning of your code before printing of the first data. So if you get a connect error you can display a `50x`(Don't remember what internal error is) error message. And keep it open for the whole session and close it when you know you wont need it anymore.
3
-1
5,669,878
I'm building a WSGI web app and I have a MySQL database. I'm using MySQLdb, which provides cursors for executing statements and getting results. **What is the standard practice for getting and closing cursors?** In particular, how long should my cursors last? Should I get a new cursor for each transaction? I believe you need to close the cursor before committing the connection. Is there any significant advantage to finding sets of transactions that don't require intermediate commits so that you don't have to get new cursors for each transaction? Is there a lot of overhead for getting new cursors, or is it just not a big deal?
2011/04/14
[ "https://Stackoverflow.com/questions/5669878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/484488/" ]
Instead of asking what is standard practice, since that's often unclear and subjective, you might try looking to the module itself for guidance. In general, using the `with` keyword as another user suggested is a great idea, but in this specific circumstance it may not give you quite the functionality you expect. As of version 1.2.5 of the module, `MySQLdb.Connection` implements the [context manager protocol](http://docs.python.org/2/library/stdtypes.html#context-manager-types) with the following code ([github](https://github.com/farcepest/MySQLdb1/blob/2204283605e8c450223965eda8d8f357d5fe4c90/MySQLdb/connections.py)): ``` def __enter__(self): if self.get_autocommit(): self.query("BEGIN") return self.cursor() def __exit__(self, exc, value, tb): if exc: self.rollback() else: self.commit() ``` There are several existing Q&A about `with` already, or you can read [Understanding Python's "with" statement](http://effbot.org/zone/python-with-statement.htm), but essentially what happens is that `__enter__` executes at the start of the `with` block, and `__exit__` executes upon leaving the `with` block. You can use the optional syntax `with EXPR as VAR` to bind the object returned by `__enter__` to a name if you intend to reference that object later. So, given the above implementation, here's a simple way to query your database: ``` connection = MySQLdb.connect(...) with connection as cursor: # connection.__enter__ executes at this line cursor.execute('select 1;') result = cursor.fetchall() # connection.__exit__ executes after this line print result # prints "((1L,),)" ``` The question now is, what are the states of the connection and the cursor after exiting the `with` block? The `__exit__` method shown above calls only `self.rollback()` or `self.commit()`, and neither of those methods go on to call the `close()` method. The cursor itself has no `__exit__` method defined – and wouldn't matter if it did, because `with` is only managing the connection. Therefore, both the connection and the cursor remain open after exiting the `with` block. This is easily confirmed by adding the following code to the above example: ``` try: cursor.execute('select 1;') print 'cursor is open;', except MySQLdb.ProgrammingError: print 'cursor is closed;', if connection.open: print 'connection is open' else: print 'connection is closed' ``` You should see the output "cursor is open; connection is open" printed to stdout. > I believe you need to close the cursor before committing the connection. Why? The [MySQL C API](https://dev.mysql.com/doc/refman/5.6/en/c-api-function-overview.html), which is the basis for `MySQLdb`, does not implement any cursor object, as implied in the module documentation: ["MySQL does not support cursors; however, cursors are easily emulated."](http://mysql-python.sourceforge.net/MySQLdb.html#connection-objects) Indeed, the `MySQLdb.cursors.BaseCursor` class inherits directly from `object` and imposes no such restriction on cursors with regard to commit/rollback. An Oracle developer [had this to say](http://forums.mysql.com/read.php?50,578823,578941#msg-578941): > cnx.commit() before cur.close() sounds most logical to me. Maybe you > can go by the rule: "Close the cursor if you do not need it anymore." > Thus commit() before closing the cursor. In the end, for > Connector/Python, it does not make much difference, but or other > databases it might. I expect that's as close as you're going to get to "standard practice" on this subject. > Is there any significant advantage to finding sets of transactions that don't require intermediate commits so that you don't have to get new cursors for each transaction? I very much doubt it, and in trying to do so, you may introduce additional human error. Better to decide on a convention and stick with it. > Is there a lot of overhead for getting new cursors, or is it just not a big deal? The overhead is negligible, and doesn't touch the database server at all; it's entirely within the implementation of MySQLdb. You can [look at `BaseCursor.__init__` on github](https://github.com/farcepest/MySQLdb1/blob/master/MySQLdb/cursors.py) if you're really curious to know what's happening when you create a new cursor. Going back to earlier when we were discussing `with`, perhaps now you can understand why the `MySQLdb.Connection` class `__enter__` and `__exit__` methods give you a brand new cursor object in every `with` block and don't bother keeping track of it or closing it at the end of the block. It's fairly lightweight and exists purely for your convenience. If it's really that important to you to micromanage the cursor object, you can use [contextlib.closing](http://docs.python.org/2/library/contextlib.html#contextlib.closing) to make up for the fact that the cursor object has no defined `__exit__` method. For that matter, you can also use it to force the connection object to close itself upon exiting a `with` block. This should output "my\_curs is closed; my\_conn is closed": ``` from contextlib import closing import MySQLdb with closing(MySQLdb.connect(...)) as my_conn: with closing(my_conn.cursor()) as my_curs: my_curs.execute('select 1;') result = my_curs.fetchall() try: my_curs.execute('select 1;') print 'my_curs is open;', except MySQLdb.ProgrammingError: print 'my_curs is closed;', if my_conn.open: print 'my_conn is open' else: print 'my_conn is closed' ``` Note that `with closing(arg_obj)` will not call the argument object's `__enter__` and `__exit__` methods; it will *only* call the argument object's `close` method at the end of the `with` block. (To see this in action, simply define a class `Foo` with `__enter__`, `__exit__`, and `close` methods containing simple `print` statements, and compare what happens when you do `with Foo(): pass` to what happens when you do `with closing(Foo()): pass`.) This has two significant implications: First, if autocommit mode is enabled, MySQLdb will `BEGIN` an explicit transaction on the server when you use `with connection` and commit or rollback the transaction at the end of the block. These are default behaviors of MySQLdb, intended to protect you from MySQL's default behavior of immediately committing any and all DML statements. MySQLdb assumes that when you use a context manager, you want a transaction, and uses the explicit `BEGIN` to bypass the autocommit setting on the server. If you're used to using `with connection`, you might think autocommit is disabled when actually it was only being bypassed. You might get an unpleasant surprise if you add `closing` to your code and lose transactional integrity; you won't be able to rollback changes, you may start seeing concurrency bugs and it may not be immediately obvious why. Second, `with closing(MySQLdb.connect(user, pass)) as VAR` binds the *connection object* to `VAR`, in contrast to `with MySQLdb.connect(user, pass) as VAR`, which binds *a new cursor object* to `VAR`. In the latter case you would have no direct access to the connection object! Instead, you would have to use the cursor's `connection` attribute, which provides proxy access to the original connection. When the cursor is closed, its `connection` attribute is set to `None`. This results in an abandoned connection that will stick around until one of the following happens: * All references to the cursor are removed * The cursor goes out of scope * The connection times out * The connection is closed manually via server administration tools You can test this by monitoring open connections (in Workbench or by [using `SHOW PROCESSLIST`](http://dev.mysql.com/doc/refman/5.6/en/show-processlist.html)) while executing the following lines one by one: ``` with MySQLdb.connect(...) as my_curs: pass my_curs.close() my_curs.connection # None my_curs.connection.close() # throws AttributeError, but connection still open del my_curs # connection will close here ```
I think you'll be better off trying to use one cursor for all of your executions, and close it at the end of your code. It's easier to work with, and it might have efficiency benefits as well (don't quote me on that one). ``` conn = MySQLdb.connect("host","user","pass","database") cursor = conn.cursor() cursor.execute("somestuff") results = cursor.fetchall() ..do stuff with results cursor.execute("someotherstuff") results2 = cursor.fetchall() ..do stuff with results2 cursor.close() ``` The point is that you can store the results of a cursor's execution in another variable, thereby freeing your cursor to make a second execution. You run into problems this way only if you're using fetchone(), and need to make a second cursor execution before you've iterated through all results from the first query. Otherwise, I'd say just close your cursors as soon as you're done getting all of the data out of them. That way you don't have to worry about tying up loose ends later in your code.
8
3
5,669,878
I'm building a WSGI web app and I have a MySQL database. I'm using MySQLdb, which provides cursors for executing statements and getting results. **What is the standard practice for getting and closing cursors?** In particular, how long should my cursors last? Should I get a new cursor for each transaction? I believe you need to close the cursor before committing the connection. Is there any significant advantage to finding sets of transactions that don't require intermediate commits so that you don't have to get new cursors for each transaction? Is there a lot of overhead for getting new cursors, or is it just not a big deal?
2011/04/14
[ "https://Stackoverflow.com/questions/5669878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/484488/" ]
It's better to rewrite it using 'with' keyword. 'With' will take care about closing cursor (it's important because it's unmanaged resource) automatically. The benefit is it will close cursor in case of exception too. ``` from contextlib import closing import MySQLdb ''' At the beginning you open a DB connection. Particular moment when you open connection depends from your approach: - it can be inside the same function where you work with cursors - in the class constructor - etc ''' db = MySQLdb.connect("host", "user", "pass", "database") with closing(db.cursor()) as cur: cur.execute("somestuff") results = cur.fetchall() # do stuff with results cur.execute("insert operation") # call commit if you do INSERT, UPDATE or DELETE operations db.commit() cur.execute("someotherstuff") results2 = cur.fetchone() # do stuff with results2 # at some point when you decided that you do not need # the open connection anymore you close it db.close() ```
I think you'll be better off trying to use one cursor for all of your executions, and close it at the end of your code. It's easier to work with, and it might have efficiency benefits as well (don't quote me on that one). ``` conn = MySQLdb.connect("host","user","pass","database") cursor = conn.cursor() cursor.execute("somestuff") results = cursor.fetchall() ..do stuff with results cursor.execute("someotherstuff") results2 = cursor.fetchall() ..do stuff with results2 cursor.close() ``` The point is that you can store the results of a cursor's execution in another variable, thereby freeing your cursor to make a second execution. You run into problems this way only if you're using fetchone(), and need to make a second cursor execution before you've iterated through all results from the first query. Otherwise, I'd say just close your cursors as soon as you're done getting all of the data out of them. That way you don't have to worry about tying up loose ends later in your code.
5
3
5,669,878
I'm building a WSGI web app and I have a MySQL database. I'm using MySQLdb, which provides cursors for executing statements and getting results. **What is the standard practice for getting and closing cursors?** In particular, how long should my cursors last? Should I get a new cursor for each transaction? I believe you need to close the cursor before committing the connection. Is there any significant advantage to finding sets of transactions that don't require intermediate commits so that you don't have to get new cursors for each transaction? Is there a lot of overhead for getting new cursors, or is it just not a big deal?
2011/04/14
[ "https://Stackoverflow.com/questions/5669878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/484488/" ]
Instead of asking what is standard practice, since that's often unclear and subjective, you might try looking to the module itself for guidance. In general, using the `with` keyword as another user suggested is a great idea, but in this specific circumstance it may not give you quite the functionality you expect. As of version 1.2.5 of the module, `MySQLdb.Connection` implements the [context manager protocol](http://docs.python.org/2/library/stdtypes.html#context-manager-types) with the following code ([github](https://github.com/farcepest/MySQLdb1/blob/2204283605e8c450223965eda8d8f357d5fe4c90/MySQLdb/connections.py)): ``` def __enter__(self): if self.get_autocommit(): self.query("BEGIN") return self.cursor() def __exit__(self, exc, value, tb): if exc: self.rollback() else: self.commit() ``` There are several existing Q&A about `with` already, or you can read [Understanding Python's "with" statement](http://effbot.org/zone/python-with-statement.htm), but essentially what happens is that `__enter__` executes at the start of the `with` block, and `__exit__` executes upon leaving the `with` block. You can use the optional syntax `with EXPR as VAR` to bind the object returned by `__enter__` to a name if you intend to reference that object later. So, given the above implementation, here's a simple way to query your database: ``` connection = MySQLdb.connect(...) with connection as cursor: # connection.__enter__ executes at this line cursor.execute('select 1;') result = cursor.fetchall() # connection.__exit__ executes after this line print result # prints "((1L,),)" ``` The question now is, what are the states of the connection and the cursor after exiting the `with` block? The `__exit__` method shown above calls only `self.rollback()` or `self.commit()`, and neither of those methods go on to call the `close()` method. The cursor itself has no `__exit__` method defined – and wouldn't matter if it did, because `with` is only managing the connection. Therefore, both the connection and the cursor remain open after exiting the `with` block. This is easily confirmed by adding the following code to the above example: ``` try: cursor.execute('select 1;') print 'cursor is open;', except MySQLdb.ProgrammingError: print 'cursor is closed;', if connection.open: print 'connection is open' else: print 'connection is closed' ``` You should see the output "cursor is open; connection is open" printed to stdout. > I believe you need to close the cursor before committing the connection. Why? The [MySQL C API](https://dev.mysql.com/doc/refman/5.6/en/c-api-function-overview.html), which is the basis for `MySQLdb`, does not implement any cursor object, as implied in the module documentation: ["MySQL does not support cursors; however, cursors are easily emulated."](http://mysql-python.sourceforge.net/MySQLdb.html#connection-objects) Indeed, the `MySQLdb.cursors.BaseCursor` class inherits directly from `object` and imposes no such restriction on cursors with regard to commit/rollback. An Oracle developer [had this to say](http://forums.mysql.com/read.php?50,578823,578941#msg-578941): > cnx.commit() before cur.close() sounds most logical to me. Maybe you > can go by the rule: "Close the cursor if you do not need it anymore." > Thus commit() before closing the cursor. In the end, for > Connector/Python, it does not make much difference, but or other > databases it might. I expect that's as close as you're going to get to "standard practice" on this subject. > Is there any significant advantage to finding sets of transactions that don't require intermediate commits so that you don't have to get new cursors for each transaction? I very much doubt it, and in trying to do so, you may introduce additional human error. Better to decide on a convention and stick with it. > Is there a lot of overhead for getting new cursors, or is it just not a big deal? The overhead is negligible, and doesn't touch the database server at all; it's entirely within the implementation of MySQLdb. You can [look at `BaseCursor.__init__` on github](https://github.com/farcepest/MySQLdb1/blob/master/MySQLdb/cursors.py) if you're really curious to know what's happening when you create a new cursor. Going back to earlier when we were discussing `with`, perhaps now you can understand why the `MySQLdb.Connection` class `__enter__` and `__exit__` methods give you a brand new cursor object in every `with` block and don't bother keeping track of it or closing it at the end of the block. It's fairly lightweight and exists purely for your convenience. If it's really that important to you to micromanage the cursor object, you can use [contextlib.closing](http://docs.python.org/2/library/contextlib.html#contextlib.closing) to make up for the fact that the cursor object has no defined `__exit__` method. For that matter, you can also use it to force the connection object to close itself upon exiting a `with` block. This should output "my\_curs is closed; my\_conn is closed": ``` from contextlib import closing import MySQLdb with closing(MySQLdb.connect(...)) as my_conn: with closing(my_conn.cursor()) as my_curs: my_curs.execute('select 1;') result = my_curs.fetchall() try: my_curs.execute('select 1;') print 'my_curs is open;', except MySQLdb.ProgrammingError: print 'my_curs is closed;', if my_conn.open: print 'my_conn is open' else: print 'my_conn is closed' ``` Note that `with closing(arg_obj)` will not call the argument object's `__enter__` and `__exit__` methods; it will *only* call the argument object's `close` method at the end of the `with` block. (To see this in action, simply define a class `Foo` with `__enter__`, `__exit__`, and `close` methods containing simple `print` statements, and compare what happens when you do `with Foo(): pass` to what happens when you do `with closing(Foo()): pass`.) This has two significant implications: First, if autocommit mode is enabled, MySQLdb will `BEGIN` an explicit transaction on the server when you use `with connection` and commit or rollback the transaction at the end of the block. These are default behaviors of MySQLdb, intended to protect you from MySQL's default behavior of immediately committing any and all DML statements. MySQLdb assumes that when you use a context manager, you want a transaction, and uses the explicit `BEGIN` to bypass the autocommit setting on the server. If you're used to using `with connection`, you might think autocommit is disabled when actually it was only being bypassed. You might get an unpleasant surprise if you add `closing` to your code and lose transactional integrity; you won't be able to rollback changes, you may start seeing concurrency bugs and it may not be immediately obvious why. Second, `with closing(MySQLdb.connect(user, pass)) as VAR` binds the *connection object* to `VAR`, in contrast to `with MySQLdb.connect(user, pass) as VAR`, which binds *a new cursor object* to `VAR`. In the latter case you would have no direct access to the connection object! Instead, you would have to use the cursor's `connection` attribute, which provides proxy access to the original connection. When the cursor is closed, its `connection` attribute is set to `None`. This results in an abandoned connection that will stick around until one of the following happens: * All references to the cursor are removed * The cursor goes out of scope * The connection times out * The connection is closed manually via server administration tools You can test this by monitoring open connections (in Workbench or by [using `SHOW PROCESSLIST`](http://dev.mysql.com/doc/refman/5.6/en/show-processlist.html)) while executing the following lines one by one: ``` with MySQLdb.connect(...) as my_curs: pass my_curs.close() my_curs.connection # None my_curs.connection.close() # throws AttributeError, but connection still open del my_curs # connection will close here ```
Note: this answer is for [PyMySQL](https://github.com/PyMySQL/PyMySQL), which is a drop-in replacement for MySQLdb and effectively the latest version of MySQLdb since MySQLdb stopped being maintained. I believe everything here is *also* true of the legacy MySQLdb, but haven't checked. First of all, some facts: * Python's [`with`](https://docs.python.org/library/stdtypes.html#context-manager-types) syntax calls the context manager's `__enter__` method before executing the body of the `with` block, and its `__exit__` method afterwards. * Connections have an [`__enter__`](https://github.com/PyMySQL/PyMySQL/blob/0.7.10/pymysql/connections.py#L831-L833) method that does nothing besides create and return a cursor, and an [`__exit__`](https://github.com/PyMySQL/PyMySQL/blob/0.7.10/pymysql/connections.py#L835-L840) method that either commits or rolls back (depending upon whether an exception was thrown). It *does not* close the connection. * Cursors in PyMySQL are purely an abstraction implemented in Python; there is no equivalent concept in MySQL itself.1 * Cursors have an [`__enter__`](https://github.com/PyMySQL/PyMySQL/blob/0.7.10/pymysql/cursors.py#L62-L63) method that doesn't do anything and an [`__exit__`](https://github.com/PyMySQL/PyMySQL/blob/0.7.10/pymysql/cursors.py#L65-L67) method which "closes" the cursor (which just means nulling the cursor's reference to its parent connection and throwing away any data stored on the cursor). * Cursors hold a reference to the connection that spawned them, but connections don't hold a reference to the cursors that they've created. * Connections have a [`__del__`](https://github.com/PyMySQL/PyMySQL/blob/0.7.10/pymysql/connections.py#L750) method which closes them * Per <https://docs.python.org/3/reference/datamodel.html>, CPython (the default Python implementation) uses reference counting and automatically deletes an object once the number of references to it hits zero. Putting these things together, we see that naive code like this is *in theory* problematic: ``` # Problematic code, at least in theory! import pymysql with pymysql.connect() as cursor: cursor.execute('SELECT 1') # ... happily carry on and do something unrelated ``` The problem is that nothing has closed the connection. Indeed, if you paste the code above into a Python shell and then run `SHOW FULL PROCESSLIST` at a MySQL shell, you'll be able to see the idle connection that you created. Since MySQL's default number of connections is [151](https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_max_connections), which isn't *huge*, you could theoretically start running into problems if you had many processes keeping these connections open. However, in CPython, there is a saving grace that ensures that code like my example above *probably* won't cause you to leave around loads of open connections. That saving grace is that as soon as `cursor` goes out of scope (e.g. the function in which it was created finishes, or `cursor` gets another value assigned to it), its reference count hits zero, which causes it to be deleted, dropping the connection's reference count to zero, causing the connection's `__del__` method to be called which force-closes the connection. If you already pasted the code above into your Python shell, then you can now simulate this by running `cursor = 'arbitrary value'`; as soon as you do this, the connection you opened will vanish from the `SHOW PROCESSLIST` output. However, relying upon this is inelegant, and theoretically might fail in Python implementations other than CPython. Cleaner, in theory, would be to explicitly `.close()` the connection (to free up a connection on the database without waiting for Python to destroy the object). This more robust code looks like this: ``` import contextlib import pymysql with contextlib.closing(pymysql.connect()) as conn: with conn as cursor: cursor.execute('SELECT 1') ``` This is ugly, but doesn't rely upon Python destructing your objects to free up your (finite available number of) database connections. Note that closing the *cursor*, if you're already closing the connection explicitly like this, is entirely pointless. Finally, to answer the secondary questions here: > Is there a lot of overhead for getting new cursors, or is it just not a big deal? Nope, instantiating a cursor doesn't hit MySQL at all and [basically does nothing](https://github.com/PyMySQL/PyMySQL/blob/0.7.10/pymysql/cursors.py#L34-L47). > Is there any significant advantage to finding sets of transactions that don't require intermediate commits so that you don't have to get new cursors for each transaction? This is situational and difficult to give a general answer to. As <https://dev.mysql.com/doc/refman/en/optimizing-innodb-transaction-management.html> puts it, *"an application might encounter performance issues if it commits thousands of times per second, and different performance issues if it commits only every 2-3 hours"*. You pay a performance overhead for every commit, but by leaving transactions open for longer, you increase the chance of other connections having to spend time waiting for locks, increase your risk of deadlocks, and potentially increase the cost of some lookups performed by other connections. --- 1 MySQL *does* have a construct it calls a [cursor](https://dev.mysql.com/doc/refman/en/cursors.html) but they only exist inside stored procedures; they're completely different to PyMySQL cursors and are not relevant here.
8
3
56,148,199
I am new to the Ruby on Rails ecosystem so might question might be really trivial. I have set up an Active Storage on one of my model ```rb class Sedcard < ApplicationRecord has_many_attached :photos end ``` And I simply want to seed data with `Faker` in it like so: ```rb require 'faker' Sedcard.destroy_all 20.times do |_i| sedcard = Sedcard.create!( showname: Faker::Name.female_first_name, description: Faker::Lorem.paragraph(10), phone: Faker::PhoneNumber.cell_phone, birthdate: Faker::Date.birthday(18, 40), gender: Sedcard.genders[:female], is_active: Faker::Boolean.boolean ) index = Faker::Number.unique.between(1, 99) image = open("https://randomuser.me/api/portraits/women/#{index}.jpg") sedcard.photos.attach(io: image, filename: "avatar#{index}.jpg", content_type: 'image/png') end ``` The problem is that some of these records end up with multiple photos attached to them, could be 5 or 10. Most records are seeded well, they have only one photo associated, but the ones with multiple photos all follow the same pattern, they are all seeded with the exact same images.
2019/05/15
[ "https://Stackoverflow.com/questions/56148199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2828594/" ]
I found the problem myself. I was using UUID as my model's primary key which is not natively compatible with ActiveStorage. Thus, I more or less followed the instructions [here](https://www.wrburgess.com/posts/2018-02-03-1.html)
You need to purge the attachments. Try adding this snippet before destroyingthe `Sedcard`'s ``` Sedcard.all.each{ |s| s.photos.purge } ``` Ref: <https://edgeguides.rubyonrails.org/active_storage_overview.html#removing-files>
1
0
199,883
Say I have an expansion of terms containing functions `y[j,t]` and its derivatives, indexed by `j` with the index beginning at 0 whose independent variable are `t`, like so: `Expr = y[0,t]^2 + D[y[0,t],t]*y[0,t] + y[0,t]*y[1,t] + y[0,t]*D[y[1,t],t] + (y[1,t])^2*y[0,t] +` ... etc. Now I wish to define new functions indexed by `i`, call them `A[i]`, that collect all terms from the expression above such that the sum of the indices of the factors in each term sums to `i`. In the above case for the terms shown we would have for example `A[0] = y[0,t]^2 + D[y[0,t],t]*y[0,t]` `A[1] = y[0,t]*y[1,t] + y[0,t]*D[y[1,t],t]` `A[2] = (y[1,t])^2*y[0,t]` How can I get mathematica to assign these terms to these new functions automatically for all `i`? Note: If there is a better way to be indexing functions also feel free to suggest.
2019/06/06
[ "https://mathematica.stackexchange.com/questions/199883", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/41975/" ]
Since [`Show`](http://reference.wolfram.com/language/ref/Show) uses the [`PlotRange`](http://reference.wolfram.com/language/ref/PlotRange) setting from the first plot, you can just set your plot range when defining the first plot: ``` p1=LogLogPlot[ RO, {t,0.00001,0.05}, PlotRange -> {{10^-5, 10^-4}, All}, PlotStyle->{Purple} ]; Show[p1, p2] ``` or you can use a dummy plot with the desired plot range: ``` p0 = LogLogPlot[None, {t, 10^-5, 10^-4}]; Show[p0, p1, p2] ``` If you really want to set the [`PlotRange`](http://reference.wolfram.com/language/ref/PlotRange) using a [`Show`](http://reference.wolfram.com/language/ref/Show) option, than you need to realize that the [`Graphics`](http://reference.wolfram.com/language/ref/Graphics) objects produced by `p1` and `p2` don't know that "Log" scaling functions were used. So, you need to adjust the desired [`PlotRange`](http://reference.wolfram.com/language/ref/PlotRange) accordingly: ``` Show[p1, p2, PlotRange -> {Log @ {10^-5, 10^-4}, All}] ```
Your syntax is incorrect, it should be ``` Show[{p1,p2},PlotRange->{{x_min,x_max},{y_min,y_max}}] ``` If you want all in y, you can do: ``` Show[{p1,p2},PlotRange->{{10^(-5),10^(-4)},All}] ```
3
1
61,989,976
I am trying to perform JWT auth in spring boot and the request are getting stuck in redirect loop. **JWTAuthenticationProvider** ``` @Component public class JwtAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider { @Autowired private JwtUtil jwtUtil; @Override public boolean supports(Class<?> authentication) { return (JwtAuthenticationToken.class.isAssignableFrom(authentication)); } @Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { } @Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken) authentication; String token = jwtAuthenticationToken.getToken(); JwtParsedUser parsedUser = jwtUtil.parseToken(token); if (parsedUser == null) { throw new JwtException("JWT token is not valid"); } UserDetails user = User.withUsername(parsedUser.getUserName()).password("temp_password").authorities(parsedUser.getRole()).build(); return user; } ``` **JwtAuthenticationFilter** ``` public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter { public JwtAuthenticationFilter(AuthenticationManager authenticationManager) { super("/**"); this.setAuthenticationManager(authenticationManager); } @Override protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) { return true; } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { String header = request.getHeader("Authorization"); if (header == null || !header.startsWith("Bearer ")) { throw new JwtException("No JWT token found in request headers"); } String authToken = header.substring(7); JwtAuthenticationToken authRequest = new JwtAuthenticationToken(authToken); return getAuthenticationManager().authenticate(authRequest); } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { super.successfulAuthentication(request, response, chain, authResult); chain.doFilter(request, response); } } ``` **SecurityConfiguration** ``` @Configuration @EnableWebSecurity(debug = true) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private JwtAuthenticationProvider jwtAuthenticationProvider; @Autowired public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(jwtAuthenticationProvider); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().authorizeRequests().antMatchers("/secured-resource-1/**", "/secured-resource-2/**") .hasRole("ADMIN").antMatchers("/secured-resource-2/**").hasRole("ADMIN").and().formLogin() .successHandler(new AuthenticationSuccessHandler()).and().httpBasic().and().exceptionHandling() .accessDeniedHandler(new CustomAccessDeniedHandler()).authenticationEntryPoint(getBasicAuthEntryPoint()) .and() .addFilterBefore(new JwtAuthenticationFilter(authenticationManager()), FilterSecurityInterceptor.class) .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); } @Bean public CustomBasicAuthenticationEntryPoint getBasicAuthEntryPoint() { return new CustomBasicAuthenticationEntryPoint(); } } ``` **MainController** ``` @RestController public class MainController { @Autowired private JwtUtil jwtUtil; @GetMapping("/secured-resource-1") public String securedResource1() { return "Secured resource1"; } } ``` When I hit the endpoint with the valid JWT token, the code goes in a loop from Filter to provider class and ends in Error: ``` Exceeded maxRedirects. Probably stuck in a redirect loop http://localhost:8000/ error. ``` Debug logs shows the following error: ``` Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Cannot call sendError() after the response has been committed] with root cause java.lang.IllegalStateException: Cannot call sendError() after the response has been committed ``` Any suggestions what am I missing here. Thanks in advance.
2020/05/24
[ "https://Stackoverflow.com/questions/61989976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4457734/" ]
I believe the the reason for this is because you have not actually set the `AuthenticationSuccessHandler` for the bean `JwtAuthenticationFilter`, since it is not actually set it will keep looping around super and chain and later when the error needs to be sent since response is already written in `super()` `chain.doFilter` will fail because once the response is written it cannot be again written hence the error `call sendError() after the response has been committed`. To correct this in your SecurityConfiguration before setting this ``` .addFilterBefore(new JwtAuthenticationFilter(authenticationManager()), FilterSecurityInterceptor.class) ``` Instantiate the filter and set it's success manager like so ``` JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager()),FilterSecurityInterceptor.class); jwtAuthenticationFilter.setAuthenticationSuccessHandler(new CustomAuthenticationSuccessHandler()); ``` Now use the above variable to set the filter. This is a great reference project: <https://gitlab.com/palmapps/jwt-spring-security-demo/-/tree/master/>.
I solved this problem with another approach. In the JwtAuthenticationFilter class we need to set authentication object in context and call chain.doFilter. Calling super.successfulAuthentication can be skipped as we have overridden the implementation. ``` @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { //super.successfulAuthentication(request, response, chain, authResult); SecurityContextHolder.getContext().setAuthentication(authResult); chain.doFilter(request, response); } public JwtAuthenticationFilter(AuthenticationManager authenticationManager) { super("/**"); this.setAuthenticationManager(authenticationManager); //this.setAuthenticationSuccessHandler(new JwtAuthenticationSuccessHandler()); } ```
2
0
4,177,291
I have the following string: ``` Mon Sep 14 15:24:40 UTC 2009 ``` I need to format it into a string like this: ``` 14/9/2009 ``` How do I do it in Java?
2010/11/14
[ "https://Stackoverflow.com/questions/4177291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264419/" ]
Use [`SimpleDateFormat`](http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html) (click the javadoc link to see patterns) to parse the string in one pattern to a fullworthy [`Date`](http://download.oracle.com/javase/6/docs/api/java/util/Date.html) and use another one to format the parsed `Date` to a string in another pattern. ``` String string1 = "Mon Sep 14 15:24:40 UTC 2009"; Date date = new SimpleDateFormat("EEE MMM d HH:mm:ss Z yyyy").parse(string1); String string2 = new SimpleDateFormat("d/M/yyyy").format(date); System.out.println(string2); // 14/9/2009 ```
You can use SimpleDateFormat class to convert the string you have to a date object. The date format can be given in the constructor. The format method converts the string to a date object. After getting the date object, you can format it in the way you want.
4
2
4,177,291
I have the following string: ``` Mon Sep 14 15:24:40 UTC 2009 ``` I need to format it into a string like this: ``` 14/9/2009 ``` How do I do it in Java?
2010/11/14
[ "https://Stackoverflow.com/questions/4177291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264419/" ]
One liner in java 8 and above. ``` String localDateTime= LocalDateTime.parse("Mon Sep 14 15:24:40 UTC 2009", DateTimeFormatter.ofPattern("EE MMM dd HH:mm:ss z yyyy")).format(DateTimeFormatter.ofPattern("d/M/yyyy")); ```
``` Date d = new Date("Mon Sep 14 15:24:40 UTC 2009"); SimpleDateFormat f = new SimpleDateFormat("dd/M/yyyy"); String s = new String(f.format(d)); ```
0
-1
4,177,291
I have the following string: ``` Mon Sep 14 15:24:40 UTC 2009 ``` I need to format it into a string like this: ``` 14/9/2009 ``` How do I do it in Java?
2010/11/14
[ "https://Stackoverflow.com/questions/4177291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264419/" ]
You can use SimpleDateFormat class to convert the string you have to a date object. The date format can be given in the constructor. The format method converts the string to a date object. After getting the date object, you can format it in the way you want.
``` Date d = new Date("Mon Sep 14 15:24:40 UTC 2009"); SimpleDateFormat f = new SimpleDateFormat("dd/M/yyyy"); String s = new String(f.format(d)); ```
2
-1
4,177,291
I have the following string: ``` Mon Sep 14 15:24:40 UTC 2009 ``` I need to format it into a string like this: ``` 14/9/2009 ``` How do I do it in Java?
2010/11/14
[ "https://Stackoverflow.com/questions/4177291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264419/" ]
Use [`SimpleDateFormat`](http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html) (click the javadoc link to see patterns) to parse the string in one pattern to a fullworthy [`Date`](http://download.oracle.com/javase/6/docs/api/java/util/Date.html) and use another one to format the parsed `Date` to a string in another pattern. ``` String string1 = "Mon Sep 14 15:24:40 UTC 2009"; Date date = new SimpleDateFormat("EEE MMM d HH:mm:ss Z yyyy").parse(string1); String string2 = new SimpleDateFormat("d/M/yyyy").format(date); System.out.println(string2); // 14/9/2009 ```
``` Date d = new Date("Mon Sep 14 15:24:40 UTC 2009"); SimpleDateFormat f = new SimpleDateFormat("dd/M/yyyy"); String s = new String(f.format(d)); ```
4
-1
4,177,291
I have the following string: ``` Mon Sep 14 15:24:40 UTC 2009 ``` I need to format it into a string like this: ``` 14/9/2009 ``` How do I do it in Java?
2010/11/14
[ "https://Stackoverflow.com/questions/4177291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264419/" ]
You can use SimpleDateFormat class to convert the string you have to a date object. The date format can be given in the constructor. The format method converts the string to a date object. After getting the date object, you can format it in the way you want.
One liner in java 8 and above. ``` String localDateTime= LocalDateTime.parse("Mon Sep 14 15:24:40 UTC 2009", DateTimeFormatter.ofPattern("EE MMM dd HH:mm:ss z yyyy")).format(DateTimeFormatter.ofPattern("d/M/yyyy")); ```
2
0
44,169,413
[Error Message Picture](https://i.stack.imgur.com/kkbkN.png) I basically followed the instructions from the below link EXACTLY and I'm getting this damn error? I have no idea what I'm supposed to do, wtf? Do I need to create some kind of persisted method?? There were several other questions like this and after reading ALL of them they were not helpful at ALL. Please help. <https://github.com/zquestz/omniauth-google-oauth2> Omniauths Controller ``` class OmniauthCallbacksController < Devise::OmniauthCallbacksController def google_oauth2 # You need to implement the method below in your model (e.g. app/models/user.rb) @user = User.from_omniauth(request.env["omniauth.auth"]) if @user.persisted? flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google" sign_in_and_redirect @user, :event => :authentication else session["devise.google_data"] = request.env["omniauth.auth"].except(:extra) #Removing extra as it can overflow some session stores redirect_to new_user_registration_url, alert: @user.errors.full_messages.join("\n") end end end ``` User model code snippet ``` def self.from_omniauth(access_token) data = access_token.info user = User.where(:email => data["email"]).first # Uncomment the section below if you want users to be created if they don't exist # unless user # user = User.create(name: data["name"], # email: data["email"], # password: Devise.friendly_token[0,20] # ) # end user end ```
2017/05/24
[ "https://Stackoverflow.com/questions/44169413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6484371/" ]
Changed the bottom portion to: ``` def self.from_omniauth(auth) where(provider: auth.provider, uid: auth.uid).first_or_create do |user| user.email = auth.info.email user.password = Devise.friendly_token[0,20] user.name = auth.info.name # assuming the user model has a name end end ``` ran rails g migration AddOmniauthToUsers provider:string uid:string Then it went to Successfully authenticated from Google account. So I believe it works now. I think maybe the issue was I needed to add the provider and uid to the user database model?
The persisted? method is checking whether or not the user exists thereby returning nil value if no such record exists and your user model is not creating new ones. So by uncommenting the code from the example to this: ``` def self.from_omniauth(access_token) data = access_token.info user = User.where(:email => data["email"]).first # creates a new user if user email does not exist. unless user user = User.create(name: data["name"], email: data["email"], password: Devise.friendly_token[0,20] ) end user end ``` Should solve the problem of checking to see if the user exists or creating a new user.
3
0
29,130,635
I read [this](https://stackoverflow.com/questions/5842903/block-tridiagonal-matrix-python), but I wasn't able to create a (N^2 x N^2) - matrix **A** with (N x N) - *matrices* **I** on the lower and upper side-diagonal and **T** on the diagonal. I tried this ``` def prep_matrix(N): I_N = np.identity(N) NV = zeros(N*N - 1) # now I want NV[0]=NV[1]=...=NV[N-1]:=I_N ``` but I have no idea how to fill NV with my matrices. What can I do? I found a lot on how to create tridiagonal matrices with scalars, but not with matrix blocks.
2015/03/18
[ "https://Stackoverflow.com/questions/29130635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2668777/" ]
Dirty, hacky, inefficient, solution (assumes use of forms authentication): ``` public void Global_BeginRequest(object sender, EventArgs e) { if( Context.User != null && !String.IsNullOrWhiteSpace(Context.User.Identity.Name) && Context.Session != null && Context.Session["IAMTRACKED"] == null ) { Context.Session["IAMTRACKED"] = new object(); Application.Lock(); Application["UsersLoggedIn"] = Application["UsersLoggedIn"] + 1; Application.UnLock(); } } ``` At a high level, this works by, on every request, checking if the user is logged in and, if so, tags the user as logged in and increments the login. This assumes users cannot log out (if they can, you can add a similar test for users who are logged out and tracked). This is a horrible way to solve your problem, but it's a working proto-type which demonstrates that your problem is solvable. Note that this understates logins substantially after an application recycle; logins are much longer term than sessions.
I think the session items are client sided. You can create a query to count the open connections (hence you're working with a MySQL database.) Another option is to use external software (I use the tawk.to helpchat, which shows the amount of users visiting a page in realtime). You could maybe use that, making the supportchat invisible, and only putting it on paging which are accesible for loggedin users. OR Execute an update query which adds/substracts from a column in your database (using the onStart and OnEnd hooks).
1
0
29,130,635
I read [this](https://stackoverflow.com/questions/5842903/block-tridiagonal-matrix-python), but I wasn't able to create a (N^2 x N^2) - matrix **A** with (N x N) - *matrices* **I** on the lower and upper side-diagonal and **T** on the diagonal. I tried this ``` def prep_matrix(N): I_N = np.identity(N) NV = zeros(N*N - 1) # now I want NV[0]=NV[1]=...=NV[N-1]:=I_N ``` but I have no idea how to fill NV with my matrices. What can I do? I found a lot on how to create tridiagonal matrices with scalars, but not with matrix blocks.
2015/03/18
[ "https://Stackoverflow.com/questions/29130635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2668777/" ]
Dirty, hacky, inefficient, solution (assumes use of forms authentication): ``` public void Global_BeginRequest(object sender, EventArgs e) { if( Context.User != null && !String.IsNullOrWhiteSpace(Context.User.Identity.Name) && Context.Session != null && Context.Session["IAMTRACKED"] == null ) { Context.Session["IAMTRACKED"] = new object(); Application.Lock(); Application["UsersLoggedIn"] = Application["UsersLoggedIn"] + 1; Application.UnLock(); } } ``` At a high level, this works by, on every request, checking if the user is logged in and, if so, tags the user as logged in and increments the login. This assumes users cannot log out (if they can, you can add a similar test for users who are logged out and tracked). This is a horrible way to solve your problem, but it's a working proto-type which demonstrates that your problem is solvable. Note that this understates logins substantially after an application recycle; logins are much longer term than sessions.
That is the problem that you cannot do it using *Session[]* variables. You need to be using a database (or a central data source to store the total number of active users). For example, you can see in your application, when the application starts there is no `Application["UsersOnline"]` variable, you create it at the very instance. That is why, each time the application is started, the variable is initialized with a *new value*; always *1*. You can create a separate table for your application, and inside it you can then create a column to contain *OnlineUsers* value. Which can be then incremented each time the app start event is triggered. ``` public void Session_OnStart() { Application.Lock(); Application["UsersOnline"] = (int)Application["UsersOnline"] + 1; // At this position, execute an SQL command to update the value Application.UnLock(); } ``` Otherwise, for every user the session variable would have a new value, and you would not be able to accomplish this. Session variables were never designed for such purpose, you can access the variables, but you cannot rely on them for such a task. You can get more guidance about SQL commands in .NET framework, from MSDN's [SqlClient namespace library](https://msdn.microsoft.com/en-us/library/system.data.sqlclient%28v=vs.110%29.aspx).
1
0
29,130,635
I read [this](https://stackoverflow.com/questions/5842903/block-tridiagonal-matrix-python), but I wasn't able to create a (N^2 x N^2) - matrix **A** with (N x N) - *matrices* **I** on the lower and upper side-diagonal and **T** on the diagonal. I tried this ``` def prep_matrix(N): I_N = np.identity(N) NV = zeros(N*N - 1) # now I want NV[0]=NV[1]=...=NV[N-1]:=I_N ``` but I have no idea how to fill NV with my matrices. What can I do? I found a lot on how to create tridiagonal matrices with scalars, but not with matrix blocks.
2015/03/18
[ "https://Stackoverflow.com/questions/29130635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2668777/" ]
Dirty, hacky, inefficient, solution (assumes use of forms authentication): ``` public void Global_BeginRequest(object sender, EventArgs e) { if( Context.User != null && !String.IsNullOrWhiteSpace(Context.User.Identity.Name) && Context.Session != null && Context.Session["IAMTRACKED"] == null ) { Context.Session["IAMTRACKED"] = new object(); Application.Lock(); Application["UsersLoggedIn"] = Application["UsersLoggedIn"] + 1; Application.UnLock(); } } ``` At a high level, this works by, on every request, checking if the user is logged in and, if so, tags the user as logged in and increments the login. This assumes users cannot log out (if they can, you can add a similar test for users who are logged out and tracked). This is a horrible way to solve your problem, but it's a working proto-type which demonstrates that your problem is solvable. Note that this understates logins substantially after an application recycle; logins are much longer term than sessions.
Perhaps I am missing something, but why not something like this: ``` public void Session_OnStart() { Application.Lock(); if (Application["UsersOnline"] == null ) { Application["UsersOnline"] = 0 } Application["UsersOnline"] = (int)Application["UsersOnline"] + 1; Application.UnLock(); ``` }
1
0
29,130,635
I read [this](https://stackoverflow.com/questions/5842903/block-tridiagonal-matrix-python), but I wasn't able to create a (N^2 x N^2) - matrix **A** with (N x N) - *matrices* **I** on the lower and upper side-diagonal and **T** on the diagonal. I tried this ``` def prep_matrix(N): I_N = np.identity(N) NV = zeros(N*N - 1) # now I want NV[0]=NV[1]=...=NV[N-1]:=I_N ``` but I have no idea how to fill NV with my matrices. What can I do? I found a lot on how to create tridiagonal matrices with scalars, but not with matrix blocks.
2015/03/18
[ "https://Stackoverflow.com/questions/29130635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2668777/" ]
Dirty, hacky, inefficient, solution (assumes use of forms authentication): ``` public void Global_BeginRequest(object sender, EventArgs e) { if( Context.User != null && !String.IsNullOrWhiteSpace(Context.User.Identity.Name) && Context.Session != null && Context.Session["IAMTRACKED"] == null ) { Context.Session["IAMTRACKED"] = new object(); Application.Lock(); Application["UsersLoggedIn"] = Application["UsersLoggedIn"] + 1; Application.UnLock(); } } ``` At a high level, this works by, on every request, checking if the user is logged in and, if so, tags the user as logged in and increments the login. This assumes users cannot log out (if they can, you can add a similar test for users who are logged out and tracked). This is a horrible way to solve your problem, but it's a working proto-type which demonstrates that your problem is solvable. Note that this understates logins substantially after an application recycle; logins are much longer term than sessions.
Maybe I'm missing something, but is there a reason you don't just want to use something like Google Analytics? Unless you're looking for more queryable data, in which case I'd suggest what others have; store the login count to a data store. Just keep in mind you also have to have something to decrement that counter when the user either logs out or their session times out.
1
0
29,130,635
I read [this](https://stackoverflow.com/questions/5842903/block-tridiagonal-matrix-python), but I wasn't able to create a (N^2 x N^2) - matrix **A** with (N x N) - *matrices* **I** on the lower and upper side-diagonal and **T** on the diagonal. I tried this ``` def prep_matrix(N): I_N = np.identity(N) NV = zeros(N*N - 1) # now I want NV[0]=NV[1]=...=NV[N-1]:=I_N ``` but I have no idea how to fill NV with my matrices. What can I do? I found a lot on how to create tridiagonal matrices with scalars, but not with matrix blocks.
2015/03/18
[ "https://Stackoverflow.com/questions/29130635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2668777/" ]
Dirty, hacky, inefficient, solution (assumes use of forms authentication): ``` public void Global_BeginRequest(object sender, EventArgs e) { if( Context.User != null && !String.IsNullOrWhiteSpace(Context.User.Identity.Name) && Context.Session != null && Context.Session["IAMTRACKED"] == null ) { Context.Session["IAMTRACKED"] = new object(); Application.Lock(); Application["UsersLoggedIn"] = Application["UsersLoggedIn"] + 1; Application.UnLock(); } } ``` At a high level, this works by, on every request, checking if the user is logged in and, if so, tags the user as logged in and increments the login. This assumes users cannot log out (if they can, you can add a similar test for users who are logged out and tracked). This is a horrible way to solve your problem, but it's a working proto-type which demonstrates that your problem is solvable. Note that this understates logins substantially after an application recycle; logins are much longer term than sessions.
Try this. It may help you. ``` void Application_Start(object sender, EventArgs e) { Application["cnt"] = 0; Application["onlineusers"] = 0; // Code that runs on application startup } void Session_Start(object sender, EventArgs e) { Application.Lock(); Application["cnt"] = (int)Application["cnt"] + 1; if(Session["username"] != null) { Application["onlineusers"] = (int)Application["onlineusers"] + 1; } else { Application["onlineusers"] = (int)Application["onlineusers"] - 1; } Application.UnLock(); // Code that runs when a new session is started } ``` now you can display the number of users(Without Loggedin): ``` <%=Application["cnt"].ToString()%> ``` and number of online users: ``` <%=Application["onlineusers"].ToString()%> ```
1
0
25,677,031
I want Rails to automatically translate placeholder text like it does with form labels. How can I do this? Form labels are translated automatically like this: ``` = f.text_field :first_name ``` This helper uses the locale file: ``` en: active_model: models: user: attributes: first_name: Your name ``` Which outputs this HTML ``` <label for="first_name">Your name</label> ``` How can I make it so the placeholder is translated? Do I have to type the full scope like this: ``` = f.text_field :first_name, placeholder: t('.first_name', scope: 'active_model.models.user.attributes.first_name') ``` Is there are easier way?
2014/09/05
[ "https://Stackoverflow.com/questions/25677031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2615384/" ]
If using Rails 4.2, you can set the placeholder attribute to true: ``` = f.text_field :first_name, placeholder: true ``` and specify the placeholder text in the locale file like this: ``` en: helpers: placeholder: user: first_name: "Your name" ```
You can view the source on render at <http://rubydoc.info/docs/rails/ActionView/Helpers/Tags/Label> to see how Rails does it. It probably doesn't get a lot better than you have, but you could probably swipe some of Rail's logic and stick it in a helper, if you have a lot of them to do. Alternatively, you may consider using a custom form builder to remove some of the repetition in your whole form, not just placeholders.
5
0
25,677,031
I want Rails to automatically translate placeholder text like it does with form labels. How can I do this? Form labels are translated automatically like this: ``` = f.text_field :first_name ``` This helper uses the locale file: ``` en: active_model: models: user: attributes: first_name: Your name ``` Which outputs this HTML ``` <label for="first_name">Your name</label> ``` How can I make it so the placeholder is translated? Do I have to type the full scope like this: ``` = f.text_field :first_name, placeholder: t('.first_name', scope: 'active_model.models.user.attributes.first_name') ``` Is there are easier way?
2014/09/05
[ "https://Stackoverflow.com/questions/25677031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2615384/" ]
With Rails >= 4.2, you can set the placeholder attribute to true `= f.text_field :first_name, placeholder: true` and in your local file (e.g. en.yml): ``` ru: activerecord: attributes: user: first_name: Your name ``` otherwise (Rails >= 3.0) I think you can write something like this: ``` = f.text_field :attr, placeholder: "#{I18n.t 'activerecord.attributes.user.first_name'}" ```
You can view the source on render at <http://rubydoc.info/docs/rails/ActionView/Helpers/Tags/Label> to see how Rails does it. It probably doesn't get a lot better than you have, but you could probably swipe some of Rail's logic and stick it in a helper, if you have a lot of them to do. Alternatively, you may consider using a custom form builder to remove some of the repetition in your whole form, not just placeholders.
1
0
25,677,031
I want Rails to automatically translate placeholder text like it does with form labels. How can I do this? Form labels are translated automatically like this: ``` = f.text_field :first_name ``` This helper uses the locale file: ``` en: active_model: models: user: attributes: first_name: Your name ``` Which outputs this HTML ``` <label for="first_name">Your name</label> ``` How can I make it so the placeholder is translated? Do I have to type the full scope like this: ``` = f.text_field :first_name, placeholder: t('.first_name', scope: 'active_model.models.user.attributes.first_name') ``` Is there are easier way?
2014/09/05
[ "https://Stackoverflow.com/questions/25677031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2615384/" ]
If using Rails 4.2, you can set the placeholder attribute to true: ``` = f.text_field :first_name, placeholder: true ``` and specify the placeholder text in the locale file like this: ``` en: helpers: placeholder: user: first_name: "Your name" ```
With Rails >= 4.2, you can set the placeholder attribute to true `= f.text_field :first_name, placeholder: true` and in your local file (e.g. en.yml): ``` ru: activerecord: attributes: user: first_name: Your name ``` otherwise (Rails >= 3.0) I think you can write something like this: ``` = f.text_field :attr, placeholder: "#{I18n.t 'activerecord.attributes.user.first_name'}" ```
5
1
3,829,150
If I call `console.log('something');` from the popup page, or any script included off that it works fine. However as the background page is not directly run off the popup page it is not included in the console. Is there a way that I can get `console.log()`'s in the background page to show up in the console for the popup page? is there any way to, from the background page call a function in the popup page?
2010/09/30
[ "https://Stackoverflow.com/questions/3829150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383759/" ]
You can open the background page's console if you click on the "background.html" link in the extensions list. To access the background page that corresponds to your extensions open `Settings / Extensions` or open a new tab and enter `chrome://extensions`. You will see something like this screenshot. ![Chrome extensions dialogue](https://i.stack.imgur.com/Xulbx.png) Under your extension click on the link `background page`. This opens a new window. For the **[context menu sample](https://developer.chrome.com/extensions/samples#context-menus-sample)** the window has the title: `_generated_background_page.html`.
Curently with Manifest 3 and service worker, you just need to go to `Extensions Page / Details` and just click `Inspect Views / Service Worker`.
8
1
3,829,150
If I call `console.log('something');` from the popup page, or any script included off that it works fine. However as the background page is not directly run off the popup page it is not included in the console. Is there a way that I can get `console.log()`'s in the background page to show up in the console for the popup page? is there any way to, from the background page call a function in the popup page?
2010/09/30
[ "https://Stackoverflow.com/questions/3829150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383759/" ]
To answer your question directly, when you call `console.log("something")` from the background, this message is logged, to the background page's console. To view it, you may go to `chrome://extensions/` and click on that `inspect view` under your extension. When you click the popup, it's loaded into the current page, thus the console.log should show log message in the current page.
It's an old post, with already good answers, but I add my two bits. I don't like to use console.log, I'd rather use a logger that logs to the console, or wherever I want, so I have a module defining a log function a bit like this one ``` function log(...args) { console.log(...args); chrome.extension.getBackgroundPage().console.log(...args); } ``` When I call log("this is my log") it will write the message both in the popup console and the background console. The advantage is to be able to change the behaviour of the logs without having to change the code (like disabling logs for production, etc...)
6
2