qid
int64
1
74.7M
question
stringlengths
22
28.7k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
24
26.4k
response_k
stringlengths
25
24.2k
632,181
I've created a custom workflow which creates a task item when the workflow is kicked off. [alt text http://img19.imageshack.us/img19/2862/screenshot310200942100p.png](http://img19.imageshack.us/img19/2862/screenshot310200942100p.png) I've also created a few custom content types for the document library and task list. For the document library: First, I add a document library and configure it to allow custom content types. Then I add my content type, which is based off the document content type. After, I add a workflow under workflow settings. Here, I select my custom workflow, give it a name and tell sharepoint to create a New task list to store the tasks in. For the task list: Now that I have a sharepoint created task list, I go there and allow custom content types and make sure "Send e-mail when ownership is assigned?" is set to Yes. Then I add my two custom content types which are both based off a workflow task content type. Thats all I should do. When I start my workflow, it does add the approval task (I'm using a CreateTaskWithContentType activity which is named createApprovalTask), but no email is sent out for the created task. The code I'm using in the createApprovalTask activity is: ``` // make a new GUID for this task createApprovalTask_TaskId = Guid.NewGuid(); // set simple properties of task createApprovalTask.TaskProperties.AssignedTo = "a valid domain\user"; createApprovalTask.TaskProperties.Title = "Review Contract: " + approvalWorkflowActivated_WorkflowProperties.Item.DisplayName; createApprovalTask.TaskProperties.SendEmailNotification = true; ``` If I create a document library and use one of Sharepoint's built-in workflows (Approval for example), and tell it to create a task list for it, when an item is added to that list, it sends out the email correctly. So, the setting for the outgoing mail server are correct, as we're receiving other emails just fine. I'm using a SendEmail activity right after the createApprovalTask activity to send an email back to the submitter telling them we've received their approval request. The code for that is something similar to: ``` sendApprovalRecievedEmail.Body = emailBody; sendApprovalRecievedEmail.Subject = emailSubject; sendApprovalRecievedEmail.To = emailTo; sendApprovalRecievedEmail.From = emailFrom; ``` This works, so the submitter receives their custom email, but the task owner never receives the task item email.
2009/03/10
[ "https://Stackoverflow.com/questions/632181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34253/" ]
you have to make sharepoint outgoing email settings properly. example is shown in below link <http://sharepoint-amila.blogspot.com/2008/02/outgoin-email-settings.html> if you need to send an email through the c#.net code you can use below method to send emails in custom workflows. SPUtility.SendEmail Method (Microsoft.SharePoint.Utilities) example is shown in below link <http://www.sharepoint-amila.blogspot.com/>
Is it possible to point out a SharePoint user by "domain\user" like you do with createApprovalTask.TaskProperties.AssignedTo? Isnt the ID required? "id;#domain\username"
632,181
I've created a custom workflow which creates a task item when the workflow is kicked off. [alt text http://img19.imageshack.us/img19/2862/screenshot310200942100p.png](http://img19.imageshack.us/img19/2862/screenshot310200942100p.png) I've also created a few custom content types for the document library and task list. For the document library: First, I add a document library and configure it to allow custom content types. Then I add my content type, which is based off the document content type. After, I add a workflow under workflow settings. Here, I select my custom workflow, give it a name and tell sharepoint to create a New task list to store the tasks in. For the task list: Now that I have a sharepoint created task list, I go there and allow custom content types and make sure "Send e-mail when ownership is assigned?" is set to Yes. Then I add my two custom content types which are both based off a workflow task content type. Thats all I should do. When I start my workflow, it does add the approval task (I'm using a CreateTaskWithContentType activity which is named createApprovalTask), but no email is sent out for the created task. The code I'm using in the createApprovalTask activity is: ``` // make a new GUID for this task createApprovalTask_TaskId = Guid.NewGuid(); // set simple properties of task createApprovalTask.TaskProperties.AssignedTo = "a valid domain\user"; createApprovalTask.TaskProperties.Title = "Review Contract: " + approvalWorkflowActivated_WorkflowProperties.Item.DisplayName; createApprovalTask.TaskProperties.SendEmailNotification = true; ``` If I create a document library and use one of Sharepoint's built-in workflows (Approval for example), and tell it to create a task list for it, when an item is added to that list, it sends out the email correctly. So, the setting for the outgoing mail server are correct, as we're receiving other emails just fine. I'm using a SendEmail activity right after the createApprovalTask activity to send an email back to the submitter telling them we've received their approval request. The code for that is something similar to: ``` sendApprovalRecievedEmail.Body = emailBody; sendApprovalRecievedEmail.Subject = emailSubject; sendApprovalRecievedEmail.To = emailTo; sendApprovalRecievedEmail.From = emailFrom; ``` This works, so the submitter receives their custom email, but the task owner never receives the task item email.
2009/03/10
[ "https://Stackoverflow.com/questions/632181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34253/" ]
Unfortunately, our mail servers were blocking the emails for some reason. I wasted a good 2 1/2 days searching around for this problem...and it turns out our IT department didn't have their sh\*t together. Thanks everyone.
Is it possible to point out a SharePoint user by "domain\user" like you do with createApprovalTask.TaskProperties.AssignedTo? Isnt the ID required? "id;#domain\username"
632,181
I've created a custom workflow which creates a task item when the workflow is kicked off. [alt text http://img19.imageshack.us/img19/2862/screenshot310200942100p.png](http://img19.imageshack.us/img19/2862/screenshot310200942100p.png) I've also created a few custom content types for the document library and task list. For the document library: First, I add a document library and configure it to allow custom content types. Then I add my content type, which is based off the document content type. After, I add a workflow under workflow settings. Here, I select my custom workflow, give it a name and tell sharepoint to create a New task list to store the tasks in. For the task list: Now that I have a sharepoint created task list, I go there and allow custom content types and make sure "Send e-mail when ownership is assigned?" is set to Yes. Then I add my two custom content types which are both based off a workflow task content type. Thats all I should do. When I start my workflow, it does add the approval task (I'm using a CreateTaskWithContentType activity which is named createApprovalTask), but no email is sent out for the created task. The code I'm using in the createApprovalTask activity is: ``` // make a new GUID for this task createApprovalTask_TaskId = Guid.NewGuid(); // set simple properties of task createApprovalTask.TaskProperties.AssignedTo = "a valid domain\user"; createApprovalTask.TaskProperties.Title = "Review Contract: " + approvalWorkflowActivated_WorkflowProperties.Item.DisplayName; createApprovalTask.TaskProperties.SendEmailNotification = true; ``` If I create a document library and use one of Sharepoint's built-in workflows (Approval for example), and tell it to create a task list for it, when an item is added to that list, it sends out the email correctly. So, the setting for the outgoing mail server are correct, as we're receiving other emails just fine. I'm using a SendEmail activity right after the createApprovalTask activity to send an email back to the submitter telling them we've received their approval request. The code for that is something similar to: ``` sendApprovalRecievedEmail.Body = emailBody; sendApprovalRecievedEmail.Subject = emailSubject; sendApprovalRecievedEmail.To = emailTo; sendApprovalRecievedEmail.From = emailFrom; ``` This works, so the submitter receives their custom email, but the task owner never receives the task item email.
2009/03/10
[ "https://Stackoverflow.com/questions/632181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34253/" ]
Unfortunately, our mail servers were blocking the emails for some reason. I wasted a good 2 1/2 days searching around for this problem...and it turns out our IT department didn't have their sh\*t together. Thanks everyone.
you have to make sharepoint outgoing email settings properly. example is shown in below link <http://sharepoint-amila.blogspot.com/2008/02/outgoin-email-settings.html> if you need to send an email through the c#.net code you can use below method to send emails in custom workflows. SPUtility.SendEmail Method (Microsoft.SharePoint.Utilities) example is shown in below link <http://www.sharepoint-amila.blogspot.com/>
16,237,561
I have a list of cases containing agencies. All agencies contain tasks which have a status assigned to it. 0 = complete, 1 = ongoing and 2 = overdue. I am trying to show for all cases if there is any tasks overdue. At the moment my query shows the status as 1, even though there are some tasks overdue. SQL FIDDLE HERE <http://sqlfiddle.com/#!2/a4394/3> I don't know what I need to change in order to pull out the correct data. Any ideas? Any help would be greatly appreciated!!
2013/04/26
[ "https://Stackoverflow.com/questions/16237561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2187103/" ]
Your query is right, the problem is that you're getting info from multiple tables but, you don't have enough records in all of them, basically you have IDs on your `cases_agency_association` table up to 6, and the records from your `cases_task_association` table where the `status` is 2, all have IDs greater than 6...
Would not this solve your basic problem: ``` select * from `cases_task_association` where status =2; ``` This is without the joins etc, but the query above is the base for providing all cases that are overdue and not completed.
16,237,561
I have a list of cases containing agencies. All agencies contain tasks which have a status assigned to it. 0 = complete, 1 = ongoing and 2 = overdue. I am trying to show for all cases if there is any tasks overdue. At the moment my query shows the status as 1, even though there are some tasks overdue. SQL FIDDLE HERE <http://sqlfiddle.com/#!2/a4394/3> I don't know what I need to change in order to pull out the correct data. Any ideas? Any help would be greatly appreciated!!
2013/04/26
[ "https://Stackoverflow.com/questions/16237561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2187103/" ]
Ignoring that you're writing a MySQL-only `SELECT`, your joins are wrong; you're joining `cc.case_ID` on `caa.ID` when you actually want `caa.case_ID`: ``` SELECT cc . * , a.ID, MAX(cta.status) AS current_status FROM cases_complete cc, agencies a, cases_agency_association caa, cases_task_association cta WHERE cc.case_ID = caa.case_ID AND caa.agency_ID = a.ID AND cta.agency_association_ID = caa.ID GROUP BY cc.case_ID ``` However @meewoK's approach, and the comment about not abusing `GROUP BY` are both worth thinking through from the point of view of coming up with something clearer, more maintainable, and hopefully more portable / future compatible as well.
Would not this solve your basic problem: ``` select * from `cases_task_association` where status =2; ``` This is without the joins etc, but the query above is the base for providing all cases that are overdue and not completed.
16,237,561
I have a list of cases containing agencies. All agencies contain tasks which have a status assigned to it. 0 = complete, 1 = ongoing and 2 = overdue. I am trying to show for all cases if there is any tasks overdue. At the moment my query shows the status as 1, even though there are some tasks overdue. SQL FIDDLE HERE <http://sqlfiddle.com/#!2/a4394/3> I don't know what I need to change in order to pull out the correct data. Any ideas? Any help would be greatly appreciated!!
2013/04/26
[ "https://Stackoverflow.com/questions/16237561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2187103/" ]
Ignoring that you're writing a MySQL-only `SELECT`, your joins are wrong; you're joining `cc.case_ID` on `caa.ID` when you actually want `caa.case_ID`: ``` SELECT cc . * , a.ID, MAX(cta.status) AS current_status FROM cases_complete cc, agencies a, cases_agency_association caa, cases_task_association cta WHERE cc.case_ID = caa.case_ID AND caa.agency_ID = a.ID AND cta.agency_association_ID = caa.ID GROUP BY cc.case_ID ``` However @meewoK's approach, and the comment about not abusing `GROUP BY` are both worth thinking through from the point of view of coming up with something clearer, more maintainable, and hopefully more portable / future compatible as well.
Your query is right, the problem is that you're getting info from multiple tables but, you don't have enough records in all of them, basically you have IDs on your `cases_agency_association` table up to 6, and the records from your `cases_task_association` table where the `status` is 2, all have IDs greater than 6...
2,024
> > On the night of 9/10 July, the Western Allies mounted an amphibious > invasion of Sicily. Three days later, Hitler summoned Günther von > Kluge and Erich von Manstein to his Wolfsschanze headquarters in East > Prussia and declared his intention to "temporarily" call off [Operation Zitadelle](https://en.wikipedia.org/wiki/Operation_Citadel). **Von Manstein attempted to dissuade him, arguing that > Zitadelle was on the brink of victory: "on no account should we let go > of the enemy until the mobile reserves which he had committed were > decisively beaten"**. In an unusual reversal of their roles, Hitler gave > von Manstein a few more days to continue the offensive, but on 17 > July, he ordered a withdrawal and canceled the operation. He then > ordered the entire SS Panzer Corps to be transferred to Italy.[87] > > > While Hitler often made notoriously poor judgments for all the wrong reasons, did he make the right decision for Germany (for the wrong reason) in this specific isolated case? Was Zitadelle really on the brink of victory as Von Manstein believed?
2012/05/12
[ "https://history.stackexchange.com/questions/2024", "https://history.stackexchange.com", "https://history.stackexchange.com/users/852/" ]
Hitler was right in this instance. It was Manstein that extended the battle too far. The "official" reason for the offensive, was to recapture the city of Kursk. That was within the reach of the Germans. The REAL purpose of the offensive was to cut off the Russian salient, of which Kursk was the tip. The reason this didn't work was that the Russians concentrated their defense lines at the BASE of salient (south and north of Orel and Belgorod), on either side, instead of concentrating their forces at Kursk, where they could be cut off. What Manstein should have done was to "snap off" Kursk at the tip of the salient, then "declare victory and go home." What he actually did was to WIDEN the front by moving the German forces east to Prokhorovka. This turned the battle from one of decision (which favored the Germans) to one of attrition (which favored the Russians), who could trade their more numerous tanks for German vehicles at a rate of about one to one. This was because Manstein had let the Kursk operation deteriorate from the [1] "set piece battle" to a "meeting engagement" in which Germany had no advantage. So Hitler was right to stop the Kursk operation, with or without regard to what was happening in Italy. [1] <https://english.stackexchange.com/questions/48646/what-is-the-meaning-and-origin-of-set-piece-battle>
The whole operation was doomed from the start because the Allies at Bletchley Park had deciphered the German plans for the attack. The British gave the Russians ample warning time of this, although the Russians already knew about it as they had spies of their own within British intelligence. <http://www.colossus-computer.com/colossus1.html> Given that the Russians had several weeks forewarning, they amassed tanks, guns and soldiers in great number and prepared many layers of defence lines to defeat the German assault. Had the Germans never launched Zitadelle they would have preserved their precious tanks and probably prolonged the war although the end result would have been the same. Hitler made the right decision on this occasion, by calling the operation off, but he should have done so sooner.
2,024
> > On the night of 9/10 July, the Western Allies mounted an amphibious > invasion of Sicily. Three days later, Hitler summoned Günther von > Kluge and Erich von Manstein to his Wolfsschanze headquarters in East > Prussia and declared his intention to "temporarily" call off [Operation Zitadelle](https://en.wikipedia.org/wiki/Operation_Citadel). **Von Manstein attempted to dissuade him, arguing that > Zitadelle was on the brink of victory: "on no account should we let go > of the enemy until the mobile reserves which he had committed were > decisively beaten"**. In an unusual reversal of their roles, Hitler gave > von Manstein a few more days to continue the offensive, but on 17 > July, he ordered a withdrawal and canceled the operation. He then > ordered the entire SS Panzer Corps to be transferred to Italy.[87] > > > While Hitler often made notoriously poor judgments for all the wrong reasons, did he make the right decision for Germany (for the wrong reason) in this specific isolated case? Was Zitadelle really on the brink of victory as Von Manstein believed?
2012/05/12
[ "https://history.stackexchange.com/questions/2024", "https://history.stackexchange.com", "https://history.stackexchange.com/users/852/" ]
Hitler was right in this instance. It was Manstein that extended the battle too far. The "official" reason for the offensive, was to recapture the city of Kursk. That was within the reach of the Germans. The REAL purpose of the offensive was to cut off the Russian salient, of which Kursk was the tip. The reason this didn't work was that the Russians concentrated their defense lines at the BASE of salient (south and north of Orel and Belgorod), on either side, instead of concentrating their forces at Kursk, where they could be cut off. What Manstein should have done was to "snap off" Kursk at the tip of the salient, then "declare victory and go home." What he actually did was to WIDEN the front by moving the German forces east to Prokhorovka. This turned the battle from one of decision (which favored the Germans) to one of attrition (which favored the Russians), who could trade their more numerous tanks for German vehicles at a rate of about one to one. This was because Manstein had let the Kursk operation deteriorate from the [1] "set piece battle" to a "meeting engagement" in which Germany had no advantage. So Hitler was right to stop the Kursk operation, with or without regard to what was happening in Italy. [1] <https://english.stackexchange.com/questions/48646/what-is-the-meaning-and-origin-of-set-piece-battle>
I think he was only partially right and this is because the units transferred were SS units. In the east, the SS fought both its racial and ideological enemies (the Bolshevik Jewry; which was mostly propaganda, but people believed it). There it was in its element, both as regards the savagery of fighting and the atrocities inflicted on the civilian population. In light of later massive surrendering of Germans to the western Allies, but stiff resistance against the Russians, no SS unit should probably ever have been transferred from the East, except for rest and refit.
2,024
> > On the night of 9/10 July, the Western Allies mounted an amphibious > invasion of Sicily. Three days later, Hitler summoned Günther von > Kluge and Erich von Manstein to his Wolfsschanze headquarters in East > Prussia and declared his intention to "temporarily" call off [Operation Zitadelle](https://en.wikipedia.org/wiki/Operation_Citadel). **Von Manstein attempted to dissuade him, arguing that > Zitadelle was on the brink of victory: "on no account should we let go > of the enemy until the mobile reserves which he had committed were > decisively beaten"**. In an unusual reversal of their roles, Hitler gave > von Manstein a few more days to continue the offensive, but on 17 > July, he ordered a withdrawal and canceled the operation. He then > ordered the entire SS Panzer Corps to be transferred to Italy.[87] > > > While Hitler often made notoriously poor judgments for all the wrong reasons, did he make the right decision for Germany (for the wrong reason) in this specific isolated case? Was Zitadelle really on the brink of victory as Von Manstein believed?
2012/05/12
[ "https://history.stackexchange.com/questions/2024", "https://history.stackexchange.com", "https://history.stackexchange.com/users/852/" ]
Hitler was right in this instance. It was Manstein that extended the battle too far. The "official" reason for the offensive, was to recapture the city of Kursk. That was within the reach of the Germans. The REAL purpose of the offensive was to cut off the Russian salient, of which Kursk was the tip. The reason this didn't work was that the Russians concentrated their defense lines at the BASE of salient (south and north of Orel and Belgorod), on either side, instead of concentrating their forces at Kursk, where they could be cut off. What Manstein should have done was to "snap off" Kursk at the tip of the salient, then "declare victory and go home." What he actually did was to WIDEN the front by moving the German forces east to Prokhorovka. This turned the battle from one of decision (which favored the Germans) to one of attrition (which favored the Russians), who could trade their more numerous tanks for German vehicles at a rate of about one to one. This was because Manstein had let the Kursk operation deteriorate from the [1] "set piece battle" to a "meeting engagement" in which Germany had no advantage. So Hitler was right to stop the Kursk operation, with or without regard to what was happening in Italy. [1] <https://english.stackexchange.com/questions/48646/what-is-the-meaning-and-origin-of-set-piece-battle>
I believe that the underlying intention of the High command was never to close the kursk salient with 2 pincers. This has been lauded as gospel for ages and ages and stands in the way of Mansteins thinking. I believe that the Soviet High command make a key strategic error when they positioned the bulk of their armour too close to the Northern pincer. The Northern "Pincer" was not the main pincer, in fact it's firepower was more defensive in charachter with all Ferdinands placed there and the defensive Hagen position available to fall back to which they did in good order. (Model had soaked up significant attacks at the Meat grinder of Rshev with the 9th army and the expectation was that he was to do it again) So essentially one sees what actually occurred in the Invasion of France in 1940 with a sickle through the ardennes now being the Southern Pincer. von Manstein having the core of the firepower, the massive SS corps and Gross Deutschlkand etc down South. Unlike the fiction of Prokhoroka being a Soviet victory it wasn't the 5th Guards etc was wasted...the Soviets actually had committed all reserves in the South and the German Armoured formations were both intact and had reserves. There was no substantive threat to the Eastern flank as those Soviet reserves had already been committed and slaughtered. Whilst Von Manstein had 3 additional panzer divisions in reserve. Its quiet clear that a break through could have been made and given that the rest of the Soviet armoured reserve units were out of position trying to break through against Model in the North. They would not have been able to turn South and get to von Manstein in time. The effect would have been a hammer blow comming up from the South against the soviet armoured units and pressed them against Models Hagen line (Anvil). The distance involved was open tank country...German tanks were being repaired at such a rate that in fact there was almost no difference between tank avaialability on the 13th than there was 5 days earlier...If Von Manstein could snatch a victory at Kharkiv outnumbered 8:1 what he would have done at Kursk could certainly have been within his grasp. As more and more detail comes out of the battle we realize that the Soviets were simply lieing lieing at infinitum Stalin had prepared the script before the battle even started. Hitler essentially pulled out as he did at the Invasion of France where Guderian didn't stop at Sedan but kept up the charge to Dunkirk where Adolf again made the wrong call.
2,024
> > On the night of 9/10 July, the Western Allies mounted an amphibious > invasion of Sicily. Three days later, Hitler summoned Günther von > Kluge and Erich von Manstein to his Wolfsschanze headquarters in East > Prussia and declared his intention to "temporarily" call off [Operation Zitadelle](https://en.wikipedia.org/wiki/Operation_Citadel). **Von Manstein attempted to dissuade him, arguing that > Zitadelle was on the brink of victory: "on no account should we let go > of the enemy until the mobile reserves which he had committed were > decisively beaten"**. In an unusual reversal of their roles, Hitler gave > von Manstein a few more days to continue the offensive, but on 17 > July, he ordered a withdrawal and canceled the operation. He then > ordered the entire SS Panzer Corps to be transferred to Italy.[87] > > > While Hitler often made notoriously poor judgments for all the wrong reasons, did he make the right decision for Germany (for the wrong reason) in this specific isolated case? Was Zitadelle really on the brink of victory as Von Manstein believed?
2012/05/12
[ "https://history.stackexchange.com/questions/2024", "https://history.stackexchange.com", "https://history.stackexchange.com/users/852/" ]
Hitler was right in this instance. It was Manstein that extended the battle too far. The "official" reason for the offensive, was to recapture the city of Kursk. That was within the reach of the Germans. The REAL purpose of the offensive was to cut off the Russian salient, of which Kursk was the tip. The reason this didn't work was that the Russians concentrated their defense lines at the BASE of salient (south and north of Orel and Belgorod), on either side, instead of concentrating their forces at Kursk, where they could be cut off. What Manstein should have done was to "snap off" Kursk at the tip of the salient, then "declare victory and go home." What he actually did was to WIDEN the front by moving the German forces east to Prokhorovka. This turned the battle from one of decision (which favored the Germans) to one of attrition (which favored the Russians), who could trade their more numerous tanks for German vehicles at a rate of about one to one. This was because Manstein had let the Kursk operation deteriorate from the [1] "set piece battle" to a "meeting engagement" in which Germany had no advantage. So Hitler was right to stop the Kursk operation, with or without regard to what was happening in Italy. [1] <https://english.stackexchange.com/questions/48646/what-is-the-meaning-and-origin-of-set-piece-battle>
Kursk was an exercise in futility by July of 1943. Giving the Soviets 4-5 months to prepare the defenses around Kursk made the whole operation a waste of resources and time. What Germany SHOULD HAVE done was to spend 1943 on the defensive as Guderian recommended. "How many people do you think even know where Kursk is? It's a matter of profound indifference to the world whether we hold Kursk or not..." But what about handing the initiatives to the Allies? That can be solved trivially. All Hitler had to do to prevent the Soviet from launching a massive attack in the summer, was to pretend that he was going to do an all out attack on Kursk (which was widely expected, as anyone with a map could see the value of such an attack). And then did what he always did, delay the attack and delay, and delay, until the best of the campaigning season is over. Given his track record of delaying his offensives repeatedly, no one would doubt that the planned attack was coming. But to answer the original question. Was Hitler right to cancel? Yes. He shouldn't even have authorized the offensive. While Manstein was making decent progress in the South. Model's northern arm was totally spent (by the time Hitler made his decision). Given the weather that followed (pelting rain) it would have been unlikely that Manstein could have broken through all the way to link up with Model. And even if he was able to do that, there was no real reason to believe there would have been enough German troops to prevent the Russian from reaching the newly cut off in the Kursk pocket. The problem was, the Soviet still had significant reserve left (the Steppe Front), and the Germans didn't.
2,024
> > On the night of 9/10 July, the Western Allies mounted an amphibious > invasion of Sicily. Three days later, Hitler summoned Günther von > Kluge and Erich von Manstein to his Wolfsschanze headquarters in East > Prussia and declared his intention to "temporarily" call off [Operation Zitadelle](https://en.wikipedia.org/wiki/Operation_Citadel). **Von Manstein attempted to dissuade him, arguing that > Zitadelle was on the brink of victory: "on no account should we let go > of the enemy until the mobile reserves which he had committed were > decisively beaten"**. In an unusual reversal of their roles, Hitler gave > von Manstein a few more days to continue the offensive, but on 17 > July, he ordered a withdrawal and canceled the operation. He then > ordered the entire SS Panzer Corps to be transferred to Italy.[87] > > > While Hitler often made notoriously poor judgments for all the wrong reasons, did he make the right decision for Germany (for the wrong reason) in this specific isolated case? Was Zitadelle really on the brink of victory as Von Manstein believed?
2012/05/12
[ "https://history.stackexchange.com/questions/2024", "https://history.stackexchange.com", "https://history.stackexchange.com/users/852/" ]
The whole operation was doomed from the start because the Allies at Bletchley Park had deciphered the German plans for the attack. The British gave the Russians ample warning time of this, although the Russians already knew about it as they had spies of their own within British intelligence. <http://www.colossus-computer.com/colossus1.html> Given that the Russians had several weeks forewarning, they amassed tanks, guns and soldiers in great number and prepared many layers of defence lines to defeat the German assault. Had the Germans never launched Zitadelle they would have preserved their precious tanks and probably prolonged the war although the end result would have been the same. Hitler made the right decision on this occasion, by calling the operation off, but he should have done so sooner.
I think he was only partially right and this is because the units transferred were SS units. In the east, the SS fought both its racial and ideological enemies (the Bolshevik Jewry; which was mostly propaganda, but people believed it). There it was in its element, both as regards the savagery of fighting and the atrocities inflicted on the civilian population. In light of later massive surrendering of Germans to the western Allies, but stiff resistance against the Russians, no SS unit should probably ever have been transferred from the East, except for rest and refit.
2,024
> > On the night of 9/10 July, the Western Allies mounted an amphibious > invasion of Sicily. Three days later, Hitler summoned Günther von > Kluge and Erich von Manstein to his Wolfsschanze headquarters in East > Prussia and declared his intention to "temporarily" call off [Operation Zitadelle](https://en.wikipedia.org/wiki/Operation_Citadel). **Von Manstein attempted to dissuade him, arguing that > Zitadelle was on the brink of victory: "on no account should we let go > of the enemy until the mobile reserves which he had committed were > decisively beaten"**. In an unusual reversal of their roles, Hitler gave > von Manstein a few more days to continue the offensive, but on 17 > July, he ordered a withdrawal and canceled the operation. He then > ordered the entire SS Panzer Corps to be transferred to Italy.[87] > > > While Hitler often made notoriously poor judgments for all the wrong reasons, did he make the right decision for Germany (for the wrong reason) in this specific isolated case? Was Zitadelle really on the brink of victory as Von Manstein believed?
2012/05/12
[ "https://history.stackexchange.com/questions/2024", "https://history.stackexchange.com", "https://history.stackexchange.com/users/852/" ]
The whole operation was doomed from the start because the Allies at Bletchley Park had deciphered the German plans for the attack. The British gave the Russians ample warning time of this, although the Russians already knew about it as they had spies of their own within British intelligence. <http://www.colossus-computer.com/colossus1.html> Given that the Russians had several weeks forewarning, they amassed tanks, guns and soldiers in great number and prepared many layers of defence lines to defeat the German assault. Had the Germans never launched Zitadelle they would have preserved their precious tanks and probably prolonged the war although the end result would have been the same. Hitler made the right decision on this occasion, by calling the operation off, but he should have done so sooner.
I believe that the underlying intention of the High command was never to close the kursk salient with 2 pincers. This has been lauded as gospel for ages and ages and stands in the way of Mansteins thinking. I believe that the Soviet High command make a key strategic error when they positioned the bulk of their armour too close to the Northern pincer. The Northern "Pincer" was not the main pincer, in fact it's firepower was more defensive in charachter with all Ferdinands placed there and the defensive Hagen position available to fall back to which they did in good order. (Model had soaked up significant attacks at the Meat grinder of Rshev with the 9th army and the expectation was that he was to do it again) So essentially one sees what actually occurred in the Invasion of France in 1940 with a sickle through the ardennes now being the Southern Pincer. von Manstein having the core of the firepower, the massive SS corps and Gross Deutschlkand etc down South. Unlike the fiction of Prokhoroka being a Soviet victory it wasn't the 5th Guards etc was wasted...the Soviets actually had committed all reserves in the South and the German Armoured formations were both intact and had reserves. There was no substantive threat to the Eastern flank as those Soviet reserves had already been committed and slaughtered. Whilst Von Manstein had 3 additional panzer divisions in reserve. Its quiet clear that a break through could have been made and given that the rest of the Soviet armoured reserve units were out of position trying to break through against Model in the North. They would not have been able to turn South and get to von Manstein in time. The effect would have been a hammer blow comming up from the South against the soviet armoured units and pressed them against Models Hagen line (Anvil). The distance involved was open tank country...German tanks were being repaired at such a rate that in fact there was almost no difference between tank avaialability on the 13th than there was 5 days earlier...If Von Manstein could snatch a victory at Kharkiv outnumbered 8:1 what he would have done at Kursk could certainly have been within his grasp. As more and more detail comes out of the battle we realize that the Soviets were simply lieing lieing at infinitum Stalin had prepared the script before the battle even started. Hitler essentially pulled out as he did at the Invasion of France where Guderian didn't stop at Sedan but kept up the charge to Dunkirk where Adolf again made the wrong call.
2,024
> > On the night of 9/10 July, the Western Allies mounted an amphibious > invasion of Sicily. Three days later, Hitler summoned Günther von > Kluge and Erich von Manstein to his Wolfsschanze headquarters in East > Prussia and declared his intention to "temporarily" call off [Operation Zitadelle](https://en.wikipedia.org/wiki/Operation_Citadel). **Von Manstein attempted to dissuade him, arguing that > Zitadelle was on the brink of victory: "on no account should we let go > of the enemy until the mobile reserves which he had committed were > decisively beaten"**. In an unusual reversal of their roles, Hitler gave > von Manstein a few more days to continue the offensive, but on 17 > July, he ordered a withdrawal and canceled the operation. He then > ordered the entire SS Panzer Corps to be transferred to Italy.[87] > > > While Hitler often made notoriously poor judgments for all the wrong reasons, did he make the right decision for Germany (for the wrong reason) in this specific isolated case? Was Zitadelle really on the brink of victory as Von Manstein believed?
2012/05/12
[ "https://history.stackexchange.com/questions/2024", "https://history.stackexchange.com", "https://history.stackexchange.com/users/852/" ]
The whole operation was doomed from the start because the Allies at Bletchley Park had deciphered the German plans for the attack. The British gave the Russians ample warning time of this, although the Russians already knew about it as they had spies of their own within British intelligence. <http://www.colossus-computer.com/colossus1.html> Given that the Russians had several weeks forewarning, they amassed tanks, guns and soldiers in great number and prepared many layers of defence lines to defeat the German assault. Had the Germans never launched Zitadelle they would have preserved their precious tanks and probably prolonged the war although the end result would have been the same. Hitler made the right decision on this occasion, by calling the operation off, but he should have done so sooner.
Kursk was an exercise in futility by July of 1943. Giving the Soviets 4-5 months to prepare the defenses around Kursk made the whole operation a waste of resources and time. What Germany SHOULD HAVE done was to spend 1943 on the defensive as Guderian recommended. "How many people do you think even know where Kursk is? It's a matter of profound indifference to the world whether we hold Kursk or not..." But what about handing the initiatives to the Allies? That can be solved trivially. All Hitler had to do to prevent the Soviet from launching a massive attack in the summer, was to pretend that he was going to do an all out attack on Kursk (which was widely expected, as anyone with a map could see the value of such an attack). And then did what he always did, delay the attack and delay, and delay, until the best of the campaigning season is over. Given his track record of delaying his offensives repeatedly, no one would doubt that the planned attack was coming. But to answer the original question. Was Hitler right to cancel? Yes. He shouldn't even have authorized the offensive. While Manstein was making decent progress in the South. Model's northern arm was totally spent (by the time Hitler made his decision). Given the weather that followed (pelting rain) it would have been unlikely that Manstein could have broken through all the way to link up with Model. And even if he was able to do that, there was no real reason to believe there would have been enough German troops to prevent the Russian from reaching the newly cut off in the Kursk pocket. The problem was, the Soviet still had significant reserve left (the Steppe Front), and the Germans didn't.
2,024
> > On the night of 9/10 July, the Western Allies mounted an amphibious > invasion of Sicily. Three days later, Hitler summoned Günther von > Kluge and Erich von Manstein to his Wolfsschanze headquarters in East > Prussia and declared his intention to "temporarily" call off [Operation Zitadelle](https://en.wikipedia.org/wiki/Operation_Citadel). **Von Manstein attempted to dissuade him, arguing that > Zitadelle was on the brink of victory: "on no account should we let go > of the enemy until the mobile reserves which he had committed were > decisively beaten"**. In an unusual reversal of their roles, Hitler gave > von Manstein a few more days to continue the offensive, but on 17 > July, he ordered a withdrawal and canceled the operation. He then > ordered the entire SS Panzer Corps to be transferred to Italy.[87] > > > While Hitler often made notoriously poor judgments for all the wrong reasons, did he make the right decision for Germany (for the wrong reason) in this specific isolated case? Was Zitadelle really on the brink of victory as Von Manstein believed?
2012/05/12
[ "https://history.stackexchange.com/questions/2024", "https://history.stackexchange.com", "https://history.stackexchange.com/users/852/" ]
Kursk was an exercise in futility by July of 1943. Giving the Soviets 4-5 months to prepare the defenses around Kursk made the whole operation a waste of resources and time. What Germany SHOULD HAVE done was to spend 1943 on the defensive as Guderian recommended. "How many people do you think even know where Kursk is? It's a matter of profound indifference to the world whether we hold Kursk or not..." But what about handing the initiatives to the Allies? That can be solved trivially. All Hitler had to do to prevent the Soviet from launching a massive attack in the summer, was to pretend that he was going to do an all out attack on Kursk (which was widely expected, as anyone with a map could see the value of such an attack). And then did what he always did, delay the attack and delay, and delay, until the best of the campaigning season is over. Given his track record of delaying his offensives repeatedly, no one would doubt that the planned attack was coming. But to answer the original question. Was Hitler right to cancel? Yes. He shouldn't even have authorized the offensive. While Manstein was making decent progress in the South. Model's northern arm was totally spent (by the time Hitler made his decision). Given the weather that followed (pelting rain) it would have been unlikely that Manstein could have broken through all the way to link up with Model. And even if he was able to do that, there was no real reason to believe there would have been enough German troops to prevent the Russian from reaching the newly cut off in the Kursk pocket. The problem was, the Soviet still had significant reserve left (the Steppe Front), and the Germans didn't.
I think he was only partially right and this is because the units transferred were SS units. In the east, the SS fought both its racial and ideological enemies (the Bolshevik Jewry; which was mostly propaganda, but people believed it). There it was in its element, both as regards the savagery of fighting and the atrocities inflicted on the civilian population. In light of later massive surrendering of Germans to the western Allies, but stiff resistance against the Russians, no SS unit should probably ever have been transferred from the East, except for rest and refit.
2,024
> > On the night of 9/10 July, the Western Allies mounted an amphibious > invasion of Sicily. Three days later, Hitler summoned Günther von > Kluge and Erich von Manstein to his Wolfsschanze headquarters in East > Prussia and declared his intention to "temporarily" call off [Operation Zitadelle](https://en.wikipedia.org/wiki/Operation_Citadel). **Von Manstein attempted to dissuade him, arguing that > Zitadelle was on the brink of victory: "on no account should we let go > of the enemy until the mobile reserves which he had committed were > decisively beaten"**. In an unusual reversal of their roles, Hitler gave > von Manstein a few more days to continue the offensive, but on 17 > July, he ordered a withdrawal and canceled the operation. He then > ordered the entire SS Panzer Corps to be transferred to Italy.[87] > > > While Hitler often made notoriously poor judgments for all the wrong reasons, did he make the right decision for Germany (for the wrong reason) in this specific isolated case? Was Zitadelle really on the brink of victory as Von Manstein believed?
2012/05/12
[ "https://history.stackexchange.com/questions/2024", "https://history.stackexchange.com", "https://history.stackexchange.com/users/852/" ]
Kursk was an exercise in futility by July of 1943. Giving the Soviets 4-5 months to prepare the defenses around Kursk made the whole operation a waste of resources and time. What Germany SHOULD HAVE done was to spend 1943 on the defensive as Guderian recommended. "How many people do you think even know where Kursk is? It's a matter of profound indifference to the world whether we hold Kursk or not..." But what about handing the initiatives to the Allies? That can be solved trivially. All Hitler had to do to prevent the Soviet from launching a massive attack in the summer, was to pretend that he was going to do an all out attack on Kursk (which was widely expected, as anyone with a map could see the value of such an attack). And then did what he always did, delay the attack and delay, and delay, until the best of the campaigning season is over. Given his track record of delaying his offensives repeatedly, no one would doubt that the planned attack was coming. But to answer the original question. Was Hitler right to cancel? Yes. He shouldn't even have authorized the offensive. While Manstein was making decent progress in the South. Model's northern arm was totally spent (by the time Hitler made his decision). Given the weather that followed (pelting rain) it would have been unlikely that Manstein could have broken through all the way to link up with Model. And even if he was able to do that, there was no real reason to believe there would have been enough German troops to prevent the Russian from reaching the newly cut off in the Kursk pocket. The problem was, the Soviet still had significant reserve left (the Steppe Front), and the Germans didn't.
I believe that the underlying intention of the High command was never to close the kursk salient with 2 pincers. This has been lauded as gospel for ages and ages and stands in the way of Mansteins thinking. I believe that the Soviet High command make a key strategic error when they positioned the bulk of their armour too close to the Northern pincer. The Northern "Pincer" was not the main pincer, in fact it's firepower was more defensive in charachter with all Ferdinands placed there and the defensive Hagen position available to fall back to which they did in good order. (Model had soaked up significant attacks at the Meat grinder of Rshev with the 9th army and the expectation was that he was to do it again) So essentially one sees what actually occurred in the Invasion of France in 1940 with a sickle through the ardennes now being the Southern Pincer. von Manstein having the core of the firepower, the massive SS corps and Gross Deutschlkand etc down South. Unlike the fiction of Prokhoroka being a Soviet victory it wasn't the 5th Guards etc was wasted...the Soviets actually had committed all reserves in the South and the German Armoured formations were both intact and had reserves. There was no substantive threat to the Eastern flank as those Soviet reserves had already been committed and slaughtered. Whilst Von Manstein had 3 additional panzer divisions in reserve. Its quiet clear that a break through could have been made and given that the rest of the Soviet armoured reserve units were out of position trying to break through against Model in the North. They would not have been able to turn South and get to von Manstein in time. The effect would have been a hammer blow comming up from the South against the soviet armoured units and pressed them against Models Hagen line (Anvil). The distance involved was open tank country...German tanks were being repaired at such a rate that in fact there was almost no difference between tank avaialability on the 13th than there was 5 days earlier...If Von Manstein could snatch a victory at Kharkiv outnumbered 8:1 what he would have done at Kursk could certainly have been within his grasp. As more and more detail comes out of the battle we realize that the Soviets were simply lieing lieing at infinitum Stalin had prepared the script before the battle even started. Hitler essentially pulled out as he did at the Invasion of France where Guderian didn't stop at Sedan but kept up the charge to Dunkirk where Adolf again made the wrong call.
44,724,523
I am trying to upload some files into a Neo4j database using python. I am using Python 2.7.6 and haved successfully installed neo4j-driver and py2neo modues: ``` $ sudo pip install neo4j-driver Downloading/unpacking neo4j-driver Downloading neo4j-driver-1.3.1.tar.gz (167kB): 167kB downloaded Running setup.py (path:/tmp/pip_build_root/neo4j-driver/setup.py) egg_info for package neo4j-driver warning: no previously-included files matching '*.class' found anywhere in distribution warning: no previously-included files matching '*.pyc' found anywhere in distribution warning: no previously-included files matching '*.pyo' found anywhere in distribution warning: no previously-included files matching '*.so' found anywhere in distribution warning: no previously-included files matching '*.dll' found anywhere in distribution warning: no previously-included files matching '__pycache__' found anywhere in distribution no previously-included directories found matching 'test' Installing collected packages: neo4j-driver Running setup.py install for neo4j-driver building 'neo4j.bolt._io' extension x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c neo4j/bolt/_io.c -o build/temp.linux-x86_64-2.7/neo4j/bolt/_io.o x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/neo4j/bolt/_io.o -o build/lib.linux-x86_64-2.7/neo4j/bolt/_io.so building 'neo4j.packstream._packer' extension x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c neo4j/packstream/_packer.c -o build/temp.linux-x86_64-2.7/neo4j/packstream/_packer.o x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/neo4j/packstream/_packer.o -o build/lib.linux-x86_64-2.7/neo4j/packstream/_packer.so building 'neo4j.packstream._unpacker' extension x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c neo4j/packstream/_unpacker.c -o build/temp.linux-x86_64-2.7/neo4j/packstream/_unpacker.o x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/neo4j/packstream/_unpacker.o -o build/lib.linux-x86_64-2.7/neo4j/packstream/_unpacker.so warning: no previously-included files matching '*.class' found anywhere in distribution warning: no previously-included files matching '*.pyc' found anywhere in distribution warning: no previously-included files matching '*.pyo' found anywhere in distribution warning: no previously-included files matching '*.so' found anywhere in distribution warning: no previously-included files matching '*.dll' found anywhere in distribution warning: no previously-included files matching '__pycache__' found anywhere in distribution no previously-included directories found matching 'test' Could not find .egg-info directory in install record for neo4j-driver Successfully installed neo4j-driver Cleaning up... $ sudo pip install py2neo Downloading/unpacking py2neo Downloading py2neo-3.1.2.tar.gz (100kB): 100kB downloaded Running setup.py (path:/tmp/pip_build_root/py2neo/setup.py) egg_info for package py2neo warning: no previously-included files found matching 'CONTRIBUTING.md' warning: no previously-included files found matching 'README.md' warning: no previously-included files matching '*' found under directory 'test' warning: no previously-included files matching '*' found under directory 'test_ext' Installing collected packages: py2neo Running setup.py install for py2neo warning: no previously-included files found matching 'CONTRIBUTING.md' warning: no previously-included files found matching 'README.md' warning: no previously-included files matching '*' found under directory 'test' warning: no previously-included files matching '*' found under directory 'test_ext' Installing neokit script to /usr/local/bin Installing geoff script to /usr/local/bin Installing py2neo script to /usr/local/bin Could not find .egg-info directory in install record for py2neo Successfully installed py2neo Cleaning up... ``` but there are complaints of no module called `core` ``` $ python Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from py2neo.core import Graph Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named core >>> ``` Anyone else had this issue?
2017/06/23
[ "https://Stackoverflow.com/questions/44724523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1268941/" ]
The [py2neo docs](http://py2neo.org/2.0/essentials.html) says you should use: ``` from py2neo import Graph ``` instead of: ``` from py2neo.core import Graph ``` That is: remove the `.core` from the above code line. Take a look in [this link](http://py2neo.org/2.0/essentials.html#the-graph).
You installed the official **Python Driver for Neo4j**. (And never install with sudo, use a virtual environment.) `sudo pip install neo4j-driver` and then complain about **py2neo** ... `from py2neo import Graph` **The API Documentation for the official Python Driver 4.0 for Neo4j:** <https://neo4j.com/docs/api/python-driver/4.0/>
65,939,488
I want to deploy a Synapse pipeline which contains a Spark Job definition, activities etc. with an terraform script or an ARM template. But i don't find any documentation for this. I found for data factory pipeline : <https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/data_factory_pipeline> but not equivalent documentation for Synapse. Same issue with ARM documentation (<https://learn.microsoft.com/fr-fr/azure/templates/>). I don't want to use the Workspace of Azure Synapse. Is the documentation available ? Thanks for your support
2021/01/28
[ "https://Stackoverflow.com/questions/65939488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15099549/" ]
Why not simplify: ```js var x = `This is an example url http://www.longurl.com/?a=example@gmail.com&x=y1 and this must me a example url http:// www.longurl.com/?a=example@gmail.com&x=y1 (with an arbitrary number of spaces between the protocol and the beginning of the url) here is a mailto:a@b.c?subject=aaa%20bbb and some more text So https://www.google.com/search?q=bla or ftp://aaa:bbb@server.com could appear` function getMatch(str) { var urlRegex = /((mailto:|ftp:\/\/|https?:\/\/)\S+?)[^\s]+/ig; return str.match(urlRegex); } console.log(getMatch(x)); ```
Supposing an URL always start with `http` and can not have an empty space, a solution would be: `http[^ ]+` `[^ ]+` will match one or more non white-space characters.
56,306,079
so I have this code to calculate the value of the variable chance and print it there are no error codes but when it gets to the print statement no matter what compiler I use to compile it nothing appears in the output There is no error so I don't have anything to go off of ``` import math luck = 54 justice = 0 compassion = 1 bravery = 1 truth = 2 coreType = "Legendary" baseChance = 0.01 element = "Light" import math valid = True if coreType == "Common": coreRarity = 1 elif coreType == "Rare": coreRarity = 1.5 elif coreType == "Legendary": coreRarity = 3 else: print("Invalid core type") valid = False if justice > compassion and justice > truth and justice > bravery: idea = "justice" elif compassion > justice and compassion > truth and compassion > bravery: idea = "compassion" elif truth > compassion and truth > justice and truth > bravery: idea = truth elif bravery > compassion and bravery > truth and bravery > justice: idea = "bravery" else: idea = "all" if idea == "justice" and (element == "Light" or element == "Shadow"): boost = justice elif idea == "truth" and (element == "Ice" or element == "Wind"): boost = truth elif idea == "compassion" and (element == "Earth" or element == "Lightning"): boost = compassion elif idea == "bravery" and (element == "Fire" or element == "Water"): boost = bravery elif idea == "all": boost = bravery #basicly the above determines what the highest idea is and sets it but if the highest is all it means they are all the same so It doesn't matter one one the boost's value is cause its all the same if valid == True: chance = math.max(math.sqrt(luck*0.01*1.3)+0.95,1)*0.01*(0.01*(100+5*idea)*coreRarity*baseChance) if coreType == "common": chance =* 0.25 print(chance) ``` It's supposed to print the value of chance but prints nothing
2019/05/25
[ "https://Stackoverflow.com/questions/56306079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11555030/" ]
You have two issues with your code: * `chance =* 0.25` should be `chance *= 0.25` ([here](https://www.tutorialspoint.com/python/assignment_operators_example.htm) is a list of all assignmet operators) * the module `math` doesn't have a `max` attribute, so I would recommend you trying `max()` instead of `math.max()` That beeing said try replacing your current `if` statement (the one at the end) with this one: ``` if valid == True: chance = max(math.sqrt(luck*0.01*1.3)+0.95,1)*0.01*(0.01*(100+5*idea)*coreRarity*baseChance) if coreType == "common": chance *= 0.25 print(chance) ``` Hope this helps
There's a lot of ways this code can be improved: **Setting coreRarity** - This code below: ``` valid = True if coreType == "Common": coreRarity = 1 elif coreType == "Rare": coreRarity = 1.5 elif coreType == "Legendary": coreRarity = 3 else: print("Invalid core type") valid = False ``` can be made into a dictionary lookup ``` coreRarityDict = { "Common": 1, "Rare": 1.5, "Legendary": 3 } ``` To set `valid` and `coreRarity` uses readable dictionary methods ``` valid = coreType in coreRarityDict if valid: coreRarity = coreRarityDict[coreType] # dictionary lookup else: print("Invalid core type") ``` **Setting idea** - The next part: ``` if justice > compassion and justice > truth and justice > bravery: idea = "justice" elif compassion > justice and compassion > truth and compassion > bravery: idea = "compassion" elif truth > compassion and truth > justice and truth > bravery: idea = truth elif bravery > compassion and bravery > truth and bravery > justice: idea = "bravery" else: idea = "all" ``` The logic here is basically boils down to which is the (strict) maximum of `justice, compassion, truth, bravery`. If there is a ties for the maximum, set idea to "all". Note `idea = truth` looks like it should be `idea = "truth"` Again let's use a dictionary ``` ideasDict = { "justice": justice, "compassion": compassion, "truth": truth, "bravery": bravery, } ``` To set idea we want the key with the strict largest value See - [Getting key with maximum value in dictionary?](https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary) ``` idea = max(ideasDict, key=lambda x: ideasDict[x]) ``` To check for ties we can count the number of times this idea value occurs in our dictionary - see [Python 2.7 Counting number of dictionary items with given value](https://stackoverflow.com/questions/13462365/python-2-7-counting-number-of-dictionary-items-with-given-value) ``` sum(1 for x in ideasDict.values() if x == idea) ``` Combining this, ``` idea = max(ideasDict, key=lambda x: ideasDict[x]) idea_freq = sum(1 for x in ideasDict.values() if x == idea) if idea_freq > 1: idea = "all" ``` **Setting boost** - This code ``` if idea == "justice" and (element == "Light" or element == "Shadow"): boost = justice elif idea == "truth" and (element == "Ice" or element == "Wind"): boost = truth elif idea == "compassion" and (element == "Earth" or element == "Lightning"): boost = compassion elif idea == "bravery" and (element == "Fire" or element == "Water"): boost = bravery elif idea == "all": boost = bravery #basically the above determines what the highest idea is and sets it but if the highest is all it means they are all the same so It doesn't matter one one the boost's value is cause its all the same ``` Notice you are repeating `if idea == "xx": boost = xx` Reusing the dictionary the code would look like ``` if idea == "justice" and (element == "Light" or element == "Shadow"): boost = ideasDict[idea] elif idea == "truth" and (element == "Ice" or element == "Wind"): boost = ideasDict[idea] elif idea == "compassion" and (element == "Earth" or element == "Lightning"): boost = ideasDict[idea] elif idea == "bravery" and (element == "Fire" or element == "Water"): boost = ideasDict[idea] elif idea == "all": boost = bravery #basically the above determines what the highest idea is and sets it but if the highest is all it means they are all the same so It doesn't matter one one the boost's value is cause its all the same ``` That's a lot of repeating `boost = ideasDict[idea]`! Let's simplify further! Note the `elif` can just be made as an `if` as your conditions are non-overlapping: `idea` can't be both `== "justice"` and `== "truth"`. Let's use a dictionary again ``` elementsBoostDict = { "justice": ["Light", "Shadow"], "compassion": ["Ice", "Wind"], "truth": ["Earth", "Lightning"], "bravery": ["Fire", "Water"], } if idea == "all": boost = bravery elif element in elementsBoostDict[idea]: boost = ideasDict[idea] ``` Notice `boost` may not be set e.g `idea == "justice"` and `element == "ice"` and `boost` is not used anywhere else in your code? Is this intended? **Calculating chance** - this is your code ``` if valid == True: chance = math.max(math.sqrt(luck*0.01*1.3)+0.95,1)*0.01*(0.01*(100+5*idea)*coreRarity*baseChance) if coreType == "common": chance =* 0.25 print(chance) ``` Note `idea` is a string (I get error `TypeError: unsupported operand type(s) for +: 'int' and 'str'` after previously correcting to `idea = "truth"`) and should be replaced by it's relative value. The line `if valid == True:` can be simplified to `if valid:` Your chance calculation includes a lot of hard coded numbers and can be simplified `0.01*0.01 = 0.0001`. Let's move this into a function with some defaults. Also as `luck` is a percentage we'll use `luck=0.54` and remove the multiplication by `0.01`. ``` def chance_calc(coreType, coreRarity, idea, luck=0.54, baseChance=0.01): temp = math.max(math.sqrt(luck * 1.3) + 0.95, 1) chance = temp * 0.0001 * (100 + 5 * ideasDict[idea]) * coreRarity * baseChance if coreType == "common": chance *= 0.25 return chance ``` **Final code** ``` import math justice = 0 compassion = 1 bravery = 1 truth = 2 coreType = "Legendary" element = "Light" coreRarityDict = { "Common": 1, "Rare": 1.5, "Legendary": 3 } ideasDict= { "justice": justice, "compassion": compassion, "truth": truth, "bravery": bravery, } elementsBoost = { "justice": ["Light", "Shadow"], "compassion": ["Ice", "Wind"], "truth": ["Earth", "Lightning"], "bravery": ["Fire", "Water"], } # set coreRarity valid = coreType in coreRarityDict if valid: coreRarity = coreRarityDict[coreType] else: print("Invalid core type") # set idea idea = max(ideasDict, key=lambda x: ideasDict[x]) idea_freq = sum(1 for x in ideasDict.values() if x == idea) if idea_freq > 1: idea = "all" # set boost if idea == "all": boost = bravery elif element in elementsBoost[idea]: boost = ideasDict[idea] def chance_calc(coreType, coreRarity, idea, luck=0.54, baseChance=0.01): temp = math.max(math.sqrt(luck * 1.3) + 0.95, 1) chance = temp * 0.0001 * (100 + 5 * ideasDict[idea]) * coreRarity * baseChance if coreType == "common": chance *= 0.25 return chance if valid: chance = chance_calc(coreType, coreRarity, idea) print(chance) # result 0.0005899919528666251 ``` **Final thoughts and post mortem** There's a high chance I changed what you intended or made some error. Using a structured data type like a dictionary has the benefit of simplifying code and provides methods we can use. An alternative could be using classes which could combine `ideasDict` and `elementsBoost`. If idea is "all" then `ideasDict[idea]` will return `None` and `chance_calc` will return an error. `boost` is not used If `ideasDict[idea]` is big enough the chance may be bigger than 1. The chance calculation looks like it could be improved. A good idea might be to write down a bunch of combinations of `justice, compassion, bravery, truth, coreType, element` and what chance you would like for each and then try to write a function that gets close to this.
38,407,396
I want to do form validation for all three tags and after validation, enable the submit button until validation is done not to enable submit button. ``` <html> <head> <link rel="stylesheet" href="css/bootstrap.css" /> <link rel="stylesheet" href="css/datepicker.css" /> <link rel="stylesheet" href="css/mystyle.css" /> <script src="js/jquery-2.2.2.js"></script> <script src="js/bootstrap-datepicker.js"></script> <script src="js/moment.js"></script> </head> <body> <form id="report-form"> <div id="report-pane" class="row"> <div class="col-xs-1"> <label>Report:</label> </div> <div class="col-xs-2"> <select class="form-control" id="report"> <option value="" selected>Select Report</option> <option id="rep1" value="10">Report 1</option> <option id="rep2" value="20">Report 2</option> <option id="rep3" value="30">Report 3</option> </select> </div> </div> <!--Date Section--> <div id="date-pane" class="row"> <!--Script for datepicker--> <script type="text/javascript"> $(function() { var now = new Date(); var yearsold = new Date(); yearsold.setFullYear((now.getFullYear() - 2)); $('.datepicker').datepicker({ format: 'mm/dd/yyyy', startDate: yearsold, endDate: now }); var defaultDate = moment().format('DD/MM/YYYY'); $("#datePicker1").val(defaultDate); $("#datePicker2").val(defaultDate); }); </script> <div class="col-xs-1"> <label>Start Date:</label> </div> <div class='col-sm-3'> <input class="datepicker form-control" type="text" id="datePicker1" /> </div> <div class="col-xs-1"> <label>End Date:</label> </div> <div class='col-sm-3'> <input class="datepicker form-control" type="text" id="datePicker2" /> </div> </div> <div id="button-pane" class="row"> <div class="col-lg-12"> <!-- <button class="btn btn-primary">Generate Report</button>--> <input type="submit" id="requestBtn" class="btn btn-primary" value="Generate Report"></input> </div> </div> <script type="text/javascript"> $(document).ready(function() { // Validation Function Needed }); </script> </form> <script src="js/bootstrap.js"></script> </body> </html> ``` Enable the submit button only if all the form validation is done Example [![Sample Visual](https://i.stack.imgur.com/7cd2O.png)](https://i.stack.imgur.com/7cd2O.png)
2016/07/16
[ "https://Stackoverflow.com/questions/38407396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5845221/" ]
``` $(document).ready(function () { $('#ccSelectForm').validate({ rules: { inputEmail: { required: true, email: true }, inputEmailConfirm: { equalTo: '#inputEmail' } } }); $('#ccSelectForm input').on('keyup blur', function () { if ($('#ccSelectForm').valid()) { $('button.btn').prop('disabled', false); } else { $('button.btn').prop('disabled', 'disabled'); } }); ``` }); [Check this link](http://jsfiddle.net/p628Y/1/)
i think you want something like this ``` $(document).ready(function() { // before validation $("#submit").attr("disabled","disabled"); // after validation $("#submit").removeAttr("disabled"); }); ```
38,407,396
I want to do form validation for all three tags and after validation, enable the submit button until validation is done not to enable submit button. ``` <html> <head> <link rel="stylesheet" href="css/bootstrap.css" /> <link rel="stylesheet" href="css/datepicker.css" /> <link rel="stylesheet" href="css/mystyle.css" /> <script src="js/jquery-2.2.2.js"></script> <script src="js/bootstrap-datepicker.js"></script> <script src="js/moment.js"></script> </head> <body> <form id="report-form"> <div id="report-pane" class="row"> <div class="col-xs-1"> <label>Report:</label> </div> <div class="col-xs-2"> <select class="form-control" id="report"> <option value="" selected>Select Report</option> <option id="rep1" value="10">Report 1</option> <option id="rep2" value="20">Report 2</option> <option id="rep3" value="30">Report 3</option> </select> </div> </div> <!--Date Section--> <div id="date-pane" class="row"> <!--Script for datepicker--> <script type="text/javascript"> $(function() { var now = new Date(); var yearsold = new Date(); yearsold.setFullYear((now.getFullYear() - 2)); $('.datepicker').datepicker({ format: 'mm/dd/yyyy', startDate: yearsold, endDate: now }); var defaultDate = moment().format('DD/MM/YYYY'); $("#datePicker1").val(defaultDate); $("#datePicker2").val(defaultDate); }); </script> <div class="col-xs-1"> <label>Start Date:</label> </div> <div class='col-sm-3'> <input class="datepicker form-control" type="text" id="datePicker1" /> </div> <div class="col-xs-1"> <label>End Date:</label> </div> <div class='col-sm-3'> <input class="datepicker form-control" type="text" id="datePicker2" /> </div> </div> <div id="button-pane" class="row"> <div class="col-lg-12"> <!-- <button class="btn btn-primary">Generate Report</button>--> <input type="submit" id="requestBtn" class="btn btn-primary" value="Generate Report"></input> </div> </div> <script type="text/javascript"> $(document).ready(function() { // Validation Function Needed }); </script> </form> <script src="js/bootstrap.js"></script> </body> </html> ``` Enable the submit button only if all the form validation is done Example [![Sample Visual](https://i.stack.imgur.com/7cd2O.png)](https://i.stack.imgur.com/7cd2O.png)
2016/07/16
[ "https://Stackoverflow.com/questions/38407396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5845221/" ]
``` $(document).ready(function () { $('#ccSelectForm').validate({ rules: { inputEmail: { required: true, email: true }, inputEmailConfirm: { equalTo: '#inputEmail' } } }); $('#ccSelectForm input').on('keyup blur', function () { if ($('#ccSelectForm').valid()) { $('button.btn').prop('disabled', false); } else { $('button.btn').prop('disabled', 'disabled'); } }); ``` }); [Check this link](http://jsfiddle.net/p628Y/1/)
If you insist on Jq custom logic is needed, ``` var validationCallBk = function(){ var report = $('#report').val(); var startDate = $('#datePicker1').val(); var endDate = $('#datePicker2').val(); if(report != '' && startDate == somevaliddate && endDate == somevaliddate) //enable btn else //disable btn }; $('#report').on('change',validationCallBk); //use the datepicker on select event and call validationCallBk ```
747,561
I'm having trouble figuring out the limits. What messes me up is that the limit approaches infinity. Usually it approaches a specific number. Is that a trick to solve problems like these? So for example, use the root test to find convergence/divergence. (n!)^n/(n^n)^7. n=1 and it's to infinity
2014/04/10
[ "https://math.stackexchange.com/questions/747561", "https://math.stackexchange.com", "https://math.stackexchange.com/users/136944/" ]
${\root n\of{a\_n}}=n!/n^7\to\infty$, so $\sum a\_n$ diverges.
$$\sum\_{n=1}^{\infty}=\dfrac{(n!)^n}{(n^n)^7}$$ so,we let $a\_n=\dfrac{(n!)^n}{(n^n)^7}.$ To use the root test,we take $$L=\lim\_{n\rightarrow \infty}\sqrt[n]{\left|a\_n\right|}$$ $$L=\lim\_{n\rightarrow \infty}\sqrt[n]{\dfrac{(n!)^n}{(n^n)^7}}$$ $$L=\lim\_{n\rightarrow \infty}\dfrac{(n!)}{(n)^7}$$ And as n! increases much faser than $n^7$ as $n\rightarrow\infty$ $$L=\infty$$ As $L\ne0$, The series diverges.
788,671
I am assuming the following ways to copy a file with in a NFS share: **Process 1:** * The client requests for the data to be copied from NFS share (if cache is not there) and the chunks of data are asynchronously copied to memory of the NFS client which then asynchronously send it to the NFS filer again to copy to new location. * The NFS filer receives the chunks of data asynchronously in the memory and writes it to the new location. * In this process, though there is network involved while reading and also writing, due to asynchronous read & write, the latency for one overall read-write operation will be same as latency for read-write operation of overall data. Hence, reading from local hard disk and writing to NFS is almost same as reading from NFS and write to NFS. In the first step, if cache is already there, the reading can be very quick. **Process 2:** * The client send request to initiate the data copy operation to NFS server, along with the location from where it has to read and where it has to write (seems it is not). * The server does the rest, read-write operations using it's own memory. Hence, no network involved. And hence, can have better performance (unless there is no latency at the network end) But it is likely not the way. Please correct me at every point, if I am wrong. Also, does the memory involves at every operation, I mean when it sends data across network, the data is first sent to memory (data buffer) from disk and then from memory (data buffer) to data buffer (on the other side of the network), but not from data buffer to disk on the other side of the network right?
2016/07/08
[ "https://serverfault.com/questions/788671", "https://serverfault.com", "https://serverfault.com/users/292068/" ]
NFSv4.2 does have a offload-copy operation which can do server-to-server copy without proxying data trough the client. Modern linux kernels (> 3.13?) supports that. I don't know about other servers. **UPDATE** By linux kernel 4.7 server side copy is not supported by linux servers <https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/fs/nfsd/nfs4xdr.c?id=refs/tags/v4.7-rc6#n1797> **UPDATE 2** With kernel version 5.6 the server side copy is added to the NFSD implementation <https://lkml.org/lkml/2020/2/7/687>
The `"copy a file"` operation is not a basic file-system operation such as `read`, `write`, `open`, `close`, and similar operations. See [this page for a good explanation](http://www.tldp.org/LDP/khg/HyperNews/get/fs/vfstour.html) of the operations a filesystem has to support. And that's all file systems - whether it's `ext4`, `btrfs`, or `nfsv4`. Note that there's no way to know why a process opens file A, opens file B, reads from file A, then writes to file B. So, in general there's no way to "short-circuit" and optimize the copying of a file so that the data doesn't have to cross the network twice in the case of both file A and file B being on NFS file systems, even if they're shared from the same NFS server. Many operating systems do provide system calls [such as `sendfile()`](http://man7.org/linux/man-pages/man2/sendfile.2.html), which do efficiently copy data by removing the need to copy the data to and from user space, and in theory that could be done at the file system level for copying files, but even then there would have to be restrictions similar to that on the `rename()` operation - such a hypothetical `copyfile()` operation would likely have to be restricted to short-circuiting only those copies within a single file system. To do otherwise would make a complex mess - what to do if file A and file B are on the same NFS server, a client wants to copy from one to the other, but file A is on an ext4 file system and file B is on another XFS file system?
12,432,663
I have looked in the standard library and on StackOverflow, and have not found a similar question. So, is there a way to do the following without rolling my own function? Bonus points if someone writes a beautiful function if there is no built in way. ``` def stringPercentToFloat(stringPercent) # ??? return floatPercent p1 = "99%" p2 = "99.5%" print stringPercentToFloat(p1) print stringPercentToFloat(p2) >>>> 0.99 >>>> 0.995 ```
2012/09/14
[ "https://Stackoverflow.com/questions/12432663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1476403/" ]
I wrote the following method that should always return the output to the exact same accuracy as the input, with no floating point errors such as in the other answers. ``` def percent_to_float(s): s = str(float(s.rstrip("%"))) i = s.find(".") if i == -1: return int(s) / 100 if s.startswith("-"): return -percent_to_float(s.lstrip("-")) s = s.replace(".", "") i -= 2 if i < 0: return float("." + "0" * abs(i) + s) else: return float(s[:i] + "." + s[i:]) ``` Explanation ----------- 1. Strip the "%" from the end. 2. If percent has no ".", simply return it divided by 100. 3. If percent is negative, strip the "-" and re-call function, then convert the result back to a negative and return it. 4. Remove the decimal place. 5. Decrement `i` (the index the decimal place was at) by 2, because we want to shift the decimal place 2 spaces to the left. 6. If `i` is negative, then we need to pad with zeros. * **Example:** Suppose the input is "1.33%". To be able to shift the decimal place 2 spaces to the left, we would need to pad with a zero. 7. Convert to a float. --- Test case ([Try it online](https://repl.it/@HatScripts/percenttofloat)): ``` from unittest.case import TestCase class ParsePercentCase(TestCase): tests = { "150%" : 1.5, "100%" : 1, "99%" : 0.99, "99.999%" : 0.99999, "99.5%" : 0.995, "95%" : 0.95, "90%" : 0.9, "50%" : 0.5, "66.666%" : 0.66666, "42%" : 0.42, "20.5%" : 0.205, "20%" : 0.2, "10%" : 0.1, "3.141592653589793%": 0.03141592653589793, "1%" : 0.01, "0.1%" : 0.001, "0.01%" : 0.0001, "0%" : 0, } tests = sorted(tests.items(), key=lambda x: -x[1]) def test_parse_percent(self): for percent_str, expected in self.tests: parsed = percent_to_float(percent_str) self.assertEqual(expected, parsed, percent_str) def test_parse_percent_negative(self): negative_tests = [("-" + s, -f) for s, f in self.tests] for percent_str, expected in negative_tests: parsed = percent_to_float(percent_str) self.assertEqual(expected, parsed, percent_str) ```
Another way: `float(stringPercent[:-1]) / 100`
12,432,663
I have looked in the standard library and on StackOverflow, and have not found a similar question. So, is there a way to do the following without rolling my own function? Bonus points if someone writes a beautiful function if there is no built in way. ``` def stringPercentToFloat(stringPercent) # ??? return floatPercent p1 = "99%" p2 = "99.5%" print stringPercentToFloat(p1) print stringPercentToFloat(p2) >>>> 0.99 >>>> 0.995 ```
2012/09/14
[ "https://Stackoverflow.com/questions/12432663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1476403/" ]
Use `strip('%')` , as: ``` In [9]: "99.5%".strip('%') Out[9]: '99.5' #convert this to float using float() and divide by 100 In [10]: def p2f(x): ....: return float(x.strip('%'))/100 ....: In [12]: p2f("99%") Out[12]: 0.98999999999999999 In [13]: p2f("99.5%") Out[13]: 0.995 ```
I wrote the following method that should always return the output to the exact same accuracy as the input, with no floating point errors such as in the other answers. ``` def percent_to_float(s): s = str(float(s.rstrip("%"))) i = s.find(".") if i == -1: return int(s) / 100 if s.startswith("-"): return -percent_to_float(s.lstrip("-")) s = s.replace(".", "") i -= 2 if i < 0: return float("." + "0" * abs(i) + s) else: return float(s[:i] + "." + s[i:]) ``` Explanation ----------- 1. Strip the "%" from the end. 2. If percent has no ".", simply return it divided by 100. 3. If percent is negative, strip the "-" and re-call function, then convert the result back to a negative and return it. 4. Remove the decimal place. 5. Decrement `i` (the index the decimal place was at) by 2, because we want to shift the decimal place 2 spaces to the left. 6. If `i` is negative, then we need to pad with zeros. * **Example:** Suppose the input is "1.33%". To be able to shift the decimal place 2 spaces to the left, we would need to pad with a zero. 7. Convert to a float. --- Test case ([Try it online](https://repl.it/@HatScripts/percenttofloat)): ``` from unittest.case import TestCase class ParsePercentCase(TestCase): tests = { "150%" : 1.5, "100%" : 1, "99%" : 0.99, "99.999%" : 0.99999, "99.5%" : 0.995, "95%" : 0.95, "90%" : 0.9, "50%" : 0.5, "66.666%" : 0.66666, "42%" : 0.42, "20.5%" : 0.205, "20%" : 0.2, "10%" : 0.1, "3.141592653589793%": 0.03141592653589793, "1%" : 0.01, "0.1%" : 0.001, "0.01%" : 0.0001, "0%" : 0, } tests = sorted(tests.items(), key=lambda x: -x[1]) def test_parse_percent(self): for percent_str, expected in self.tests: parsed = percent_to_float(percent_str) self.assertEqual(expected, parsed, percent_str) def test_parse_percent_negative(self): negative_tests = [("-" + s, -f) for s, f in self.tests] for percent_str, expected in negative_tests: parsed = percent_to_float(percent_str) self.assertEqual(expected, parsed, percent_str) ```
12,432,663
I have looked in the standard library and on StackOverflow, and have not found a similar question. So, is there a way to do the following without rolling my own function? Bonus points if someone writes a beautiful function if there is no built in way. ``` def stringPercentToFloat(stringPercent) # ??? return floatPercent p1 = "99%" p2 = "99.5%" print stringPercentToFloat(p1) print stringPercentToFloat(p2) >>>> 0.99 >>>> 0.995 ```
2012/09/14
[ "https://Stackoverflow.com/questions/12432663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1476403/" ]
Use `strip('%')` , as: ``` In [9]: "99.5%".strip('%') Out[9]: '99.5' #convert this to float using float() and divide by 100 In [10]: def p2f(x): ....: return float(x.strip('%'))/100 ....: In [12]: p2f("99%") Out[12]: 0.98999999999999999 In [13]: p2f("99.5%") Out[13]: 0.995 ```
``` float(stringPercent.strip('%')) / 100.0 ```
12,432,663
I have looked in the standard library and on StackOverflow, and have not found a similar question. So, is there a way to do the following without rolling my own function? Bonus points if someone writes a beautiful function if there is no built in way. ``` def stringPercentToFloat(stringPercent) # ??? return floatPercent p1 = "99%" p2 = "99.5%" print stringPercentToFloat(p1) print stringPercentToFloat(p2) >>>> 0.99 >>>> 0.995 ```
2012/09/14
[ "https://Stackoverflow.com/questions/12432663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1476403/" ]
Based on the answer from @WKPlus this solution takes into account the locales where the decimal point is either a point `.` or a comma `,` ``` float("-3,5%".replace(',','.')[:-1]) / 100 ```
Another way: `float(stringPercent[:-1]) / 100`
12,432,663
I have looked in the standard library and on StackOverflow, and have not found a similar question. So, is there a way to do the following without rolling my own function? Bonus points if someone writes a beautiful function if there is no built in way. ``` def stringPercentToFloat(stringPercent) # ??? return floatPercent p1 = "99%" p2 = "99.5%" print stringPercentToFloat(p1) print stringPercentToFloat(p2) >>>> 0.99 >>>> 0.995 ```
2012/09/14
[ "https://Stackoverflow.com/questions/12432663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1476403/" ]
Use `strip('%')` , as: ``` In [9]: "99.5%".strip('%') Out[9]: '99.5' #convert this to float using float() and divide by 100 In [10]: def p2f(x): ....: return float(x.strip('%'))/100 ....: In [12]: p2f("99%") Out[12]: 0.98999999999999999 In [13]: p2f("99.5%") Out[13]: 0.995 ```
Simply replace the `%` by `e-2` before parsing to `float` : ``` float("99.5%".replace('%', 'e-2')) ``` It's safer since the result will still be correct if there's no `%` used.
12,432,663
I have looked in the standard library and on StackOverflow, and have not found a similar question. So, is there a way to do the following without rolling my own function? Bonus points if someone writes a beautiful function if there is no built in way. ``` def stringPercentToFloat(stringPercent) # ??? return floatPercent p1 = "99%" p2 = "99.5%" print stringPercentToFloat(p1) print stringPercentToFloat(p2) >>>> 0.99 >>>> 0.995 ```
2012/09/14
[ "https://Stackoverflow.com/questions/12432663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1476403/" ]
Simply replace the `%` by `e-2` before parsing to `float` : ``` float("99.5%".replace('%', 'e-2')) ``` It's safer since the result will still be correct if there's no `%` used.
Based on the answer from @WKPlus this solution takes into account the locales where the decimal point is either a point `.` or a comma `,` ``` float("-3,5%".replace(',','.')[:-1]) / 100 ```
12,432,663
I have looked in the standard library and on StackOverflow, and have not found a similar question. So, is there a way to do the following without rolling my own function? Bonus points if someone writes a beautiful function if there is no built in way. ``` def stringPercentToFloat(stringPercent) # ??? return floatPercent p1 = "99%" p2 = "99.5%" print stringPercentToFloat(p1) print stringPercentToFloat(p2) >>>> 0.99 >>>> 0.995 ```
2012/09/14
[ "https://Stackoverflow.com/questions/12432663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1476403/" ]
``` float(stringPercent.strip('%')) / 100.0 ```
Based on the answer from @WKPlus this solution takes into account the locales where the decimal point is either a point `.` or a comma `,` ``` float("-3,5%".replace(',','.')[:-1]) / 100 ```
12,432,663
I have looked in the standard library and on StackOverflow, and have not found a similar question. So, is there a way to do the following without rolling my own function? Bonus points if someone writes a beautiful function if there is no built in way. ``` def stringPercentToFloat(stringPercent) # ??? return floatPercent p1 = "99%" p2 = "99.5%" print stringPercentToFloat(p1) print stringPercentToFloat(p2) >>>> 0.99 >>>> 0.995 ```
2012/09/14
[ "https://Stackoverflow.com/questions/12432663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1476403/" ]
Use `strip('%')` , as: ``` In [9]: "99.5%".strip('%') Out[9]: '99.5' #convert this to float using float() and divide by 100 In [10]: def p2f(x): ....: return float(x.strip('%'))/100 ....: In [12]: p2f("99%") Out[12]: 0.98999999999999999 In [13]: p2f("99.5%") Out[13]: 0.995 ```
Another way: `float(stringPercent[:-1]) / 100`
12,432,663
I have looked in the standard library and on StackOverflow, and have not found a similar question. So, is there a way to do the following without rolling my own function? Bonus points if someone writes a beautiful function if there is no built in way. ``` def stringPercentToFloat(stringPercent) # ??? return floatPercent p1 = "99%" p2 = "99.5%" print stringPercentToFloat(p1) print stringPercentToFloat(p2) >>>> 0.99 >>>> 0.995 ```
2012/09/14
[ "https://Stackoverflow.com/questions/12432663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1476403/" ]
``` float(stringPercent.strip('%')) / 100.0 ```
I wrote the following method that should always return the output to the exact same accuracy as the input, with no floating point errors such as in the other answers. ``` def percent_to_float(s): s = str(float(s.rstrip("%"))) i = s.find(".") if i == -1: return int(s) / 100 if s.startswith("-"): return -percent_to_float(s.lstrip("-")) s = s.replace(".", "") i -= 2 if i < 0: return float("." + "0" * abs(i) + s) else: return float(s[:i] + "." + s[i:]) ``` Explanation ----------- 1. Strip the "%" from the end. 2. If percent has no ".", simply return it divided by 100. 3. If percent is negative, strip the "-" and re-call function, then convert the result back to a negative and return it. 4. Remove the decimal place. 5. Decrement `i` (the index the decimal place was at) by 2, because we want to shift the decimal place 2 spaces to the left. 6. If `i` is negative, then we need to pad with zeros. * **Example:** Suppose the input is "1.33%". To be able to shift the decimal place 2 spaces to the left, we would need to pad with a zero. 7. Convert to a float. --- Test case ([Try it online](https://repl.it/@HatScripts/percenttofloat)): ``` from unittest.case import TestCase class ParsePercentCase(TestCase): tests = { "150%" : 1.5, "100%" : 1, "99%" : 0.99, "99.999%" : 0.99999, "99.5%" : 0.995, "95%" : 0.95, "90%" : 0.9, "50%" : 0.5, "66.666%" : 0.66666, "42%" : 0.42, "20.5%" : 0.205, "20%" : 0.2, "10%" : 0.1, "3.141592653589793%": 0.03141592653589793, "1%" : 0.01, "0.1%" : 0.001, "0.01%" : 0.0001, "0%" : 0, } tests = sorted(tests.items(), key=lambda x: -x[1]) def test_parse_percent(self): for percent_str, expected in self.tests: parsed = percent_to_float(percent_str) self.assertEqual(expected, parsed, percent_str) def test_parse_percent_negative(self): negative_tests = [("-" + s, -f) for s, f in self.tests] for percent_str, expected in negative_tests: parsed = percent_to_float(percent_str) self.assertEqual(expected, parsed, percent_str) ```
12,432,663
I have looked in the standard library and on StackOverflow, and have not found a similar question. So, is there a way to do the following without rolling my own function? Bonus points if someone writes a beautiful function if there is no built in way. ``` def stringPercentToFloat(stringPercent) # ??? return floatPercent p1 = "99%" p2 = "99.5%" print stringPercentToFloat(p1) print stringPercentToFloat(p2) >>>> 0.99 >>>> 0.995 ```
2012/09/14
[ "https://Stackoverflow.com/questions/12432663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1476403/" ]
Simply replace the `%` by `e-2` before parsing to `float` : ``` float("99.5%".replace('%', 'e-2')) ``` It's safer since the result will still be correct if there's no `%` used.
I wrote the following method that should always return the output to the exact same accuracy as the input, with no floating point errors such as in the other answers. ``` def percent_to_float(s): s = str(float(s.rstrip("%"))) i = s.find(".") if i == -1: return int(s) / 100 if s.startswith("-"): return -percent_to_float(s.lstrip("-")) s = s.replace(".", "") i -= 2 if i < 0: return float("." + "0" * abs(i) + s) else: return float(s[:i] + "." + s[i:]) ``` Explanation ----------- 1. Strip the "%" from the end. 2. If percent has no ".", simply return it divided by 100. 3. If percent is negative, strip the "-" and re-call function, then convert the result back to a negative and return it. 4. Remove the decimal place. 5. Decrement `i` (the index the decimal place was at) by 2, because we want to shift the decimal place 2 spaces to the left. 6. If `i` is negative, then we need to pad with zeros. * **Example:** Suppose the input is "1.33%". To be able to shift the decimal place 2 spaces to the left, we would need to pad with a zero. 7. Convert to a float. --- Test case ([Try it online](https://repl.it/@HatScripts/percenttofloat)): ``` from unittest.case import TestCase class ParsePercentCase(TestCase): tests = { "150%" : 1.5, "100%" : 1, "99%" : 0.99, "99.999%" : 0.99999, "99.5%" : 0.995, "95%" : 0.95, "90%" : 0.9, "50%" : 0.5, "66.666%" : 0.66666, "42%" : 0.42, "20.5%" : 0.205, "20%" : 0.2, "10%" : 0.1, "3.141592653589793%": 0.03141592653589793, "1%" : 0.01, "0.1%" : 0.001, "0.01%" : 0.0001, "0%" : 0, } tests = sorted(tests.items(), key=lambda x: -x[1]) def test_parse_percent(self): for percent_str, expected in self.tests: parsed = percent_to_float(percent_str) self.assertEqual(expected, parsed, percent_str) def test_parse_percent_negative(self): negative_tests = [("-" + s, -f) for s, f in self.tests] for percent_str, expected in negative_tests: parsed = percent_to_float(percent_str) self.assertEqual(expected, parsed, percent_str) ```
40,721,107
I am working on some task which requires from me to solve the following algorithmic problem: --- - You Have collection of items (their weights): [w1, w2, ..., wn] - And You have a bag which weight is: W - It is Needed to fill the bag maximally (fill as much as possible) with the subset of given items. --- So this **is not** "Knapsack 0/1" problem, as we deal only with weights (we have only one parameter for item). Therefore I assume that it might have a solution (Knapsack is NP-complete) or some kind of algorithm which gives approximately correct result. Please don't suggest me "greedy algorithms", because I believe that there should be an algorithm which gives better results. I think that it should be an algorithm which uses "dynamic programming". Thank you in advance :)
2016/11/21
[ "https://Stackoverflow.com/questions/40721107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1085722/" ]
In this particular instance you get maximum benefit by minimizing the free space in the bag and therefore by considering *weight as a value*. This problem is commonly referred to as [subset sum problem](http://marcodiiga.github.io/knapsack-problem) and is a particular case of knapsack problems family. The DP relation looks like the following [![enter image description here](https://i.stack.imgur.com/AiqMc.png)](https://i.stack.imgur.com/AiqMc.png) where at each step you try to find the maximum value (which does not exceed the bag's capacity) among the previous elements set plus the new element A C++ implementation of the subset sum problem to answer the question "can I fill the bag entirely given these elements?" and driver follows ``` bool ssp(const vector<int>& v, const int& N) { vector<vector<int>> m( v.size() + 1 /* 1-based */, vector<int>(N + 1 /* 1-based */, 0) ); // The line above also took care of the initialization for base // cases f(i,0) = 0 and f(0,b) = 0 for (int i = 1; i <= v.size(); ++i) { // For each subset of elements for (int b = 1; b <= N; ++b) { // For each subcapacity int opt1 = m[i - 1][b]; int opt2 = -1; if (b - v[i - 1] >= 0) { // No caching to keep this readable opt2 = m[i - 1][b - v[i - 1]] + v[i - 1]; if (opt2 > b) opt2 = -1; // Not allowed } m[i][b] = max(opt1, opt2); } } return (m[v.size()][N] == N); } int main() { const vector<int> v = { 1, 3, 7, 4 }; const int N = 11; cout << "Subset sum problem can be solved with the given input: " << boolalpha << ssp(v, N); // true return 0; } ``` The complexity is `O(N⋅I)` where `I` is the number of elements in the starting set. This is a pseudopolynomial complexity. Source: [Knapsack problem](http://marcodiiga.github.io/knapsack-problem)
The described problem in fact is not the [0-1-Knapsack problem](https://en.wikipedia.org/wiki/Knapsack_problem), but a special case thereof, also called the Maximum Subset Sum problem, which is desribed [here](https://en.wikipedia.org/wiki/Subset_sum_problem). It is `NP`-complete, which means that it is not easier than 0-1-Knapsack complexity-wise. That being said, it can be solved by any optimization algorithm intended for the 0-1-Knapsack problem by setting the item profits equal to their weights. In total, it can be solved to optimality using the following dynamic programming algorithm; `s[i]` denotes the size if the `i`-th item and `m` is an integer-valued state space where `m[i,s]` denotes the maximum value attainable by using items from the item rage `{0,...i}`. ``` for j from 0 to W do: m[0, j] := 0 for i from 1 to n do: for j from 0 to W do: if s[i] > j then: m[i, j] := m[i-1, j] else: m[i, j] := max(m[i-1, j], m[i-1, j-s[i]] + s[i]) ``` As they are mentioned in the original question, the following greedy algorithm yields a 2-approximation, which is a modification of a similar algorithm for the Knapsack problem. ``` 1. select any subset of the items such that there is no other item which can be feasibly chosen 2. select the largest item 3. out of 1. and 2., choose the subset which yields the larger total size ```
40,721,107
I am working on some task which requires from me to solve the following algorithmic problem: --- - You Have collection of items (their weights): [w1, w2, ..., wn] - And You have a bag which weight is: W - It is Needed to fill the bag maximally (fill as much as possible) with the subset of given items. --- So this **is not** "Knapsack 0/1" problem, as we deal only with weights (we have only one parameter for item). Therefore I assume that it might have a solution (Knapsack is NP-complete) or some kind of algorithm which gives approximately correct result. Please don't suggest me "greedy algorithms", because I believe that there should be an algorithm which gives better results. I think that it should be an algorithm which uses "dynamic programming". Thank you in advance :)
2016/11/21
[ "https://Stackoverflow.com/questions/40721107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1085722/" ]
The described problem in fact is not the [0-1-Knapsack problem](https://en.wikipedia.org/wiki/Knapsack_problem), but a special case thereof, also called the Maximum Subset Sum problem, which is desribed [here](https://en.wikipedia.org/wiki/Subset_sum_problem). It is `NP`-complete, which means that it is not easier than 0-1-Knapsack complexity-wise. That being said, it can be solved by any optimization algorithm intended for the 0-1-Knapsack problem by setting the item profits equal to their weights. In total, it can be solved to optimality using the following dynamic programming algorithm; `s[i]` denotes the size if the `i`-th item and `m` is an integer-valued state space where `m[i,s]` denotes the maximum value attainable by using items from the item rage `{0,...i}`. ``` for j from 0 to W do: m[0, j] := 0 for i from 1 to n do: for j from 0 to W do: if s[i] > j then: m[i, j] := m[i-1, j] else: m[i, j] := max(m[i-1, j], m[i-1, j-s[i]] + s[i]) ``` As they are mentioned in the original question, the following greedy algorithm yields a 2-approximation, which is a modification of a similar algorithm for the Knapsack problem. ``` 1. select any subset of the items such that there is no other item which can be feasibly chosen 2. select the largest item 3. out of 1. and 2., choose the subset which yields the larger total size ```
It look like [Spoj problem](https://www.spoj.com/ABC2019/problems/ACMNEW1/). And my solusion to solve: ``` #include <bits/stdc++.h> using namespace std; int TimTongLonNhatCoGioiHan(int*arr, int songuoichoi, int gioihan){ int hmm = (int)(songuoichoi*songuoichoi/2); int map[hmm]; int dem = 0, i, j, ox = songuoichoi - 1, oy = 0, result = 0, sum; for(i = ox; i > oy; --i){ for(j = oy; j < ox; ++j){ map[dem] = arr[i] + arr[j]; // tinh tong lon nhat cua 3 so for(int k = 0; k < songuoichoi; ++k){ if(k == j || k == i) continue; sum = map[dem] + arr[k]; if(sum > result && sum <= gioihan) result = sum; } dem++; } -- ox; } return result; } int main() { int sophantu = 0, songuoichoi = 0, gioihan = 0; cin>>sophantu; while(sophantu-->0){ cin>>songuoichoi; int i = 0; int arrCanNang[songuoichoi]; for(; i<songuoichoi; ++i){ cin>>arrCanNang[i]; } cin>>gioihan; cout<<TimTongLonNhatCoGioiHan(arrCanNang, songuoichoi, gioihan)<<"\n"; } return 0; } ``` For simple, you can create a matrix [w1, w2, ..., wn] x [w1, w2, ..., wn], put sum(Wi, Wj), foreach k and find MAX sum(Wi, Wj) + Wk.
40,721,107
I am working on some task which requires from me to solve the following algorithmic problem: --- - You Have collection of items (their weights): [w1, w2, ..., wn] - And You have a bag which weight is: W - It is Needed to fill the bag maximally (fill as much as possible) with the subset of given items. --- So this **is not** "Knapsack 0/1" problem, as we deal only with weights (we have only one parameter for item). Therefore I assume that it might have a solution (Knapsack is NP-complete) or some kind of algorithm which gives approximately correct result. Please don't suggest me "greedy algorithms", because I believe that there should be an algorithm which gives better results. I think that it should be an algorithm which uses "dynamic programming". Thank you in advance :)
2016/11/21
[ "https://Stackoverflow.com/questions/40721107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1085722/" ]
In this particular instance you get maximum benefit by minimizing the free space in the bag and therefore by considering *weight as a value*. This problem is commonly referred to as [subset sum problem](http://marcodiiga.github.io/knapsack-problem) and is a particular case of knapsack problems family. The DP relation looks like the following [![enter image description here](https://i.stack.imgur.com/AiqMc.png)](https://i.stack.imgur.com/AiqMc.png) where at each step you try to find the maximum value (which does not exceed the bag's capacity) among the previous elements set plus the new element A C++ implementation of the subset sum problem to answer the question "can I fill the bag entirely given these elements?" and driver follows ``` bool ssp(const vector<int>& v, const int& N) { vector<vector<int>> m( v.size() + 1 /* 1-based */, vector<int>(N + 1 /* 1-based */, 0) ); // The line above also took care of the initialization for base // cases f(i,0) = 0 and f(0,b) = 0 for (int i = 1; i <= v.size(); ++i) { // For each subset of elements for (int b = 1; b <= N; ++b) { // For each subcapacity int opt1 = m[i - 1][b]; int opt2 = -1; if (b - v[i - 1] >= 0) { // No caching to keep this readable opt2 = m[i - 1][b - v[i - 1]] + v[i - 1]; if (opt2 > b) opt2 = -1; // Not allowed } m[i][b] = max(opt1, opt2); } } return (m[v.size()][N] == N); } int main() { const vector<int> v = { 1, 3, 7, 4 }; const int N = 11; cout << "Subset sum problem can be solved with the given input: " << boolalpha << ssp(v, N); // true return 0; } ``` The complexity is `O(N⋅I)` where `I` is the number of elements in the starting set. This is a pseudopolynomial complexity. Source: [Knapsack problem](http://marcodiiga.github.io/knapsack-problem)
It look like [Spoj problem](https://www.spoj.com/ABC2019/problems/ACMNEW1/). And my solusion to solve: ``` #include <bits/stdc++.h> using namespace std; int TimTongLonNhatCoGioiHan(int*arr, int songuoichoi, int gioihan){ int hmm = (int)(songuoichoi*songuoichoi/2); int map[hmm]; int dem = 0, i, j, ox = songuoichoi - 1, oy = 0, result = 0, sum; for(i = ox; i > oy; --i){ for(j = oy; j < ox; ++j){ map[dem] = arr[i] + arr[j]; // tinh tong lon nhat cua 3 so for(int k = 0; k < songuoichoi; ++k){ if(k == j || k == i) continue; sum = map[dem] + arr[k]; if(sum > result && sum <= gioihan) result = sum; } dem++; } -- ox; } return result; } int main() { int sophantu = 0, songuoichoi = 0, gioihan = 0; cin>>sophantu; while(sophantu-->0){ cin>>songuoichoi; int i = 0; int arrCanNang[songuoichoi]; for(; i<songuoichoi; ++i){ cin>>arrCanNang[i]; } cin>>gioihan; cout<<TimTongLonNhatCoGioiHan(arrCanNang, songuoichoi, gioihan)<<"\n"; } return 0; } ``` For simple, you can create a matrix [w1, w2, ..., wn] x [w1, w2, ..., wn], put sum(Wi, Wj), foreach k and find MAX sum(Wi, Wj) + Wk.
4,484
*Disclaimer: I am going to mention the investment company that I am using, but I am not related in any way with this company, is just to exemplify my question.* --- I am currently using [foliofn.com](http://www.foliofn.com). They charge $290 per year, for unlimited window trading. You can trade ETF, Mutual Funds, Stocks and others. I am trying to find what is my effect percentage fee for my investment. If I pay 290 per year, and I have 10K in investments (example), the normal calculation will be 290/10,000 = 0.029 = 2.9% Now, the problem is that I have heard that mutual funds have their own fees, so if I have a mutual fund on my portfolio, then how I will make this calculation? I guess there are two questions in this essay: (1) Is my assumption of $290/10K = 2.9% correct? (2) How do I calculate additional fees within my portfolio to know my effective fee rate? Thanks.
2010/11/13
[ "https://money.stackexchange.com/questions/4484", "https://money.stackexchange.com", "https://money.stackexchange.com/users/1635/" ]
Because most people aren't willing to sacrifice their ability to live in the US for 100k. Remember that you can't pull this off multiple times easily. So as a one and done kind of deal, 100k isn't a great trade for the right to live in tthe US or whatever country you have roots in, particularly once you factor in: * If you have 100k in credit on cards, you are likely well-employed with some savings * you can't easily convert that credit to cash. Sure, you can try to buy gift cards and whatnot, but they may not be accepted at Casa de Honduras Hotel for Refugees, and it's not like you can pay with the cc cards- once you stop paying and go on the lam, they'll cut you off.
Quality of life, success and happiness are three factors that are self define by each individual. Most of the time all three factors go hand by hand with your ability to generate wealth and save. Actually, a recent study showed that there were more happy families with savings than with expensive products (car, jewelry and others). These 3 factors, will be very difficult to maintain after someone commit such action. First, because you will fear every interaction with the origin of the money. Second, because every individual has a notion of wrong doing. Third, for the reasons that Jaydles express. Also, most cards, will call you and stop the cards ability to give money, if they see an abusive pattern. Ether, skipping your country has some adverse psychological impact in the family and individual that most of the time 100K is not enough to motivate such change. Thanks for reading. Geo
4,484
*Disclaimer: I am going to mention the investment company that I am using, but I am not related in any way with this company, is just to exemplify my question.* --- I am currently using [foliofn.com](http://www.foliofn.com). They charge $290 per year, for unlimited window trading. You can trade ETF, Mutual Funds, Stocks and others. I am trying to find what is my effect percentage fee for my investment. If I pay 290 per year, and I have 10K in investments (example), the normal calculation will be 290/10,000 = 0.029 = 2.9% Now, the problem is that I have heard that mutual funds have their own fees, so if I have a mutual fund on my portfolio, then how I will make this calculation? I guess there are two questions in this essay: (1) Is my assumption of $290/10K = 2.9% correct? (2) How do I calculate additional fees within my portfolio to know my effective fee rate? Thanks.
2010/11/13
[ "https://money.stackexchange.com/questions/4484", "https://money.stackexchange.com", "https://money.stackexchange.com/users/1635/" ]
It's harder than you think. Once card companies start seeing your debt to credit line ratios climb, they will slash your credit lines quickly. Also, cash credit lines are always much smaller, so in reality, such a scheme would require you to buy goods that can be converted to cash, which dilutes your gains and makes it more likely that you're going to get detected and busted. Think of the other problems. Where do you store your ill-gotten gains? How do you get the money out of the country? How will your actions affect your family and friends? Also, most people are basically good people -- the prospect of defrauding $100k, leaving family and friends behind and living some anonymous life in a third world country isn't an appealing one. If you are criminally inclined, building up a great credit history is not very practical -- most criminals are by nature reactive and want quick results.
Because most people aren't willing to sacrifice their ability to live in the US for 100k. Remember that you can't pull this off multiple times easily. So as a one and done kind of deal, 100k isn't a great trade for the right to live in tthe US or whatever country you have roots in, particularly once you factor in: * If you have 100k in credit on cards, you are likely well-employed with some savings * you can't easily convert that credit to cash. Sure, you can try to buy gift cards and whatnot, but they may not be accepted at Casa de Honduras Hotel for Refugees, and it's not like you can pay with the cc cards- once you stop paying and go on the lam, they'll cut you off.
4,484
*Disclaimer: I am going to mention the investment company that I am using, but I am not related in any way with this company, is just to exemplify my question.* --- I am currently using [foliofn.com](http://www.foliofn.com). They charge $290 per year, for unlimited window trading. You can trade ETF, Mutual Funds, Stocks and others. I am trying to find what is my effect percentage fee for my investment. If I pay 290 per year, and I have 10K in investments (example), the normal calculation will be 290/10,000 = 0.029 = 2.9% Now, the problem is that I have heard that mutual funds have their own fees, so if I have a mutual fund on my portfolio, then how I will make this calculation? I guess there are two questions in this essay: (1) Is my assumption of $290/10K = 2.9% correct? (2) How do I calculate additional fees within my portfolio to know my effective fee rate? Thanks.
2010/11/13
[ "https://money.stackexchange.com/questions/4484", "https://money.stackexchange.com", "https://money.stackexchange.com/users/1635/" ]
It's harder than you think. Once card companies start seeing your debt to credit line ratios climb, they will slash your credit lines quickly. Also, cash credit lines are always much smaller, so in reality, such a scheme would require you to buy goods that can be converted to cash, which dilutes your gains and makes it more likely that you're going to get detected and busted. Think of the other problems. Where do you store your ill-gotten gains? How do you get the money out of the country? How will your actions affect your family and friends? Also, most people are basically good people -- the prospect of defrauding $100k, leaving family and friends behind and living some anonymous life in a third world country isn't an appealing one. If you are criminally inclined, building up a great credit history is not very practical -- most criminals are by nature reactive and want quick results.
Quality of life, success and happiness are three factors that are self define by each individual. Most of the time all three factors go hand by hand with your ability to generate wealth and save. Actually, a recent study showed that there were more happy families with savings than with expensive products (car, jewelry and others). These 3 factors, will be very difficult to maintain after someone commit such action. First, because you will fear every interaction with the origin of the money. Second, because every individual has a notion of wrong doing. Third, for the reasons that Jaydles express. Also, most cards, will call you and stop the cards ability to give money, if they see an abusive pattern. Ether, skipping your country has some adverse psychological impact in the family and individual that most of the time 100K is not enough to motivate such change. Thanks for reading. Geo
4,484
*Disclaimer: I am going to mention the investment company that I am using, but I am not related in any way with this company, is just to exemplify my question.* --- I am currently using [foliofn.com](http://www.foliofn.com). They charge $290 per year, for unlimited window trading. You can trade ETF, Mutual Funds, Stocks and others. I am trying to find what is my effect percentage fee for my investment. If I pay 290 per year, and I have 10K in investments (example), the normal calculation will be 290/10,000 = 0.029 = 2.9% Now, the problem is that I have heard that mutual funds have their own fees, so if I have a mutual fund on my portfolio, then how I will make this calculation? I guess there are two questions in this essay: (1) Is my assumption of $290/10K = 2.9% correct? (2) How do I calculate additional fees within my portfolio to know my effective fee rate? Thanks.
2010/11/13
[ "https://money.stackexchange.com/questions/4484", "https://money.stackexchange.com", "https://money.stackexchange.com/users/1635/" ]
Even if you could get it with no major hassle, $100,000 is just **not that much money**. In a cheap third world country, as an expat you're looking at spending about $800-$2000/month, plus unexpected expenses. Locals live on less, but very few of us would be happy with the lifestyle of a Honduran or Thai farmer. Your 100k will last 4-10 years. This is hardly a great deal considering you're cutting off ties back home and almost becoming a fugitive. With USD going down the drain (e.g. in Thailand it went down 25% in 3 years), this period would probably be even shorter. Of course, you could work in the new country, but if you do then you don't need 100k to start with. The initial amount may improve your security, but from that standpoint being able to go back and work in your home country is worth more.
Quality of life, success and happiness are three factors that are self define by each individual. Most of the time all three factors go hand by hand with your ability to generate wealth and save. Actually, a recent study showed that there were more happy families with savings than with expensive products (car, jewelry and others). These 3 factors, will be very difficult to maintain after someone commit such action. First, because you will fear every interaction with the origin of the money. Second, because every individual has a notion of wrong doing. Third, for the reasons that Jaydles express. Also, most cards, will call you and stop the cards ability to give money, if they see an abusive pattern. Ether, skipping your country has some adverse psychological impact in the family and individual that most of the time 100K is not enough to motivate such change. Thanks for reading. Geo
4,484
*Disclaimer: I am going to mention the investment company that I am using, but I am not related in any way with this company, is just to exemplify my question.* --- I am currently using [foliofn.com](http://www.foliofn.com). They charge $290 per year, for unlimited window trading. You can trade ETF, Mutual Funds, Stocks and others. I am trying to find what is my effect percentage fee for my investment. If I pay 290 per year, and I have 10K in investments (example), the normal calculation will be 290/10,000 = 0.029 = 2.9% Now, the problem is that I have heard that mutual funds have their own fees, so if I have a mutual fund on my portfolio, then how I will make this calculation? I guess there are two questions in this essay: (1) Is my assumption of $290/10K = 2.9% correct? (2) How do I calculate additional fees within my portfolio to know my effective fee rate? Thanks.
2010/11/13
[ "https://money.stackexchange.com/questions/4484", "https://money.stackexchange.com", "https://money.stackexchange.com/users/1635/" ]
I take it the premise of the question is that we're assuming the person isn't worried about the morals. He's a criminal out for a quick buck. And I guess we're assuming that wherever you go, they wouldn't arrest you and extradite you back to the U.S. As others have noted, you can't just walk into a bank the day you graduate high school or get out of prison or whatever and get a credit line of $100,000. You have to build up to that with an income and a pattern of responsible behavior over a period of many years. I don't have the statistics handy but I'd guess most people never reach a credit limit on credit cards of $100,000. Maybe many people could get that on a home equity line of credit, but again, you'd have to build up that equity in your house first, and that would take many years. Then, while $100,000 sounds like a lot of money, how long could you really live on that? Even in a country with low cost of living, it's not like you could live in luxury for the rest of your life. If you can get that kind of credit limit, you probably are used to living on a healthy income. Sure, you could get a similar lifestyle for less in some other countries, but not for THAT much less. If you know a place where for $10,000 a year you can live a life that would cost $100,000 per year in the U.S., I'd like to know about it. Even living a relatively frugal life, I doubt the money would last more than 4 or 5 years. And then what are you going to do? If you come back to the U.S. you'd presumably be promptly arrested. You could get a job in your new country, but you could have done that without first stealing $100,000. Frankly, if you're the sort of person who can get a $100,000 credit limit, you probably can live a lot better in the U.S. by continuing to work and play by the rules than you could by stealing $100,000 and fleeing to Haiti or Eritrea. You might say, okay, $100,000 isn't really enough. What if I could get a $1 million credit limit? But if you have the income and credit rating to get a $1 million credit limit, you probably are making at least several hundred thousand per year, probably a million or more, and again, you're better off to continue to play by the rules. The only way that I see that a scam like this would really work is if you could get a credit limit way out of proportion to any income you could earn legitimately. Like somehow if you could convince the bank to give you a credit limit of $1 million even though you only make $15,000 a year. But that would be a scam in itself. That's why I think the only time you do hear of people trying something like this is when they USED to make a lot of money but have lost it. Like someone has a multi-million dollar business that goes broke, he now has nothing, so before the bank figures it out he maxes out all his credit and runs off.
Quality of life, success and happiness are three factors that are self define by each individual. Most of the time all three factors go hand by hand with your ability to generate wealth and save. Actually, a recent study showed that there were more happy families with savings than with expensive products (car, jewelry and others). These 3 factors, will be very difficult to maintain after someone commit such action. First, because you will fear every interaction with the origin of the money. Second, because every individual has a notion of wrong doing. Third, for the reasons that Jaydles express. Also, most cards, will call you and stop the cards ability to give money, if they see an abusive pattern. Ether, skipping your country has some adverse psychological impact in the family and individual that most of the time 100K is not enough to motivate such change. Thanks for reading. Geo
4,484
*Disclaimer: I am going to mention the investment company that I am using, but I am not related in any way with this company, is just to exemplify my question.* --- I am currently using [foliofn.com](http://www.foliofn.com). They charge $290 per year, for unlimited window trading. You can trade ETF, Mutual Funds, Stocks and others. I am trying to find what is my effect percentage fee for my investment. If I pay 290 per year, and I have 10K in investments (example), the normal calculation will be 290/10,000 = 0.029 = 2.9% Now, the problem is that I have heard that mutual funds have their own fees, so if I have a mutual fund on my portfolio, then how I will make this calculation? I guess there are two questions in this essay: (1) Is my assumption of $290/10K = 2.9% correct? (2) How do I calculate additional fees within my portfolio to know my effective fee rate? Thanks.
2010/11/13
[ "https://money.stackexchange.com/questions/4484", "https://money.stackexchange.com", "https://money.stackexchange.com/users/1635/" ]
It's harder than you think. Once card companies start seeing your debt to credit line ratios climb, they will slash your credit lines quickly. Also, cash credit lines are always much smaller, so in reality, such a scheme would require you to buy goods that can be converted to cash, which dilutes your gains and makes it more likely that you're going to get detected and busted. Think of the other problems. Where do you store your ill-gotten gains? How do you get the money out of the country? How will your actions affect your family and friends? Also, most people are basically good people -- the prospect of defrauding $100k, leaving family and friends behind and living some anonymous life in a third world country isn't an appealing one. If you are criminally inclined, building up a great credit history is not very practical -- most criminals are by nature reactive and want quick results.
Even if you could get it with no major hassle, $100,000 is just **not that much money**. In a cheap third world country, as an expat you're looking at spending about $800-$2000/month, plus unexpected expenses. Locals live on less, but very few of us would be happy with the lifestyle of a Honduran or Thai farmer. Your 100k will last 4-10 years. This is hardly a great deal considering you're cutting off ties back home and almost becoming a fugitive. With USD going down the drain (e.g. in Thailand it went down 25% in 3 years), this period would probably be even shorter. Of course, you could work in the new country, but if you do then you don't need 100k to start with. The initial amount may improve your security, but from that standpoint being able to go back and work in your home country is worth more.
4,484
*Disclaimer: I am going to mention the investment company that I am using, but I am not related in any way with this company, is just to exemplify my question.* --- I am currently using [foliofn.com](http://www.foliofn.com). They charge $290 per year, for unlimited window trading. You can trade ETF, Mutual Funds, Stocks and others. I am trying to find what is my effect percentage fee for my investment. If I pay 290 per year, and I have 10K in investments (example), the normal calculation will be 290/10,000 = 0.029 = 2.9% Now, the problem is that I have heard that mutual funds have their own fees, so if I have a mutual fund on my portfolio, then how I will make this calculation? I guess there are two questions in this essay: (1) Is my assumption of $290/10K = 2.9% correct? (2) How do I calculate additional fees within my portfolio to know my effective fee rate? Thanks.
2010/11/13
[ "https://money.stackexchange.com/questions/4484", "https://money.stackexchange.com", "https://money.stackexchange.com/users/1635/" ]
It's harder than you think. Once card companies start seeing your debt to credit line ratios climb, they will slash your credit lines quickly. Also, cash credit lines are always much smaller, so in reality, such a scheme would require you to buy goods that can be converted to cash, which dilutes your gains and makes it more likely that you're going to get detected and busted. Think of the other problems. Where do you store your ill-gotten gains? How do you get the money out of the country? How will your actions affect your family and friends? Also, most people are basically good people -- the prospect of defrauding $100k, leaving family and friends behind and living some anonymous life in a third world country isn't an appealing one. If you are criminally inclined, building up a great credit history is not very practical -- most criminals are by nature reactive and want quick results.
I take it the premise of the question is that we're assuming the person isn't worried about the morals. He's a criminal out for a quick buck. And I guess we're assuming that wherever you go, they wouldn't arrest you and extradite you back to the U.S. As others have noted, you can't just walk into a bank the day you graduate high school or get out of prison or whatever and get a credit line of $100,000. You have to build up to that with an income and a pattern of responsible behavior over a period of many years. I don't have the statistics handy but I'd guess most people never reach a credit limit on credit cards of $100,000. Maybe many people could get that on a home equity line of credit, but again, you'd have to build up that equity in your house first, and that would take many years. Then, while $100,000 sounds like a lot of money, how long could you really live on that? Even in a country with low cost of living, it's not like you could live in luxury for the rest of your life. If you can get that kind of credit limit, you probably are used to living on a healthy income. Sure, you could get a similar lifestyle for less in some other countries, but not for THAT much less. If you know a place where for $10,000 a year you can live a life that would cost $100,000 per year in the U.S., I'd like to know about it. Even living a relatively frugal life, I doubt the money would last more than 4 or 5 years. And then what are you going to do? If you come back to the U.S. you'd presumably be promptly arrested. You could get a job in your new country, but you could have done that without first stealing $100,000. Frankly, if you're the sort of person who can get a $100,000 credit limit, you probably can live a lot better in the U.S. by continuing to work and play by the rules than you could by stealing $100,000 and fleeing to Haiti or Eritrea. You might say, okay, $100,000 isn't really enough. What if I could get a $1 million credit limit? But if you have the income and credit rating to get a $1 million credit limit, you probably are making at least several hundred thousand per year, probably a million or more, and again, you're better off to continue to play by the rules. The only way that I see that a scam like this would really work is if you could get a credit limit way out of proportion to any income you could earn legitimately. Like somehow if you could convince the bank to give you a credit limit of $1 million even though you only make $15,000 a year. But that would be a scam in itself. That's why I think the only time you do hear of people trying something like this is when they USED to make a lot of money but have lost it. Like someone has a multi-million dollar business that goes broke, he now has nothing, so before the bank figures it out he maxes out all his credit and runs off.
49,074,058
Hy everyone, my Visual Studio (2017) shows me an error in my Xamarin Forms project. I have developed an application (that uses some external packeges) and, from quite some time, i have an error that says: > > Error NU1201: Project "projectname".App.Android is not compatible with xamarinios10 (Xamarin.iOS,Version=v1.0)/win-x86. Project "projectname".App.Android supports: monoandroid80 (MonoAndroid,Version=v8.0) > > > I can't understand why i get this error, that seems to influence the installation of NuGet packages in the iOS project (it fails everytime). The execution of the Android app doesn't have any problem, i can't try the iOS one at the moment, i am waiting for the key. If someone had ever seen this error i'd like to have some help, thank you!
2018/03/02
[ "https://Stackoverflow.com/questions/49074058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9229947/" ]
Solved by myself, somehow Visual Studio had added some kind of dependecy in the iOS project to the Android one, making it (obviously) incompatible. Visual Studio initialiy blocked me from removing it, i had to remove the dependency manually from the iOS ".csproj" and reload the solution. Hope it helps if this happenes to someone else.
I got same issue because I tried to import a package designed for Android , not for iOS .
38,572,127
I'm a newbie to data warehousing and I've been reading articles and watching videos on the principles but I'm a bit confused as to how I would take the design below and convert it into a star schema. In all the examples I've seen the fact table references the dim tables, so I'm assuming the questionId and responseId would be part of the fact table? Any advice would be much appreciated. [![enter image description here](https://i.stack.imgur.com/ivAAj.png)](https://i.stack.imgur.com/ivAAj.png)
2016/07/25
[ "https://Stackoverflow.com/questions/38572127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260246/" ]
I can't see the image at the moment (blocked by my firewall @ the office). but I'll try to give you some ideas. The general idea is to organize your measurable 'facts' into what are called fact tables. There are 3 main types of facts, but that is a topic for a different day (but I'd be happy to go into this if needed). Each of these facts are what you'd see in the center of typical 'star schema'. The other attributes within the fact tables are typically FK references to the dimension tables. Regarding dimensions, these are groups of attributes that share commonality (the most notable being a calendar dimension). This is important because when you're doing analysis across multiple facts the dimensions are what you use to connect them. If you consider this simple example: A product is ordered and then shipped. We could have 2 transaction facts (one that contains the qty ordered - measure, type of product ordered - dimension, and transaction date - dimension). We'd also have a transaction fact for the product shipping ( qty shipped - measure, product type - dimension, and ship date - dimension). This simple schema could be used to answer questions like 'how many products by product type last quarter were ordered but not shipped'. Hopefully this helps you get started.
Usually a fact table is used to aggregate measures - which are always numeric. Examples would be: sales dollars, distances, weights, number of items sold. The type of data you drew here doesn't have any cut and dry "measure" so you need to decide what you want to measure. Is the number of answers per question? Is it how many responses per sample? This is often called an Event Fact table (if you want to search for other examples). And you need some sort of reporting requirements before you can turn it into a star schema. So it isn't an easy answer...
38,572,127
I'm a newbie to data warehousing and I've been reading articles and watching videos on the principles but I'm a bit confused as to how I would take the design below and convert it into a star schema. In all the examples I've seen the fact table references the dim tables, so I'm assuming the questionId and responseId would be part of the fact table? Any advice would be much appreciated. [![enter image description here](https://i.stack.imgur.com/ivAAj.png)](https://i.stack.imgur.com/ivAAj.png)
2016/07/25
[ "https://Stackoverflow.com/questions/38572127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260246/" ]
I can't see the image at the moment (blocked by my firewall @ the office). but I'll try to give you some ideas. The general idea is to organize your measurable 'facts' into what are called fact tables. There are 3 main types of facts, but that is a topic for a different day (but I'd be happy to go into this if needed). Each of these facts are what you'd see in the center of typical 'star schema'. The other attributes within the fact tables are typically FK references to the dimension tables. Regarding dimensions, these are groups of attributes that share commonality (the most notable being a calendar dimension). This is important because when you're doing analysis across multiple facts the dimensions are what you use to connect them. If you consider this simple example: A product is ordered and then shipped. We could have 2 transaction facts (one that contains the qty ordered - measure, type of product ordered - dimension, and transaction date - dimension). We'd also have a transaction fact for the product shipping ( qty shipped - measure, product type - dimension, and ship date - dimension). This simple schema could be used to answer questions like 'how many products by product type last quarter were ordered but not shipped'. Hopefully this helps you get started.
It's so easy :) Responses is fact, all other is dimensions. And your schema is now star designed, because you can directly connect fact with all dimensions. Example, when you need to redesign its structure where addresses stored in separate table and related with sample. You must add address table id into responses table for get star schema.
49,046,773
For my Android project, I need global singleton Cache object to access data about a user through the app. A problem occurs when an app goes into the background and after some time of using other apps I try to open app variables in Cache objects are null. Everything is okay when I kill the app and open it again. I'm using dependency injection to access Cache object. Why doesn't app start again if that happened? Is there some annotation to keep cache variable even in low memory conditions? This is my Cache class ``` class Cache { var categories : Array<BaseResponse.Category>? = null var user : BaseResponse.User? = null var options : BaseResponse.OptionsMap? = null var order: MenuOrderDataModel? = null } ``` This is Storage module for DI ``` @Module class StorageModule { @Singleton @Provides fun getSharedPrefs(context: Context): SharedPreferences { return PreferenceManager.getDefaultSharedPreferences(context) } @Singleton @Provides fun getCache() : Cache = Cache() } ``` I inject object `@Inject lateinit var cache: Cache` and then populate with user data in splash screen. Edit - added code snippets from Application and launch activity ``` class MyApp : Application() { val component: ApplicationComponent by lazy { DaggerApplicationComponent .builder() .appModule(AppModule(this)) .build() } companion object { @JvmStatic lateinit var myapp: MyApp } override fun onCreate() { super.onCreate() myapp= this Fabric.with(this, Crashlytics()) } } ``` Splash activity: ``` class SplashActivity : AppCompatActivity(), View.OnClickListener { @Inject lateinit var viewModel : ISplashViewModel private lateinit var disposable : Disposable override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) MyApp.myapp.component.inject(this) } ```
2018/03/01
[ "https://Stackoverflow.com/questions/49046773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3984177/" ]
You're getting crashes because you initialize those variables in one Activity, and expect it to be set always, in the other Activity. But Android doesn't work like that, you can easily end up crashing because after low memory condition happens, only the *current* Activity gets recreated at first, previous Activity is recreated on back navigation, and all static variables are nulled out (because the process is technically restarted). Try it out: * **put your application in background with HOME button** * click the **TERMINATE button on Logcat tab** [![terminate button](https://i.stack.imgur.com/n3o3n.png)](https://i.stack.imgur.com/n3o3n.png) * then **re-launch the app from the launcher.** You'll experience this phenomenon. ***In Android Studio 4.0, after you use `Run` from Android Studio instead of starting the app from launcher, the Terminate button SOMETIMES works a bit differently and MIGHT force-stop your app making it forget your task state on your attempt. In that case, just try again, launching the app from launcher. It will work on your second try.*** You can also trigger the "Terminate Application" behavior from the terminal, as per <https://codelabs.developers.google.com/codelabs/android-lifecycles/#6>, it looks like this: ``` $ adb shell am kill your.app.package.name ``` --- In the new Logcat (Android Studio Electric Eel and above), the "terminate process" button is removed, and was moved into the Device Monitor tab ("Kill Process"). [![enter image description here](https://i.stack.imgur.com/q8lGk.png)](https://i.stack.imgur.com/q8lGk.png) --- Solution: check for nulls and re-initialize things in a base activity (or in LiveData.onActive), or use `onSaveInstanceState`.
I would like to expand on @EpicPandaForce answer with implementation details using savedInstanceState and SavedStateHandle. 
Official documentation: <https://developer.android.com/topic/libraries/architecture/viewmodel/viewmodel-savedstate> Note that I’m using Koin for dependency injection. Inject your viewModel inside your Activity as stateViewModel: `val viewModel: MyActivityViewModel by stateViewModel(state = { Bundle() })` That way you can inject SavedStateHandle inside ViewModel and handle storing and restoring data inside it. Override onPause method in your Activity that will be opened after the process is killed so you can storeState at that moment. ``` override fun onPause() { super.onPause() viewModel.storeState() } ``` Store all properties you don’t want to become null after the process is killed. An object has to be parcelable. `savedStateHandle.set(STATE_KEY, yourProperty)` In the onCreate method, you will check if savedInstanceState is not null so you can restore the state. ``` override fun onCreate(savedInstanceState: Bundle?) { setTheme(R.style.AppTheme) super.onCreate(savedInstanceState) if (savedInstanceState != null) { viewModel.restoreState() } } ``` Reinit your property and remove that value from savedStateHandle ``` fun restoreState() { yourProperty = savedStateHandle.get<Any>(STATE_KEY) savedStateHandle.remove<Any>(STATE_KEY) } ```
67,713
Suppose I have a regular rectangular weighted grid with multiple agents and obstacles. Agents cannot be in grid sites that contain obstacles, and for simplicity assume multiple agents can be in the same grid site. If I select a single location on the grid and want to find the nearest agent to that location, a good solution is easy: I can simply do a breadth-first (BF) search. However, suppose I have *n* target locations and *m*>=*n* agents. I want to visit the target locations with *n* agents simultaneously. I do not care which agent goes to which location, but the total distance travelled must be minimal. Or, to rephrase, I'm attempting to find a distance-weighted maximum matching for two sets of nodes on a graph. One solution would be to calculate the shortest path from all agents to all targets and then do a bipartite matching. Since the graph may be disconnected by obstacles, this could result in needless multiple sampling of the entire grid space of a connected region. This hardly seems optimal. (Solution 1) I propose the following 'algorithm' (Solution 2): 1. from each target location start a BF search until there is one agent in every target's searched space 2. if the number of unique agents in the searched spaces is less than *n*, continue searching from all target locations 3. if a matching between targets and agents in their respective searched spaces is not possible with full target covering, continue searching from the ~~target locations where covering was not possible and all other target sites that share agents with the uncovered target sites~~ all target locations. 4. the first matching that fulfils step 3 is the solution now I have two questions: 1. is solution 2 optimal, i.e. is it guaranteed that I will select precisely those agents with the least total distance to their assigned targets? I.e. am I not neglecting any agents by not continuing the search for long enough? 2. *if* solution 2 *is* optimal, are there any further ways of reducing the computational complexity?
2016/12/21
[ "https://cs.stackexchange.com/questions/67713", "https://cs.stackexchange.com", "https://cs.stackexchange.com/users/63459/" ]
Read the following paper on the generalization of your problem with "makespan" as the objective. The proposed algorithm should work even if $m\neq n$. H. Ma and S. Koenig. "Optimal Target Assignment and Path Finding for Teams of Agents." <http://idm-lab.org/bib/abstracts/papers/aamas16a.pdf>
No, your proposed algorithm is not correct: it might output a matching that is sub-optimal. Here is a counter example. We have three agents, A, B, and C. We have three targets, T, U, and V. Here are the distances: Distances to T: A: 1, B: 100, C: 101 Distances to U: A: 2, B: 1, C: 3 Distances to V: A: 101, B: 1, C: 100 In the first round of your algorithm, you'll discover the AT, BU, and BV distances, but no complete matching is possible, so you'll continue searching. In the second round, you'll discover the BT, AU, and CV distances. Now a complete matching is possible, and A-T B-U C-V is the minimal matching given the information so far, so your algorithm will output that assignment, for a total cost of 102. However, this isn't the optimal answer; the optimal answer is A-T C-U B-V, for a total cost of 5. So in this example, your algorithm outputs the wrong answer. --- In general, if you have a candidate algorithm like this and you want to know whether it is correct, a good strategy is to test it with random testing. Implement your proposed algorithm, and implement a (slower) golden-reference algorithm that is known to be correct. Now generate a million random small test cases (i.e., random inputs), and run both implementations on each and check that both implementations give the same answer in all cases. If you find any mismatch, you know your algorithm is incorrect and it's back to the drawing board. If you don't find any mismatches, that doesn't prove your algorithm is correct -- but the procedure is still helpful for catching some buggy ideas.
37,378,863
I'm trying to create my first SSAS Tabular model. I'm following the steps mentioned in following tutorial: <https://msdn.microsoft.com/en-us/library/hh231690.aspx> While trying to load the tables to the model, I get the following error: > > Blockquote > > > "!! Relationship: dbo.DimCustomer[GeographyKey]->dbo.DimGeography[GeographyKey] * Status: error * Reason:Object reference not set to an instance of an object. !! Relationship: dbo.FactInternetSales[CustomerKey]->dbo.DimCustomer[CustomerKey] * Status: error * Reason:Object reference not set to an instance of an object. !! Relationship: dbo.FactInternetSales[OrderDateKey]->dbo.DimDate[DateKey] * Status: error * Reason:Object reference not set to an instance of an object. !! Relationship: dbo.FactInternetSales[DueDateKey]->dbo.DimDate[DateKey] * Status: error * Reason:Object reference not set to an instance of an object. !! Relationship: dbo.FactInternetSales[ShipDateKey]->dbo.DimDate[DateKey] * Status: error * Reason:Object reference not set to an instance of an object. !! Relationship: dbo.FactInternetSales[ProductKey]->dbo.DimProduct[ProductKey] * Status: error * Reason:Object reference not set to an instance of an object." > > Blockquote > > > What shall I do to get rid of this error message? I'm using SQL Server 2014 and Visual Studio 2015 (SSDT).
2016/05/22
[ "https://Stackoverflow.com/questions/37378863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6368443/" ]
this is because SSAS can not process data. I guess it's because of your impersonation setting in your connection. check your connection setting and test it again.
This is probably because your `model.bim` is closed when you're trying to deploy. Change this to having the model open and try again.
25,557,491
I need to match every line where if the line has "event4" then also must have "event70" or "event71", if it doesnt have "event4", match it also. Using Regular expresions. Input: ``` event4,event56,event70 event5, event72 No event number event4,event56 ``` Rows expected to be matched: ``` event4,event56,event70 event5, event72 No event number ``` Regex: ``` preg_match( "/(?:event4,(.*(event70|event71)+)|.*)/", $text, $matches, PREG_OFFSET_CAPTURE); ``` Now is matching all of the rows.
2014/08/28
[ "https://Stackoverflow.com/questions/25557491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3988152/" ]
As discussed in the comments of the answer by JWK: The images seem to be landscape instead of portrait. Some applications that show an image read extra information from the exif profile of the image to determine the orientation. This was causing some confusion because ImageMagick does not automatically use the information from the exif profile. This can be forced with the auto-orient option. The command should be changed to this: ``` convert source.jpg -auto-orient -resize 200x out.jpg ``` The 200x can also be written as 200 but using 200x or x200 shows better if the width or the height should be resized.
I got this solved. Turned out that the image information of my portrait source file was somehow messed up. I ran the `identify portrait_source.jpg` command and noticed that it had the width and height wrong ( `4320 x 3240` instead of `3240 × 4320`). So basically, ImageMagick thought it was looking at a landscape oriented file when really it was a portrait oriented file. All other programs (OSX Finder, Preview) showed the image in portrait orientation. Simply opening the image in Preview and saving it fixed the image information and after that the resize worked as expected. So, if you run into an issue similar to mine, make sure to check the image information on your source image. I have no idea why the information was wrong in the first place. I used a photo made with a digital camera.
19,428,229
i have this code: ``` List<EditText> someList = new ArrayList<EditText>(); //Let's say we'd like to add 10 EditTexts for(int i = 0; i < 10; i++){ EditText t1 = new EditText(); //The EditText you'd like to add to the list t1.setText("lol"); //Give the EditText the value 'lol' someList.add(t1); //Add the EditText to the list } //Go over the list and get the values for(EditText t : someList){ String val = t.getText(); //Get the value for the temp EditText variable t } ``` i would like to know how can i get the arraylist text with an index number? like: `somelist[2]`
2013/10/17
[ "https://Stackoverflow.com/questions/19428229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1549219/" ]
Something like this should do the trick: ``` int index = 2; EditText et = someList.get(index); Log.d(TAG, et.getText()); ```
try this : ``` EditText t = someList.get(2); String text=t.getText().toString(); ```
19,428,229
i have this code: ``` List<EditText> someList = new ArrayList<EditText>(); //Let's say we'd like to add 10 EditTexts for(int i = 0; i < 10; i++){ EditText t1 = new EditText(); //The EditText you'd like to add to the list t1.setText("lol"); //Give the EditText the value 'lol' someList.add(t1); //Add the EditText to the list } //Go over the list and get the values for(EditText t : someList){ String val = t.getText(); //Get the value for the temp EditText variable t } ``` i would like to know how can i get the arraylist text with an index number? like: `somelist[2]`
2013/10/17
[ "https://Stackoverflow.com/questions/19428229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1549219/" ]
try this : ``` EditText t = someList.get(2); String text=t.getText().toString(); ```
try this ``` EditText text2=someList.get(2); ```
19,428,229
i have this code: ``` List<EditText> someList = new ArrayList<EditText>(); //Let's say we'd like to add 10 EditTexts for(int i = 0; i < 10; i++){ EditText t1 = new EditText(); //The EditText you'd like to add to the list t1.setText("lol"); //Give the EditText the value 'lol' someList.add(t1); //Add the EditText to the list } //Go over the list and get the values for(EditText t : someList){ String val = t.getText(); //Get the value for the temp EditText variable t } ``` i would like to know how can i get the arraylist text with an index number? like: `somelist[2]`
2013/10/17
[ "https://Stackoverflow.com/questions/19428229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1549219/" ]
try this : ``` EditText t = someList.get(2); String text=t.getText().toString(); ```
use this: ``` somelist.get(2); ``` this will return the edittext at the position 2.
19,428,229
i have this code: ``` List<EditText> someList = new ArrayList<EditText>(); //Let's say we'd like to add 10 EditTexts for(int i = 0; i < 10; i++){ EditText t1 = new EditText(); //The EditText you'd like to add to the list t1.setText("lol"); //Give the EditText the value 'lol' someList.add(t1); //Add the EditText to the list } //Go over the list and get the values for(EditText t : someList){ String val = t.getText(); //Get the value for the temp EditText variable t } ``` i would like to know how can i get the arraylist text with an index number? like: `somelist[2]`
2013/10/17
[ "https://Stackoverflow.com/questions/19428229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1549219/" ]
Something like this should do the trick: ``` int index = 2; EditText et = someList.get(index); Log.d(TAG, et.getText()); ```
try this ``` EditText text2=someList.get(2); ```
19,428,229
i have this code: ``` List<EditText> someList = new ArrayList<EditText>(); //Let's say we'd like to add 10 EditTexts for(int i = 0; i < 10; i++){ EditText t1 = new EditText(); //The EditText you'd like to add to the list t1.setText("lol"); //Give the EditText the value 'lol' someList.add(t1); //Add the EditText to the list } //Go over the list and get the values for(EditText t : someList){ String val = t.getText(); //Get the value for the temp EditText variable t } ``` i would like to know how can i get the arraylist text with an index number? like: `somelist[2]`
2013/10/17
[ "https://Stackoverflow.com/questions/19428229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1549219/" ]
Something like this should do the trick: ``` int index = 2; EditText et = someList.get(index); Log.d(TAG, et.getText()); ```
use this: ``` somelist.get(2); ``` this will return the edittext at the position 2.
9,173,533
``` <html> <head> <script type="text/javascript" src="jquery-1.7.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ alert('hi'+$("input:text").val()); $("input:not(:empty)").val("sdfdf"); }); }); </script> </head> <body> <input type="text" value="aa" /> <input type="text" value="" /> <input type="text" value="aa" /> <button>Click me</button> </body> </html> ``` i am trying to access empty textboxex using jquery and assigning a value hello to it.. but it's not working . thanks in advance
2012/02/07
[ "https://Stackoverflow.com/questions/9173533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1194147/" ]
[`:empty`](http://api.jquery.com/empty-selector/) checks for whether an element has child elements. `input` elements cannot have child elements. If you want to test that the `input` element's value is blank: ``` $(document).ready(function(){ $("button").click(function(){ $("input").filter(function() { return this.value.length !== 0; }).val("sdfdf"); }); }); ``` There we get all of the `input` elements, and then filter it so only the ones whose `value` property isn't `""` are included.
> > jQuery(':empty') > Description: Select all elements that have no children (including text > nodes). > > > From <http://api.jquery.com/empty-selector/>. Thus `:empty` does not do what you think it does. Have a look at this answer <https://stackoverflow.com/a/1299468/138023> for a solution.
9,173,533
``` <html> <head> <script type="text/javascript" src="jquery-1.7.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ alert('hi'+$("input:text").val()); $("input:not(:empty)").val("sdfdf"); }); }); </script> </head> <body> <input type="text" value="aa" /> <input type="text" value="" /> <input type="text" value="aa" /> <button>Click me</button> </body> </html> ``` i am trying to access empty textboxex using jquery and assigning a value hello to it.. but it's not working . thanks in advance
2012/02/07
[ "https://Stackoverflow.com/questions/9173533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1194147/" ]
You could use another selector for your task: ``` $("input[value='']").val("sdfdf"); ```
> > jQuery(':empty') > Description: Select all elements that have no children (including text > nodes). > > > From <http://api.jquery.com/empty-selector/>. Thus `:empty` does not do what you think it does. Have a look at this answer <https://stackoverflow.com/a/1299468/138023> for a solution.
9,173,533
``` <html> <head> <script type="text/javascript" src="jquery-1.7.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ alert('hi'+$("input:text").val()); $("input:not(:empty)").val("sdfdf"); }); }); </script> </head> <body> <input type="text" value="aa" /> <input type="text" value="" /> <input type="text" value="aa" /> <button>Click me</button> </body> </html> ``` i am trying to access empty textboxex using jquery and assigning a value hello to it.. but it's not working . thanks in advance
2012/02/07
[ "https://Stackoverflow.com/questions/9173533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1194147/" ]
> > jQuery(':empty') > Description: Select all elements that have no children (including text > nodes). > > > From <http://api.jquery.com/empty-selector/>. Thus `:empty` does not do what you think it does. Have a look at this answer <https://stackoverflow.com/a/1299468/138023> for a solution.
You could use an .each with this inside: ``` if( $(this).val().length === 0 ) { $(this).parents('p').addClass('warning'); } ```
9,173,533
``` <html> <head> <script type="text/javascript" src="jquery-1.7.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ alert('hi'+$("input:text").val()); $("input:not(:empty)").val("sdfdf"); }); }); </script> </head> <body> <input type="text" value="aa" /> <input type="text" value="" /> <input type="text" value="aa" /> <button>Click me</button> </body> </html> ``` i am trying to access empty textboxex using jquery and assigning a value hello to it.. but it's not working . thanks in advance
2012/02/07
[ "https://Stackoverflow.com/questions/9173533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1194147/" ]
[`:empty`](http://api.jquery.com/empty-selector/) checks for whether an element has child elements. `input` elements cannot have child elements. If you want to test that the `input` element's value is blank: ``` $(document).ready(function(){ $("button").click(function(){ $("input").filter(function() { return this.value.length !== 0; }).val("sdfdf"); }); }); ``` There we get all of the `input` elements, and then filter it so only the ones whose `value` property isn't `""` are included.
You could use another selector for your task: ``` $("input[value='']").val("sdfdf"); ```
9,173,533
``` <html> <head> <script type="text/javascript" src="jquery-1.7.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ alert('hi'+$("input:text").val()); $("input:not(:empty)").val("sdfdf"); }); }); </script> </head> <body> <input type="text" value="aa" /> <input type="text" value="" /> <input type="text" value="aa" /> <button>Click me</button> </body> </html> ``` i am trying to access empty textboxex using jquery and assigning a value hello to it.. but it's not working . thanks in advance
2012/02/07
[ "https://Stackoverflow.com/questions/9173533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1194147/" ]
[`:empty`](http://api.jquery.com/empty-selector/) checks for whether an element has child elements. `input` elements cannot have child elements. If you want to test that the `input` element's value is blank: ``` $(document).ready(function(){ $("button").click(function(){ $("input").filter(function() { return this.value.length !== 0; }).val("sdfdf"); }); }); ``` There we get all of the `input` elements, and then filter it so only the ones whose `value` property isn't `""` are included.
You could use an .each with this inside: ``` if( $(this).val().length === 0 ) { $(this).parents('p').addClass('warning'); } ```
9,173,533
``` <html> <head> <script type="text/javascript" src="jquery-1.7.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ alert('hi'+$("input:text").val()); $("input:not(:empty)").val("sdfdf"); }); }); </script> </head> <body> <input type="text" value="aa" /> <input type="text" value="" /> <input type="text" value="aa" /> <button>Click me</button> </body> </html> ``` i am trying to access empty textboxex using jquery and assigning a value hello to it.. but it's not working . thanks in advance
2012/02/07
[ "https://Stackoverflow.com/questions/9173533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1194147/" ]
You could use another selector for your task: ``` $("input[value='']").val("sdfdf"); ```
You could use an .each with this inside: ``` if( $(this).val().length === 0 ) { $(this).parents('p').addClass('warning'); } ```
25,479,156
I have just started a Sharepoint, I would need items listed in Sharepoint 2013. Please let me know is any rest service available to access data from sharepoint which I can store in my local db. Please suggest me what are the best way to access data from it. Thanks, Laxmilal Menaria
2014/08/25
[ "https://Stackoverflow.com/questions/25479156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1444686/" ]
Yes it is perfectly fine to have hbase as your backend. What I am doing to get this done,( I have a online community and forum running on my website ) 1.Writing C# code to access the Hbase using thrift, very easy and simple to get this done. (Thrift is a cross language binding platform, to HBase Java is only the first class citizen!) 2.Managing the HBase cluster(have it on Amazon) using the Amazon EMI 3.Using ganglia to monitor Hbase Some Extra tips: So you can organize the web application like this 1. You can set up your webservers on Amazon Web Services or IBMWebSphere 2. You can set up your own HBase cluster using cloudera or use AmazonEC2 again here. 3. Communication between web server and Hbase master node happens via thrift client. 4. You can generate thrift code in your own desired programming language Here are some links that helped me A)[Thrift Client](http://hbase.apache.org/0.94/apidocs/org/apache/hadoop/hbase/thrift/doc-files/Hbase.html#Fn_Hbase_getRowWithColumns "Thrift Client"), B)[Filtering options](http://hbase.apache.org/book/thrift.html) Along with this I refer to HBase administrative cookbook by Yifeng Jiang and HBase reference guide by Lars George in case I dont get answers on web. Filtering options provided by HBase are fast and accurate. Let's say if you use HBase for storing your product details, you can have sub-stores and have a column in your Product table, which tells to which store a product may belong and use Filters to get products for a specific store.
I think you should read the article below: "Apache HBase Do’s and Don’ts" <http://blog.cloudera.com/blog/2011/04/hbase-dos-and-donts/>
46,393,578
I am trying to set Outlook appointments from a `userform` in `Excel`. The code works if I am referencing cells. How do I reference boxes in a `userform`? I also need to add to the code recipients for the meeting which I would reference from a different list worksheet. Here is the code that references the cells in Excel which works by clicking a button in the worksheet: ``` Sub AddAppointments() ' Create the Outlook session Set myOutlook = CreateObject("Outlook.Application") ' Start at row 2 r = 2 Do Until Trim(Cells(r, 1).Value) = "" ' Create the AppointmentItem Set myApt = myOutlook.CreateItem(1) ' Set the appointment properties myApt.Subject = Cells(r, 1).Value myApt.Location = Cells(r, 2).Value myApt.Start = Cells(r, 3).Value myApt.Duration = Cells(r, 4).Value ' If Busy Status is not specified, default to 2 (Busy) If Trim(Cells(r, 5).Value) = "" Then myApt.BusyStatus = 2 Else myApt.BusyStatus = Cells(r, 5).Value End If If Cells(r, 6).Value > 0 Then myApt.ReminderSet = True myApt.ReminderMinutesBeforeStart = Cells(r, 6).Value Else myApt.ReminderSet = False End If myApt.Body = Cells(r, 7).Value myApt.Display r = r + 1 Loop End Sub ``` This is my attempt at changing the code to reference boxes in a userform: ``` Private Sub Cmdappointment_Click() Dim outlookapp As Object 'the mail item is the contents inside a mail Dim mitem As AppointmentItem 'created outlook app Set outlookapp = CreateObject("outlook.Application") 'it will open a new application Set outlookapp = New Outlook.Application 'Set mail item Set mitem = outlookapp.CreateItem(olMailItem) Do Until userform2.TextBox4.Value = "" ' Create the AppointmentItem Set myApt = myOutlook.CreateItem(1) ' Set the appointment properties On Error Resume Next mitem myApt.Subject = Me.texbox4.Value myApt.Location = Me.texbox3.Value myApt.Start = Me.ComboBox1.Value myApt.Duration = Me.ComboBox2.Value ' If Busy Status is not specified, default to 2 (Busy) If Me.ComboBox3.Value = "" Then myApt.BusyStatus = 2 Else myApt.BusyStatus = Me.ComboBox3.Value End If If Me.TextBox1.Value > 0 Then myApt.ReminderSet = True myApt.ReminderMinutesBeforeStart = Me.TextBox1.Value Else myApt.ReminderSet = False End If myApt.Body = Me.TextBox2.Value myApt.Display End With Loop End Sub ```
2017/09/24
[ "https://Stackoverflow.com/questions/46393578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8577284/" ]
As you are fetching an associative array you can simply output the array keys as the header row: ``` $header = false; // a way to track if we've output the header. while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS+OCI_ASSOC)) { if ($header == false) { // this is the first iteration of the while loop so output the header. print '<thead><tr>'; foreach (array_keys($row) as $key) { print '<th>'.($key !== null ? htmlentities($key, ENT_QUOTES) : '').'</th>'; } print '</tr></thead>'; $header = true; // make sure we don't output the header again. } // output all the data rows. print '<tr>'; foreach ($row as $item) { print '<td>'.($item !== null ? htmlentities($item, ENT_QUOTES) : '').'</td>'; } print '</tr>'; } ```
You can query `ALL_TAB_COLUMNS` table to get all columns of a specific table in Oracle. ``` select COLUMN_NAME from ALL_TAB_COLUMNS where TABLE_NAME='MYTABLE'; ```
46,393,578
I am trying to set Outlook appointments from a `userform` in `Excel`. The code works if I am referencing cells. How do I reference boxes in a `userform`? I also need to add to the code recipients for the meeting which I would reference from a different list worksheet. Here is the code that references the cells in Excel which works by clicking a button in the worksheet: ``` Sub AddAppointments() ' Create the Outlook session Set myOutlook = CreateObject("Outlook.Application") ' Start at row 2 r = 2 Do Until Trim(Cells(r, 1).Value) = "" ' Create the AppointmentItem Set myApt = myOutlook.CreateItem(1) ' Set the appointment properties myApt.Subject = Cells(r, 1).Value myApt.Location = Cells(r, 2).Value myApt.Start = Cells(r, 3).Value myApt.Duration = Cells(r, 4).Value ' If Busy Status is not specified, default to 2 (Busy) If Trim(Cells(r, 5).Value) = "" Then myApt.BusyStatus = 2 Else myApt.BusyStatus = Cells(r, 5).Value End If If Cells(r, 6).Value > 0 Then myApt.ReminderSet = True myApt.ReminderMinutesBeforeStart = Cells(r, 6).Value Else myApt.ReminderSet = False End If myApt.Body = Cells(r, 7).Value myApt.Display r = r + 1 Loop End Sub ``` This is my attempt at changing the code to reference boxes in a userform: ``` Private Sub Cmdappointment_Click() Dim outlookapp As Object 'the mail item is the contents inside a mail Dim mitem As AppointmentItem 'created outlook app Set outlookapp = CreateObject("outlook.Application") 'it will open a new application Set outlookapp = New Outlook.Application 'Set mail item Set mitem = outlookapp.CreateItem(olMailItem) Do Until userform2.TextBox4.Value = "" ' Create the AppointmentItem Set myApt = myOutlook.CreateItem(1) ' Set the appointment properties On Error Resume Next mitem myApt.Subject = Me.texbox4.Value myApt.Location = Me.texbox3.Value myApt.Start = Me.ComboBox1.Value myApt.Duration = Me.ComboBox2.Value ' If Busy Status is not specified, default to 2 (Busy) If Me.ComboBox3.Value = "" Then myApt.BusyStatus = 2 Else myApt.BusyStatus = Me.ComboBox3.Value End If If Me.TextBox1.Value > 0 Then myApt.ReminderSet = True myApt.ReminderMinutesBeforeStart = Me.TextBox1.Value Else myApt.ReminderSet = False End If myApt.Body = Me.TextBox2.Value myApt.Display End With Loop End Sub ```
2017/09/24
[ "https://Stackoverflow.com/questions/46393578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8577284/" ]
As you are fetching an associative array you can simply output the array keys as the header row: ``` $header = false; // a way to track if we've output the header. while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS+OCI_ASSOC)) { if ($header == false) { // this is the first iteration of the while loop so output the header. print '<thead><tr>'; foreach (array_keys($row) as $key) { print '<th>'.($key !== null ? htmlentities($key, ENT_QUOTES) : '').'</th>'; } print '</tr></thead>'; $header = true; // make sure we don't output the header again. } // output all the data rows. print '<tr>'; foreach ($row as $item) { print '<td>'.($item !== null ? htmlentities($item, ENT_QUOTES) : '').'</td>'; } print '</tr>'; } ```
OCI8 has meta data calls like `oci_num_fields()` and `oci_field_name()`. They can be used like: ``` $s = oci_parse($c, "select * from employees"); if (!$s) { $m = oci_error($c); trigger_error('Could not parse statement: '. $m['message'], E_USER_ERROR); } $r = oci_execute($s); if (!$r) { $m = oci_error($s); trigger_error('Could not execute statement: '. $m['message'], E_USER_ERROR); } echo "<table border='1'>\n"; $ncols = oci_num_fields($s); echo "<tr>\n"; for ($i = 1; $i <= $ncols; ++$i) { $colname = oci_field_name($s, $i); echo " <th><b>".htmlspecialchars($colname,ENT_QUOTES|ENT_SUBSTITUTE)."</b></th>\n"; } echo "</tr>\n"; while (($row = oci_fetch_array($s, OCI_ASSOC+OCI_RETURN_NULLS)) != false) { echo "<tr>\n"; foreach ($row as $item) { echo "<td>"; echo $item!==null?htmlspecialchars($item, ENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;"; echo "</td>\n"; } echo "</tr>\n"; } echo "</table>\n"; ```
19,322
I am working on a reporting application and we fetch several records based on their start/end date ranges. Users can choose to leave both start and/or end dates blank. Examples: ``` Example 1 - Date: 1/15/2010 to 2/3/2011 Example 2 - Date: [blank] to 2/3/2011 Example 3 - Date: 1/1/2010 to [blank] Example 4 - Date: [blank] to [blank] ``` Example 1 reports on all records between Jan 1st 2010 and Feb 3rd 2011. Example 2 reports on any records that ended before Feb 3rd 2011. Example 3 reports on any records that started after Jan 1st 2011. Example 4 reports on all records. What is the best thing to say for those [blank] spots? "Beginning of Time" and "Infinite Future" are *technically* not correct -- because you could set ended date to blank and start date to 1/1/1970 and get a record that ended in the 1980's - not exactly the 'infinite future' -- Also "Beginning of Time" and "Infinite Future" are quite long in terms of space.
2012/03/27
[ "https://ux.stackexchange.com/questions/19322", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/13495/" ]
You can have a single field that opens a date range. Once the user finished selecting dates - it appears on a single field. This way you can use: 1. 1/15/2010 to 2/3/2011 2. until 2/3/2011 3. from 1/1/2010 4. All time
You aren't really *referring* to the beginning and end of time here. You just mean from the beginning of the data set to the end of the data set. We solve this in one of two ways in our products, depending largely on the familiarity of the user with the dataset being reported on: **Option 1** 1. 1/15/2010 to 2/3/2011 2. Before 2/3/2011 (could also be "Up to 2/3/2011" or "2/3/2011 and earlier") 3. After 1/1/2010 (could also be "Since 1/1/2010" or "1/1/2010 and later") 4. *No value in either field* The exact wording you choose should depend on things like whether your search is date-inclusive or exclusive. **Option 2** Auto-fill the beginning and end dates with the actual first and last dates represented in the dataset, so that it becomes: 1. 1/15/2010 to 2/3/2011 2. 1/1/2009 to 2/3/2011 3. 1/1/2010 to 3/28/2011 (you may choose to use the word "today" instead of the current date for clarity) 4. 1/1/2009 to 3/28/2011 This option only makes sense if the users understand that the 1/1/2009 is the beginning of the dataset; that's something that you'd need to decide based on what the data represents.
9,216,278
I have made one console application for email notification in c#. Can i convert this console application in to window service? Thanks.
2012/02/09
[ "https://Stackoverflow.com/questions/9216278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1157791/" ]
In visual studio, create a "Windows Service" project instead of a "Console Application". Look in the code that gets generated for you. There will be an OnStart() and OnStop() method. Those are the methods that will be called when your service is started and stopped. Put your code in those methods and you will have a Windows Service.
When I go about this, I write the application in a class that does not consider its self a console application. By that I mean I dont write to the Console. I use log4net to write everything to... just log to Info. Use the console app to call the application class and in the app.config you can have an appender for console logging... so you get the console output. In the windows service this will just write to a file or not at all for the Info level logging. Its important to note the differences between a console app and a service... a service is not interactive and you can not input anything, so you app must consider this. For the windows service use the same class, but use the windows service project to start it. ApplicationLogic: Has all the logic to run the application. Can take the arguments to make the app run the way it needs to, but does not interact with the console (can, but it would be bad design). Writes everything to logging (log4net maybe). ConsoleApp: Is a wrapper around ApplicationLogic that can prompt the user for what ever it needs, can prompt for input and send it to ApplicationLogic. Has a log4net console appender if you need to see the output from ApplicationLogic. WindowsService: Is a wrapper around ApplicationLogic. Has predetermined logic to keep it looping and running the Application logic. Logs to a file, no console output.
9,216,278
I have made one console application for email notification in c#. Can i convert this console application in to window service? Thanks.
2012/02/09
[ "https://Stackoverflow.com/questions/9216278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1157791/" ]
In visual studio, create a "Windows Service" project instead of a "Console Application". Look in the code that gets generated for you. There will be an OnStart() and OnStop() method. Those are the methods that will be called when your service is started and stopped. Put your code in those methods and you will have a Windows Service.
Contrary to some of the suggestions made by other answers, you probably can't do what you want using a Windows Service. It can't display the "notification" you expect because services can't display any kind of user interface. The appropriate solution is to create a regular application that runs in the background without showing any windows. You can't do this with a console application (well, you *can*, but let's not overcomplicate things) because each time you run it, the console window will be displayed. But if you create a standard Windows application (either a Windows Forms or WPF application) then just don't create a window, everything will work out just fine. You'll probably want to create and place an icon into the taskbar's notification area, which will handle displaying the notification upon the arrival of email. If you're creating a WinForms application, this can be done easily by using the [`NotifyIcon` component](http://msdn.microsoft.com/en-us/library/system.windows.forms.notifyicon.aspx). Something like (warning, written without the aid of a compiler!): ``` static class Program { [STAThread] static void Main() { // Standard infrastructure code Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Create a context menu and add item(s) to it ContextMenu mnu = new ContextMenu(); MenuItem mnuExit = new MenuItem("E&xit"); mnu.MenuItems.Add(mnuExit); mnuExit.Click += mnuExit_Click); // Create the NotifyIcon NotifyIcon ni = new NotifyIcon(); ni.Icon = new Icon(GetType(), "icon.ico"); ni.Text = "Email Notifier"; ni.ContextMenu = mnu; ni.Visible = true; // Run the application Application.Run(); // Before exiting, remove the NotifyIcon from the taskbar ni.Visible = false; } private static void mnuExit_Click(object Sender, EventArgs e) { Application.Exit(); } } ```
9,216,278
I have made one console application for email notification in c#. Can i convert this console application in to window service? Thanks.
2012/02/09
[ "https://Stackoverflow.com/questions/9216278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1157791/" ]
Contrary to some of the suggestions made by other answers, you probably can't do what you want using a Windows Service. It can't display the "notification" you expect because services can't display any kind of user interface. The appropriate solution is to create a regular application that runs in the background without showing any windows. You can't do this with a console application (well, you *can*, but let's not overcomplicate things) because each time you run it, the console window will be displayed. But if you create a standard Windows application (either a Windows Forms or WPF application) then just don't create a window, everything will work out just fine. You'll probably want to create and place an icon into the taskbar's notification area, which will handle displaying the notification upon the arrival of email. If you're creating a WinForms application, this can be done easily by using the [`NotifyIcon` component](http://msdn.microsoft.com/en-us/library/system.windows.forms.notifyicon.aspx). Something like (warning, written without the aid of a compiler!): ``` static class Program { [STAThread] static void Main() { // Standard infrastructure code Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Create a context menu and add item(s) to it ContextMenu mnu = new ContextMenu(); MenuItem mnuExit = new MenuItem("E&xit"); mnu.MenuItems.Add(mnuExit); mnuExit.Click += mnuExit_Click); // Create the NotifyIcon NotifyIcon ni = new NotifyIcon(); ni.Icon = new Icon(GetType(), "icon.ico"); ni.Text = "Email Notifier"; ni.ContextMenu = mnu; ni.Visible = true; // Run the application Application.Run(); // Before exiting, remove the NotifyIcon from the taskbar ni.Visible = false; } private static void mnuExit_Click(object Sender, EventArgs e) { Application.Exit(); } } ```
When I go about this, I write the application in a class that does not consider its self a console application. By that I mean I dont write to the Console. I use log4net to write everything to... just log to Info. Use the console app to call the application class and in the app.config you can have an appender for console logging... so you get the console output. In the windows service this will just write to a file or not at all for the Info level logging. Its important to note the differences between a console app and a service... a service is not interactive and you can not input anything, so you app must consider this. For the windows service use the same class, but use the windows service project to start it. ApplicationLogic: Has all the logic to run the application. Can take the arguments to make the app run the way it needs to, but does not interact with the console (can, but it would be bad design). Writes everything to logging (log4net maybe). ConsoleApp: Is a wrapper around ApplicationLogic that can prompt the user for what ever it needs, can prompt for input and send it to ApplicationLogic. Has a log4net console appender if you need to see the output from ApplicationLogic. WindowsService: Is a wrapper around ApplicationLogic. Has predetermined logic to keep it looping and running the Application logic. Logs to a file, no console output.
212,757
I have a remote server, which runs Linux. I would like to install remotely the OS image, in case that it gets corrupted (this has already happened twice while I am experimenting with the OS). So far, the only way that I have, is to physically go to the machine location and use a USB disk to mount the OS and the BIOS see it, so it can boot from it. Is there any way to basically connect to the machine via `ssh`, attach this image and have it act like it would be on a virtual drive on Windows (like daemon tools for example), so it would persist to a reboot and allow me to install remotely the OS? I was looking at solutions on Google, but I found something mentioning PXE boot....which sounds complicated, since you need a server and such, and it is not as simple as mounting an image and being done with it. Beyond that, I found nothing useful, so I am quite short on options....does anyone know how to accomplish this?
2015/06/29
[ "https://unix.stackexchange.com/questions/212757", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/119523/" ]
Here's a hypothetical situation which I consider might be plausible: 1. The targeted machine is EFI. 2. `grub` is either never installed on the target or has been utterly wiped from the system. * it can only ever interfere and offers nothing of value otherwise. So what we might do in the above case is configure a boot option for a small installation/rescue image we keep on our `/esp` or EFI system partition. If anything were ever to go wrong with our current installation, then, for so long as we can at least access the EFI system partition by some means, then we can interface our firmware and set the machine to boot to our recovery image on next reboot. In that case all we would have to do is change a text file or two, cross our fingers and run *`reboot now`*. Here is a basic set of commands for a minimally configured Arch Linux *(because it's what I use)* system which could still do as I describe. * First, we'll make a work directory and download some files. + I use `aria2c` here. I recommend it, but use whatever works. + I unzip `rEFInd` with `7za` but the same tool preference is yours in all cases here. + If you're not reading this within a few hours/days of my posting it, then there is a very good chance that the links used below are *not* current. ```sh mkdir /tmp/work && cd /tmp/work || exit aria2c 'magnet:?xt=urn:btih:331c7fac2e13c251d77521d2dc61976b6fc4a033&dn=archlinux-2015.06.01-dual.iso&tr=udp://tracker.archlinux.org:6969&tr=http://tracker.archlinux.org:6969/announce' \ 'http://iweb.dl.sourceforge.net/project/refind/0.8.7/refind-cd-0.8.7.zip' 7za x ref*.zip; rm ref*zip ``` * Next I'll make an image disk. + I use a file here with loop devices, but you may want to use an actual disk if you want to boot to this from firmware. + In the case of an actual device the `fallocate` and `losetup` stuff can be ignored and the actual device names will far more likely correspond to `/dev/sda[12]` than `/dev/loop0p[12]` ```sh fallocate -l4G img ``` * Now I'll partition that disk with the `gdisk` utility and assign it to a loop device. + This is a scripted shortcut for the options you'd want to feed the program interactively. It will create a GUID partition table and a partition of type **EFI-system** that spans the first available 750Mib of the target disk and another linux default partition spanning the rest of the disk. - These partitions will be `/dev/sda1` and `/dev/sda2` respectively if you're using a real disk, which will be `/dev/sda` rather than `./img`. It is usually desirable to add more than one partition for a linux root, which is assumed to be the purpose of `/dev/sda2`. + `printf` script or no, the `gdisk` program is easy to use - and so you might do better to go at it interactively instead. The target disk should not be mounted when it is run, and you'll probably need root rights to `w`rite the changes. + As a general rule you can do pretty much whatever you want in that program without any effect until you `w`rite - so be sure when you do. + I'll be putting my `$TGT` in a shell variable. Except for its definition here, which you may want to tailor as necessary, where I use it so can you. ```sh printf %s\\n o y n 1 '' +750M ef00 \ n 2 '' '' '' '' w y | gdisk ./img >/dev/null TGT=$(sudo losetup --show -Pf img)p ``` * We'll need a filesystem on the esp, too. It must be FAT. + I give mine the fs label *`VESP`*. You should call yours whatever you want. + We'll use the label later in `/etc/fstab` and another config file - so definitely make it *something.* + In my opinion you should always label *all* disks. + If you install an OS to `${TGT}2` now you will of course need a filesystem for it as well. ```sh sudo mkfs.vfat -nVESP "$TGT"1 ``` * And we'll make some `mount` directories and start extracting the relevant files. ```sh set ref ref*iso \ arch arch*iso \ efi arch/EFI/archiso/efiboot.img while [ "$#" -gt 0 ] do mkdir "$1" || exit sudo mount "$2" "$1" shift 2 done; mkdir esp ``` * Install `rEFInd`... + `rEFInd` is a boot manager - which mostly just offers and populates boot menus. + `rEFInd` will put its config files on the esp and these can be edited at any time and anyway you like. ```sh sudo ref/install.sh --usedefault "$TGT"1 && sudo umount ref && rm -rf ref* ``` * Now we'll `mount` our esp and get the needed files off of the Arch install disk to get our own live bootable rescue disk. + Most live disks implement a sort of ugly hack to make the flat, unpartitioned iso filesystem *look* like an acceptable boot device to a UEFI system while still maintaining backwards compatibility w/ BIOS systems. + Arch Linux is no exception. + This *ugly hack* is that *`efiboot.img`* currently mounted on `./efi`. It's where we'll find our kernel and initramfs image file. The *other* ones on the disk *(in `./arch/arch/boot`)* will **not** work for EFI systems. ```sh sudo sh -ec <<CONF ' mount "$1" esp cp -ar efi/EFI/archiso esp/EFI cp -ar arch/arch/*x86* esp/EFI/archiso mkdir esp/EFI/archiso/cow xargs > esp/EFI/archiso/refind_linux.conf umount efi arch rm -rf efi arch*' -- "$TGT"1 \"arch_iso\" \"archisobasedir=EFI/archiso \ archisolabel=VESP \ copytoram \ cow_label=VESP \ cow_directory=/EFI/archiso/cow\ cow_persistence=P \ cow_spacesize=384M \ initrd=EFI/archiso/archiso.img\" CONF ``` You have essentially just installed - from the ground up - a pre-boot rescue environment with a persistent *copy-on-write* save file *(so you might, for example `systemctl enable sshd_socket` now and the setting would persist in the live system's next boot)*. The Arch Linux live install media now resides on your system's boot partition and can be called from the boot menu at any time. Of course, you also installed the boot menu manager. * A couple of things about the above should stand out to you: + I use `*x86*` because I have a 64-bit machine and that glob gets what I need. For a 32-bit installation *(but why?)* use `*686*` instead. - *What I need*, by the way, is a total of only 7 files and approximately 300M. - The live-system's rootfs is the squashed image in `esp/EFI/archiso/x86_64/airootfs.sfs`. + I specify the disk by label. There are no *hints* or other such nonsense - the disk is named and so it is easily found. You'll need to substitute in whatever you chose for an esp label instead of *`VESP`*. + The *`copytoram`* kernel parameter instructs the Arch Linux live `init` system to copy its rootfs image into a tmpfs before loopmounting it - which frees you actually to access the esp when working in that environment. Most live install systems offer similarly arranged constructs. Where EFI shines is in its ability to handle a *filesystem*. On modern computers there is absolutely no need to pack some raw binary and wedge it in between your disk partitions. It astounds me that people still do, when, instead, they could manage and configure their boot environment with simple text files arranged in a regular, everyday directory tree. Above I put the kernel and initramfs in their own named folder in a central tree structure. The EFI - which will take its cues from `rEFInd` in this case for convenience - will invoke that at boot by *pathname* because it *mounts* the esp. Now all that is left to do is to ensure you understand how to select the system which will actually boot when you need to. Understand - you can boot this right now. You can do it in a virtual machine w/ `qemu` *(you'll need OVMF `-pflash` firmware)* or you can reboot your computer and `rEFInd` will detect the kernel and pass its pathname to the firmware which will load and execute the Arch Linux live system. When you install a more permanent system on the disk - or several *(which you can do right now if you so choose by rebooting to the live disk and performing the installation)* - you'll want to keep its kernel and initramfs in the same structure. This is very easily arranged. * If, for example, you were to install a system on a root partition named, for lack of an imagination, *`root`*, you'd want to set it up something like this: + `mount --bind` its particular boot folder over the root `/boot` path in `/etc/fstab`. + You'll need two lines in `/etc/fstab` and to create a mount point in `/esp` to handle this. ```sh sudo sh -c <<\FSTAB ' [ -d /esp ] || mkdir /esp findmnt /esp || mount -L ESP /esp mkdir -p /esp/EFI/root cp /boot/kernel binary \ /boot/initramfs.img \ /esp/EFI/root mount -B /esp/EFI/root /boot cat >> /etc/fstab echo "$1">/boot/refind_linux.conf ' -- '"new_menu_item" "root=LABEL=root"' LABEL=ESP /esp vfat defaults 0 2 /esp/EFI/root /boot none bind,defaults 0 0 FSTAB ``` You only ever have to do anything like that once per installation - and that is assuming you didn't set it up that way in the first place - which is easier because the kernel and initramfs will already be where they belong. Once you've got those lines in `/etc/fstab` and a minimal config file in `/boot/refind_linux.conf` you're set for good. You can support as many installations as you like on the same system with the same `/esp` device and centralize all bootable binaries in the same tree just like that. Different systems will do things a little differently - Windows takes a little more cajoling to get it to conform, for example - but they will *all work*. * Ok, the last thing you need to know, as I said before, is how choose the next booting installation from the filesystem. This is configured in the file `/esp/EFI/BOOT/refind.conf`. + You should read this file - it's probably 99% comment and will tell you all about what you might do with it. + Of course, you don't really have to do anything - by default `rEFInd` will boot the most recently updated kernel in its scan tree. + But I usually wind up setting the following options: ```sh <<\DEF sudo tee \ /esp/EFI/BOOT/refind.conf.def ### refind.conf.def ### when renamed to refind.conf this file ### will cause refind to select by default ### the menu item called "new_menu_item" ### in its /boot/refind_linux.conf default_selection new_menu_item ### this file will also set the menu timeout ### to only 5 seconds at every boot timeout 5 ### END DEF ``` + And the rescue file... ```sh <<\RES sudo tee \ /esp/EFI/BOOT/refind.conf.res ### refind.conf.res ### this one will default to selecting ### the entry named "arch_iso" with a ### 10 second timeout default_selection arch_iso timeout 10 ### END RES ``` - And so now you can just move them around. - For example, to make the rescue environment definitely boot after you do `reboot now`... ``` sudo cp /esp/EFI/BOOT/refind.conf.res \ /esp/EFI/BOOT/refind.conf ``` - And substitute *`.def`* for the *`.res`* used above, of course, to go back to default root.
Let me restate your question for clarity: You want to install a Linux distribution but you want to avoid needing to physically access the server. You cannot use alternatives such as the following: * Dell's iDRAC or an equivalent from another vendor. These solutions provide out-of-band server management that works even when the server is not running any operating system, and one of the features they provide is that you can attach virtual installation media such as a virtual USB stick. + But in order to use this you must own a server that has such a feature. * Network booting, using PXE. PXE is a feature that most servers have these days, that allows the server to boot over the network using DHCP and TFTP. + But you must be able to provision a DHCP server and a TFTP server in order to use PXE and this may not be possible in your environment (for example, there is no nearby server to provide those services). The idea you present in your question is to mount an installation image over the network using the server's existing operating system, and somehow install from that. At first glance, this of course cannot possibly work. In order to install, you have to reboot, especially if you want to install over top of the existing operating system since that would overwrite the current operating system and if you didn't reboot then you would be trying to overwrite the operating system while it is still in use. Yet if you reboot then of course the existing operating system shuts down, including the network-mounted installation image. I can think of very few ways around this. Here are 2 candidates. They are both very advanced procedures and I don't recommend that you try them unless you understand what they are doing and how they work. Also, practice first using a locally-accessible server. * Use `kexec` to boot another operating system directly from the existing operating system. `kexec` is the only facility I know about that lets you provide a boot image for a new operating system that replaces the current one. `kexec` can only be used (effectively) if the current operating system is Linux and the target operating system is also Linux. `kexec` requires that you give it a kernel and an initrd to load. You can't give it anything else such as a root filesystem image. Luckily, most Linux installers use a self-contained kernel & initrd pair, so you can use that. For example you can get the necessary kernel and initrd for the Debian installer from the [netboot download page](https://www.debian.org/distrib/netinst#netboot). Extract them from `netboot.tar.gz`. (Yes, you should be able to use the same kernel & initrd as you would for netbooting.) I have not tested this idea and I would consider it an expert procedure, so you may have some work to do to make it happen which is beyond the scope of this answer. * Install the new operating system from inside the current operating system, alongside it. Then switch to the new one. You can install to a separate partition or, if using LVM (recommended in this case) to a different LV. This of course requires that you have enough space to temporarily store both operating systems. You will need to use a tool such as `debootstrap` to install the new operating system instead of the regular operating system installer. Using `debootstrap` is much less user-friendly than using the regular installer because you must do several steps by yourself which are normally taken care of by the installer (for example, install the kernel and bootloader, edit base system configuration files). That makes this an expert procedure as well. In all cases, you'll want to have remote console access to the server. That can be achieved for example with IPMI.
49,693,841
Ok so I have a basic `GET` method for returning a 'genre' based on an id in a `MongoDB` database and being called by `Mongoose`. This works just fine when the id is valid but as soon as it is invalid it crashed my application. My code: ``` router.get('/:id', async (req, res) => { const genre = await Genre.findById(req.params.id); if(!genre) return genreNotFoundError(res); res.send(genre); }); // Helper Functions function genreNotFoundError(res) { res.status(404).send('Genre not found'); } ``` Here's the request and body: ``` http://localhost:5000/api/genres/5ac68d7d7d113ded8c36f3fc { "_id": "5ac68d7d7d113ded8c36f3fc", "name": "Drama", "__v": 0 } ``` The crash occurs at the point at which the `_id` field is changed, as below: ``` http://localhost:5000/api/genres/1234 ``` This gives me the below error. I have tried using `findByOne({_id: req.params.id})` as suggested in other posts but that does not seem to do anything. Error: ``` (node:70853) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "1234" at path "_id" for model "Genre" at new CastError (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/error/cast.js:27:11) at ObjectId.cast (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/schema/objectid.js:158:13) at ObjectId.SchemaType.applySetters (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/schematype.js:724:12) at ObjectId.SchemaType._castForQuery (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/schematype.js:1095:15) at ObjectId.castForQuery (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/schema/objectid.js:198:15) at ObjectId.SchemaType.castForQueryWrapper (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/schematype.js:1064:15) at cast (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/cast.js:300:32) at model.Query.Query.cast (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/query.js:3208:12) at model.Query.Query._castConditions (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/query.js:1280:10) at model.Query.Query._findOne (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/query.js:1496:8) at process.nextTick (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/kareem/index.js:311:33) at _combinedTickCallback (internal/process/next_tick.js:131:7) at process._tickCallback (internal/process/next_tick.js:180:9) (node:70853) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:70853) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. ```
2018/04/06
[ "https://Stackoverflow.com/questions/49693841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3346752/" ]
In python 3, [`map`](https://docs.python.org/3/library/functions.html#map) returns an iterator: ``` >>> map(print, listing) <map object at 0x7fabf5d73588> ``` This iterator is *lazy*, which means that it won't do anything until you iterate over it. Once you *do* iterate over it, you get the values of your list printed: ``` >>> listing = [1, 2, 3] >>> for _ in map(print, listing): ... pass ... 1 2 3 ``` What this also means is that `map` isn't the right tool for the job. `map` creates an iterator, so it should only be used if you're planning to iterate over that iterator. It shouldn't be used for side effects, like printing values. See also [When should I use `map` instead of a for loop](https://stackoverflow.com/questions/1975250/when-should-i-use-a-map-instead-of-a-for-loop).
I wouldn't recommend using [`map`](https://docs.python.org/3/library/functions.html#map) here, as you don't really care about the iterator. If you want to simplify the basic "for loop", you could instead use [`str.join()`](https://docs.python.org/3/library/stdtypes.html#str.join): ``` >>> mylist = ['hello', 'there', 'everyone'] >>> '\n'.join(mylist) hello there everyone ``` Or if you have a non-string list: ``` >>> mylist = [1,2,3,4] >>> '\n'.join(map(str, mylist)) 1 2 3 4 ```
13,567,687
I am trying to make an application for WP8, but I cannot for the life of me figure out how data binding works. I have tried example after example, which seem like they are doing pretty much exactly the same as me, but nothing seems to work. Basically the profile class contains the name of a profile and an icon. I want to display a list of these profiles on the screen, with the name to the right of the icon. When I run the project in the WP8 phone emulator, nothing shows up at all. If i change the properties of the elements in the DataTemplate (namely Source and Text) to absolute strings, it works fine. MainPage.xaml: ``` <phone:PhoneApplicationPage ..> <Grid x:Name="LayoutRoot" Background="Transparent"> <Grid.Resources> <DataTemplate x:Name="ProfileListTemplate"> <StackPanel Margin="10"> <Image Grid.Column="0" Width="50" Height="50" Source="{Binding ImageSource}" Stretch="Fill"/> <TextBlock Grid.Column="1" Text="{Binding ProfileName}" Margin="10" HorizontalAlignment="Left" FontSize="36"/> </StackPanel> </DataTemplate> </Grid.Resources> <phone:LongListSelector x:Name="ProfilesList" Grid.Row="1" VerticalAlignment="Top" FontSize="36" Height="535" Margin="10,0,0,0" ItemTemplate="{StaticResource ProfileListTemplate}"/> </Grid> </phone:PhoneApplicationPage> ``` MainPage.xaml.cs: ``` namespace Profiles { public partial class MainPage : PhoneApplicationPage { public MainPage() { InitializeComponent(); ObservableCollection<Profile> ProfilesCollection = new ObservableCollection<Profile>(); ProfilesCollection.Add(new Profile("Nighttime")); ProfilesCollection.Add(new Profile("Work")); ProfilesCollection.Add(new Profile("Home")); ProfilesList.ItemsSource = ProfilesCollection; } } } ``` "Profile" Class: ``` namespace Profiles { class Profile { public string ProfileName = ""; public string ImageSource = "/Resources/Delete.png"; public Profile(string name) { ProfileName = name; } } } ```
2012/11/26
[ "https://Stackoverflow.com/questions/13567687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1853736/" ]
Try changing `ProfileName` and `ImageSource` from fields to properties. ``` class Profile { private const string DefaultImageSource = "/Resources/Delete.png"; public string ProfileName { get; set; } public string ImageSource {get; set; } public Profile(string name) { ProfileName = name; ImageSource = DefaultImageSource; } } ```
Change your Profile class to be properties, as in the following... ``` public class Profile { string profileName = ""; string imageSource = "/Resources/Delete.png"; public string ProfileName { get { return profileName; } set { profileName = value; } } public string ImageSource { get { return imageSource; } set { imageSource = value; } } public Profile(string name) { ProfileName = name; } } ``` As your logic gets more involved, it is then relatively trivial to add further behaviour, and also implement INotifyPropertyChanged if you need to track changes within a single object.
37,512,502
what is the right way to draw an arrow that loops back to point to its origin in matplotlib? i tried: ``` plt.figure() plt.xlim([0, 1]) plt.ylim([0, 1]) plt.annotate("", xy=(0.6, 0.9), xycoords="figure fraction", xytext = (0.6, 0.8), textcoords="figure fraction", fontsize = 10, \ color = "k", arrowprops=dict(edgecolor='black', connectionstyle="angle,angleA=-180,angleB=45", arrowstyle = '<|-', facecolor="k", linewidth=1, shrinkA = 0, shrinkB = 0)) plt.show() ``` this doesn't give the right result: [![arrow](https://i.stack.imgur.com/DfHPl.png)](https://i.stack.imgur.com/DfHPl.png) the `connectionstyle` arguments are hard to follow from this page (<http://matplotlib.org/users/annotations_guide.html>). i'm looking for is something like [this](http://i.istockimg.com/file_thumbview_approve/25282609/6/stock-illustration-25282609-arrow-sign-refresh-reload-loop-rotation-pictogram-black-icon.jpg) or [this](https://cdn0.iconfinder.com/data/icons/arrows-volume-5/48/280-512.png): [![loopy arrow](https://i.stack.imgur.com/nVPdN.png)](https://i.stack.imgur.com/nVPdN.png) **update:** the answer linked to does not show how do this with `plt.annotate` which has other features i want to use. the proposal to use `$\circlearrowleft$` marker is not a real solution.
2016/05/29
[ "https://Stackoverflow.com/questions/37512502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5768196/" ]
It seems the easiest way to create an easily modifiable looping arrow is to use [patches](http://matplotlib.org/api/patches_api.html). I've pasted code to do this below. Change the variables in the variables section and things should all rotate and scale together. You can play around with the patch that creates the arrow head to make a different shape though I suspect that this triangle will be the easiest one. ``` %matplotlib inline # from __future__ import division #Uncomment for python2.7 import matplotlib.pyplot as plt from matplotlib.patches import Arc, RegularPolygon import numpy as np from numpy import radians as rad fig = plt.figure(figsize=(9,9)) ax = plt.gca() def drawCirc(ax,radius,centX,centY,angle_,theta2_,color_='black'): #========Line arc = Arc([centX,centY],radius,radius,angle=angle_, theta1=0,theta2=theta2_,capstyle='round',linestyle='-',lw=10,color=color_) ax.add_patch(arc) #========Create the arrow head endX=centX+(radius/2)*np.cos(rad(theta2_+angle_)) #Do trig to determine end position endY=centY+(radius/2)*np.sin(rad(theta2_+angle_)) ax.add_patch( #Create triangle as arrow head RegularPolygon( (endX, endY), # (x,y) 3, # number of vertices radius/9, # radius rad(angle_+theta2_), # orientation color=color_ ) ) ax.set_xlim([centX-radius,centY+radius]) and ax.set_ylim([centY-radius,centY+radius]) # Make sure you keep the axes scaled or else arrow will distort drawCirc(ax,1,1,1,0,250) drawCirc(ax,2,1,1,90,330,color_='blue') plt.show() ``` [![enter image description here](https://i.stack.imgur.com/Nvg9M.png)](https://i.stack.imgur.com/Nvg9M.png)
Try this: ``` import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.set_xlim(1,3) ax.set_ylim(1,3) ax.plot([2.5],[2.5],marker=r'$\circlearrowleft$',ms=100) plt.show() ``` [![enter image description here](https://i.stack.imgur.com/kyNYr.png)](https://i.stack.imgur.com/kyNYr.png)
37,512,502
what is the right way to draw an arrow that loops back to point to its origin in matplotlib? i tried: ``` plt.figure() plt.xlim([0, 1]) plt.ylim([0, 1]) plt.annotate("", xy=(0.6, 0.9), xycoords="figure fraction", xytext = (0.6, 0.8), textcoords="figure fraction", fontsize = 10, \ color = "k", arrowprops=dict(edgecolor='black', connectionstyle="angle,angleA=-180,angleB=45", arrowstyle = '<|-', facecolor="k", linewidth=1, shrinkA = 0, shrinkB = 0)) plt.show() ``` this doesn't give the right result: [![arrow](https://i.stack.imgur.com/DfHPl.png)](https://i.stack.imgur.com/DfHPl.png) the `connectionstyle` arguments are hard to follow from this page (<http://matplotlib.org/users/annotations_guide.html>). i'm looking for is something like [this](http://i.istockimg.com/file_thumbview_approve/25282609/6/stock-illustration-25282609-arrow-sign-refresh-reload-loop-rotation-pictogram-black-icon.jpg) or [this](https://cdn0.iconfinder.com/data/icons/arrows-volume-5/48/280-512.png): [![loopy arrow](https://i.stack.imgur.com/nVPdN.png)](https://i.stack.imgur.com/nVPdN.png) **update:** the answer linked to does not show how do this with `plt.annotate` which has other features i want to use. the proposal to use `$\circlearrowleft$` marker is not a real solution.
2016/05/29
[ "https://Stackoverflow.com/questions/37512502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5768196/" ]
My suggestion uses just the plot command ``` import matplotlib.pyplot as plt import numpy as np def circarrowdraw(x0, y0, radius=1, aspect=1, direction=270, closingangle=-330, arrowheadrelativesize=0.3, arrowheadopenangle=30, *args): """ Circular arrow drawing. x0 and y0 are the anchor points. direction gives the angle of the circle center relative to the anchor in degrees. closingangle indicates how much of the circle is drawn in degrees with positive being counterclockwise and negative being clockwise. aspect is important to make the aspect of the arrow fit the current figure. """ xc = x0 + radius * np.cos(direction * np.pi / 180) yc = y0 + aspect * radius * np.sin(direction * np.pi / 180) headcorrectionangle = 5 if closingangle < 0: step = -1 else: step = 1 x = [xc + radius * np.cos((ang + 180 + direction) * np.pi / 180) for ang in np.arange(0, closingangle, step)] y = [yc + aspect * radius * np.sin((ang + 180 + direction) * np.pi / 180) for ang in np.arange(0, closingangle, step)] plt.plot(x, y, *args) xlast = x[-1] ylast = y[-1] l = radius * arrowheadrelativesize headangle = (direction + closingangle + (90 - headcorrectionangle) * np.sign(closingangle)) x = [xlast + l * np.cos((headangle + arrowheadopenangle) * np.pi / 180), xlast, xlast + l * np.cos((headangle - arrowheadopenangle) * np.pi / 180)] y = [ylast + aspect * l * np.sin((headangle + arrowheadopenangle) * np.pi / 180), ylast, ylast + aspect * l * np.sin((headangle - arrowheadopenangle) * np.pi / 180)] plt.plot(x, y, *args) ``` To test it: ``` plt.figure() plt.plot(np.arange(10)**2, 'b.') bb = plt.gca().axis() asp = (bb[3] - bb[2]) / (bb[1] - bb[0]) circarrowdraw(6, 36 , radius=0.4, aspect=asp, direction=90) plt.grid() plt.show() ``` [![enter image description here](https://i.stack.imgur.com/xFGmR.png)](https://i.stack.imgur.com/xFGmR.png)
Another possibility is to use tikz to generate the figure: ``` \documentclass {minimal} \usepackage {tikz} \begin{document} \usetikzlibrary {arrows} \begin {tikzpicture}[scale=1.8] \draw[-angle 90, line width=5.0mm, rounded corners=20pt] (0.25,0)-- (1.0, 0.0) -- (1.0, -3.0) -- (-3.0, -3.0) -- (-3.0, 0) --(-1,0); \end{tikzpicture} \end{document} ``` This is the result: [![enter image description here](https://i.stack.imgur.com/W3D8l.jpg)](https://i.stack.imgur.com/W3D8l.jpg) there is a pgf/tikz backend in matplotlib that you could generate your matplotlib output to tikz code that pdflatex or lualatex can process. So this way, I think, you could insert seamlessly the looparrow figure in your matplotlib figure. See for ex: <http://matplotlib.org/users/whats_new.html#pgf-tikz-backend>
37,512,502
what is the right way to draw an arrow that loops back to point to its origin in matplotlib? i tried: ``` plt.figure() plt.xlim([0, 1]) plt.ylim([0, 1]) plt.annotate("", xy=(0.6, 0.9), xycoords="figure fraction", xytext = (0.6, 0.8), textcoords="figure fraction", fontsize = 10, \ color = "k", arrowprops=dict(edgecolor='black', connectionstyle="angle,angleA=-180,angleB=45", arrowstyle = '<|-', facecolor="k", linewidth=1, shrinkA = 0, shrinkB = 0)) plt.show() ``` this doesn't give the right result: [![arrow](https://i.stack.imgur.com/DfHPl.png)](https://i.stack.imgur.com/DfHPl.png) the `connectionstyle` arguments are hard to follow from this page (<http://matplotlib.org/users/annotations_guide.html>). i'm looking for is something like [this](http://i.istockimg.com/file_thumbview_approve/25282609/6/stock-illustration-25282609-arrow-sign-refresh-reload-loop-rotation-pictogram-black-icon.jpg) or [this](https://cdn0.iconfinder.com/data/icons/arrows-volume-5/48/280-512.png): [![loopy arrow](https://i.stack.imgur.com/nVPdN.png)](https://i.stack.imgur.com/nVPdN.png) **update:** the answer linked to does not show how do this with `plt.annotate` which has other features i want to use. the proposal to use `$\circlearrowleft$` marker is not a real solution.
2016/05/29
[ "https://Stackoverflow.com/questions/37512502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5768196/" ]
Another possibility is to use tikz to generate the figure: ``` \documentclass {minimal} \usepackage {tikz} \begin{document} \usetikzlibrary {arrows} \begin {tikzpicture}[scale=1.8] \draw[-angle 90, line width=5.0mm, rounded corners=20pt] (0.25,0)-- (1.0, 0.0) -- (1.0, -3.0) -- (-3.0, -3.0) -- (-3.0, 0) --(-1,0); \end{tikzpicture} \end{document} ``` This is the result: [![enter image description here](https://i.stack.imgur.com/W3D8l.jpg)](https://i.stack.imgur.com/W3D8l.jpg) there is a pgf/tikz backend in matplotlib that you could generate your matplotlib output to tikz code that pdflatex or lualatex can process. So this way, I think, you could insert seamlessly the looparrow figure in your matplotlib figure. See for ex: <http://matplotlib.org/users/whats_new.html#pgf-tikz-backend>
@Aguy's answer is useful if you want a smooth arc instead of a complete circle. In Aguy's answer an arrow head is drawn line by line, but instead a FancyArrowPatch can be used. This gives a full arrow head, which might be more suitable. Below gives the code with the FancyArrowPatch arrow head. ``` def circarrowdraw(x0, y0, radius=1, aspect=1, direction=270, closingangle=-330, rotate_head = 0.0, color='b', *args): """ Circular arrow drawing. x0 and y0 are the anchor points. direction gives the angle of the circle center relative to the anchor in degrees. closingangle indicates how much of the circle is drawn in degrees with positive being counterclockwise and negative being clockwise. aspect is important to make the aspect of the arrow fit the current figure. rotate_head is used to rotate the arrow head by increasing the y value of the arrow's tail coordinate. """ # Center of circle xc = x0 + radius * np.cos(direction * np.pi / 180) yc = y0 + aspect * radius * np.sin(direction * np.pi / 180) # Draw circle if closingangle < 0: step = -1 else: step = 1 x = [xc + radius * np.cos((ang + 180 + direction) * np.pi / 180) for ang in np.arange(0, closingangle, step)] y = [yc + aspect * radius * np.sin((ang + 180 + direction) * np.pi / 180) for ang in np.arange(0, closingangle, step)] plt.plot(x, y, *args, color=color) # Draw arrow head arc_arrow_head = patches.FancyArrowPatch((x[-1], y[-1] + rotate_head), (x[0], y[0]), arrowstyle="Simple,head_width=10,head_length=10,tail_width=0.01", color = color, zorder = 10) plt.gca().add_patch(arc_arrow_head) ``` To test it: ``` plt.plot([0, 0, 1, 1, 0], [0, 1, 1, 0, 0]) circarrowdraw(1.0, 1.0 , radius=0.1, aspect=0.3, direction=90, closingangle=-345, rotate_head = 0.003) circarrowdraw(0.0, 1.0 , radius=0.1, aspect=1, direction=-90, closingangle=-345, rotate_head = 0.0) circarrowdraw(0.0, 0.0 , radius=0.1, aspect=3.0, direction=90, closingangle=-345, rotate_head = 0.01) circarrowdraw(1.0, 0.0 , radius=0.1, aspect=0.3, direction=-90, closingangle=-345) plt.show() ``` [Picture of image (I don't have a high enough reputation to embed the image in my answer)](https://i.stack.imgur.com/PXEvy.png)
37,512,502
what is the right way to draw an arrow that loops back to point to its origin in matplotlib? i tried: ``` plt.figure() plt.xlim([0, 1]) plt.ylim([0, 1]) plt.annotate("", xy=(0.6, 0.9), xycoords="figure fraction", xytext = (0.6, 0.8), textcoords="figure fraction", fontsize = 10, \ color = "k", arrowprops=dict(edgecolor='black', connectionstyle="angle,angleA=-180,angleB=45", arrowstyle = '<|-', facecolor="k", linewidth=1, shrinkA = 0, shrinkB = 0)) plt.show() ``` this doesn't give the right result: [![arrow](https://i.stack.imgur.com/DfHPl.png)](https://i.stack.imgur.com/DfHPl.png) the `connectionstyle` arguments are hard to follow from this page (<http://matplotlib.org/users/annotations_guide.html>). i'm looking for is something like [this](http://i.istockimg.com/file_thumbview_approve/25282609/6/stock-illustration-25282609-arrow-sign-refresh-reload-loop-rotation-pictogram-black-icon.jpg) or [this](https://cdn0.iconfinder.com/data/icons/arrows-volume-5/48/280-512.png): [![loopy arrow](https://i.stack.imgur.com/nVPdN.png)](https://i.stack.imgur.com/nVPdN.png) **update:** the answer linked to does not show how do this with `plt.annotate` which has other features i want to use. the proposal to use `$\circlearrowleft$` marker is not a real solution.
2016/05/29
[ "https://Stackoverflow.com/questions/37512502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5768196/" ]
I find no way to make a loop using `plt.annotate` only once, but using it four times works : ``` import matplotlib.pyplot as plt fig,ax = plt.subplots() # coordinates of the center of the loop x_center = 0.5 y_center = 0.5 radius = 0.2 # linewidth of the arrow linewidth = 1 ax.annotate("", (x_center + radius, y_center), (x_center, y_center + radius), arrowprops=dict(arrowstyle="-", shrinkA=10, # creates a gap between the start point and end point of the arrow shrinkB=0, linewidth=linewidth, connectionstyle="angle,angleB=-90,angleA=180,rad=10")) ax.annotate("", (x_center, y_center - radius), (x_center + radius, y_center), arrowprops=dict(arrowstyle="-", shrinkA=0, shrinkB=0, linewidth=linewidth, connectionstyle="angle,angleB=180,angleA=-90,rad=10")) ax.annotate("", (x_center - radius, y_center), (x_center, y_center - radius), arrowprops=dict(arrowstyle="-", shrinkA=0, shrinkB=0, linewidth=linewidth, connectionstyle="angle,angleB=-90,angleA=180,rad=10")) ax.annotate("", (x_center, y_center + radius), (x_center - radius, y_center), arrowprops=dict(arrowstyle="-|>", facecolor="k", linewidth=linewidth, shrinkA=0, shrinkB=0, connectionstyle="angle,angleB=180,angleA=-90,rad=10")) plt.show() ``` [![enter image description here](https://i.stack.imgur.com/ZKi97.png)](https://i.stack.imgur.com/ZKi97.png)
Another possibility is to use tikz to generate the figure: ``` \documentclass {minimal} \usepackage {tikz} \begin{document} \usetikzlibrary {arrows} \begin {tikzpicture}[scale=1.8] \draw[-angle 90, line width=5.0mm, rounded corners=20pt] (0.25,0)-- (1.0, 0.0) -- (1.0, -3.0) -- (-3.0, -3.0) -- (-3.0, 0) --(-1,0); \end{tikzpicture} \end{document} ``` This is the result: [![enter image description here](https://i.stack.imgur.com/W3D8l.jpg)](https://i.stack.imgur.com/W3D8l.jpg) there is a pgf/tikz backend in matplotlib that you could generate your matplotlib output to tikz code that pdflatex or lualatex can process. So this way, I think, you could insert seamlessly the looparrow figure in your matplotlib figure. See for ex: <http://matplotlib.org/users/whats_new.html#pgf-tikz-backend>
37,512,502
what is the right way to draw an arrow that loops back to point to its origin in matplotlib? i tried: ``` plt.figure() plt.xlim([0, 1]) plt.ylim([0, 1]) plt.annotate("", xy=(0.6, 0.9), xycoords="figure fraction", xytext = (0.6, 0.8), textcoords="figure fraction", fontsize = 10, \ color = "k", arrowprops=dict(edgecolor='black', connectionstyle="angle,angleA=-180,angleB=45", arrowstyle = '<|-', facecolor="k", linewidth=1, shrinkA = 0, shrinkB = 0)) plt.show() ``` this doesn't give the right result: [![arrow](https://i.stack.imgur.com/DfHPl.png)](https://i.stack.imgur.com/DfHPl.png) the `connectionstyle` arguments are hard to follow from this page (<http://matplotlib.org/users/annotations_guide.html>). i'm looking for is something like [this](http://i.istockimg.com/file_thumbview_approve/25282609/6/stock-illustration-25282609-arrow-sign-refresh-reload-loop-rotation-pictogram-black-icon.jpg) or [this](https://cdn0.iconfinder.com/data/icons/arrows-volume-5/48/280-512.png): [![loopy arrow](https://i.stack.imgur.com/nVPdN.png)](https://i.stack.imgur.com/nVPdN.png) **update:** the answer linked to does not show how do this with `plt.annotate` which has other features i want to use. the proposal to use `$\circlearrowleft$` marker is not a real solution.
2016/05/29
[ "https://Stackoverflow.com/questions/37512502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5768196/" ]
It seems the easiest way to create an easily modifiable looping arrow is to use [patches](http://matplotlib.org/api/patches_api.html). I've pasted code to do this below. Change the variables in the variables section and things should all rotate and scale together. You can play around with the patch that creates the arrow head to make a different shape though I suspect that this triangle will be the easiest one. ``` %matplotlib inline # from __future__ import division #Uncomment for python2.7 import matplotlib.pyplot as plt from matplotlib.patches import Arc, RegularPolygon import numpy as np from numpy import radians as rad fig = plt.figure(figsize=(9,9)) ax = plt.gca() def drawCirc(ax,radius,centX,centY,angle_,theta2_,color_='black'): #========Line arc = Arc([centX,centY],radius,radius,angle=angle_, theta1=0,theta2=theta2_,capstyle='round',linestyle='-',lw=10,color=color_) ax.add_patch(arc) #========Create the arrow head endX=centX+(radius/2)*np.cos(rad(theta2_+angle_)) #Do trig to determine end position endY=centY+(radius/2)*np.sin(rad(theta2_+angle_)) ax.add_patch( #Create triangle as arrow head RegularPolygon( (endX, endY), # (x,y) 3, # number of vertices radius/9, # radius rad(angle_+theta2_), # orientation color=color_ ) ) ax.set_xlim([centX-radius,centY+radius]) and ax.set_ylim([centY-radius,centY+radius]) # Make sure you keep the axes scaled or else arrow will distort drawCirc(ax,1,1,1,0,250) drawCirc(ax,2,1,1,90,330,color_='blue') plt.show() ``` [![enter image description here](https://i.stack.imgur.com/Nvg9M.png)](https://i.stack.imgur.com/Nvg9M.png)
@Aguy's answer is useful if you want a smooth arc instead of a complete circle. In Aguy's answer an arrow head is drawn line by line, but instead a FancyArrowPatch can be used. This gives a full arrow head, which might be more suitable. Below gives the code with the FancyArrowPatch arrow head. ``` def circarrowdraw(x0, y0, radius=1, aspect=1, direction=270, closingangle=-330, rotate_head = 0.0, color='b', *args): """ Circular arrow drawing. x0 and y0 are the anchor points. direction gives the angle of the circle center relative to the anchor in degrees. closingangle indicates how much of the circle is drawn in degrees with positive being counterclockwise and negative being clockwise. aspect is important to make the aspect of the arrow fit the current figure. rotate_head is used to rotate the arrow head by increasing the y value of the arrow's tail coordinate. """ # Center of circle xc = x0 + radius * np.cos(direction * np.pi / 180) yc = y0 + aspect * radius * np.sin(direction * np.pi / 180) # Draw circle if closingangle < 0: step = -1 else: step = 1 x = [xc + radius * np.cos((ang + 180 + direction) * np.pi / 180) for ang in np.arange(0, closingangle, step)] y = [yc + aspect * radius * np.sin((ang + 180 + direction) * np.pi / 180) for ang in np.arange(0, closingangle, step)] plt.plot(x, y, *args, color=color) # Draw arrow head arc_arrow_head = patches.FancyArrowPatch((x[-1], y[-1] + rotate_head), (x[0], y[0]), arrowstyle="Simple,head_width=10,head_length=10,tail_width=0.01", color = color, zorder = 10) plt.gca().add_patch(arc_arrow_head) ``` To test it: ``` plt.plot([0, 0, 1, 1, 0], [0, 1, 1, 0, 0]) circarrowdraw(1.0, 1.0 , radius=0.1, aspect=0.3, direction=90, closingangle=-345, rotate_head = 0.003) circarrowdraw(0.0, 1.0 , radius=0.1, aspect=1, direction=-90, closingangle=-345, rotate_head = 0.0) circarrowdraw(0.0, 0.0 , radius=0.1, aspect=3.0, direction=90, closingangle=-345, rotate_head = 0.01) circarrowdraw(1.0, 0.0 , radius=0.1, aspect=0.3, direction=-90, closingangle=-345) plt.show() ``` [Picture of image (I don't have a high enough reputation to embed the image in my answer)](https://i.stack.imgur.com/PXEvy.png)
37,512,502
what is the right way to draw an arrow that loops back to point to its origin in matplotlib? i tried: ``` plt.figure() plt.xlim([0, 1]) plt.ylim([0, 1]) plt.annotate("", xy=(0.6, 0.9), xycoords="figure fraction", xytext = (0.6, 0.8), textcoords="figure fraction", fontsize = 10, \ color = "k", arrowprops=dict(edgecolor='black', connectionstyle="angle,angleA=-180,angleB=45", arrowstyle = '<|-', facecolor="k", linewidth=1, shrinkA = 0, shrinkB = 0)) plt.show() ``` this doesn't give the right result: [![arrow](https://i.stack.imgur.com/DfHPl.png)](https://i.stack.imgur.com/DfHPl.png) the `connectionstyle` arguments are hard to follow from this page (<http://matplotlib.org/users/annotations_guide.html>). i'm looking for is something like [this](http://i.istockimg.com/file_thumbview_approve/25282609/6/stock-illustration-25282609-arrow-sign-refresh-reload-loop-rotation-pictogram-black-icon.jpg) or [this](https://cdn0.iconfinder.com/data/icons/arrows-volume-5/48/280-512.png): [![loopy arrow](https://i.stack.imgur.com/nVPdN.png)](https://i.stack.imgur.com/nVPdN.png) **update:** the answer linked to does not show how do this with `plt.annotate` which has other features i want to use. the proposal to use `$\circlearrowleft$` marker is not a real solution.
2016/05/29
[ "https://Stackoverflow.com/questions/37512502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5768196/" ]
My suggestion uses just the plot command ``` import matplotlib.pyplot as plt import numpy as np def circarrowdraw(x0, y0, radius=1, aspect=1, direction=270, closingangle=-330, arrowheadrelativesize=0.3, arrowheadopenangle=30, *args): """ Circular arrow drawing. x0 and y0 are the anchor points. direction gives the angle of the circle center relative to the anchor in degrees. closingangle indicates how much of the circle is drawn in degrees with positive being counterclockwise and negative being clockwise. aspect is important to make the aspect of the arrow fit the current figure. """ xc = x0 + radius * np.cos(direction * np.pi / 180) yc = y0 + aspect * radius * np.sin(direction * np.pi / 180) headcorrectionangle = 5 if closingangle < 0: step = -1 else: step = 1 x = [xc + radius * np.cos((ang + 180 + direction) * np.pi / 180) for ang in np.arange(0, closingangle, step)] y = [yc + aspect * radius * np.sin((ang + 180 + direction) * np.pi / 180) for ang in np.arange(0, closingangle, step)] plt.plot(x, y, *args) xlast = x[-1] ylast = y[-1] l = radius * arrowheadrelativesize headangle = (direction + closingangle + (90 - headcorrectionangle) * np.sign(closingangle)) x = [xlast + l * np.cos((headangle + arrowheadopenangle) * np.pi / 180), xlast, xlast + l * np.cos((headangle - arrowheadopenangle) * np.pi / 180)] y = [ylast + aspect * l * np.sin((headangle + arrowheadopenangle) * np.pi / 180), ylast, ylast + aspect * l * np.sin((headangle - arrowheadopenangle) * np.pi / 180)] plt.plot(x, y, *args) ``` To test it: ``` plt.figure() plt.plot(np.arange(10)**2, 'b.') bb = plt.gca().axis() asp = (bb[3] - bb[2]) / (bb[1] - bb[0]) circarrowdraw(6, 36 , radius=0.4, aspect=asp, direction=90) plt.grid() plt.show() ``` [![enter image description here](https://i.stack.imgur.com/xFGmR.png)](https://i.stack.imgur.com/xFGmR.png)
@Aguy's answer is useful if you want a smooth arc instead of a complete circle. In Aguy's answer an arrow head is drawn line by line, but instead a FancyArrowPatch can be used. This gives a full arrow head, which might be more suitable. Below gives the code with the FancyArrowPatch arrow head. ``` def circarrowdraw(x0, y0, radius=1, aspect=1, direction=270, closingangle=-330, rotate_head = 0.0, color='b', *args): """ Circular arrow drawing. x0 and y0 are the anchor points. direction gives the angle of the circle center relative to the anchor in degrees. closingangle indicates how much of the circle is drawn in degrees with positive being counterclockwise and negative being clockwise. aspect is important to make the aspect of the arrow fit the current figure. rotate_head is used to rotate the arrow head by increasing the y value of the arrow's tail coordinate. """ # Center of circle xc = x0 + radius * np.cos(direction * np.pi / 180) yc = y0 + aspect * radius * np.sin(direction * np.pi / 180) # Draw circle if closingangle < 0: step = -1 else: step = 1 x = [xc + radius * np.cos((ang + 180 + direction) * np.pi / 180) for ang in np.arange(0, closingangle, step)] y = [yc + aspect * radius * np.sin((ang + 180 + direction) * np.pi / 180) for ang in np.arange(0, closingangle, step)] plt.plot(x, y, *args, color=color) # Draw arrow head arc_arrow_head = patches.FancyArrowPatch((x[-1], y[-1] + rotate_head), (x[0], y[0]), arrowstyle="Simple,head_width=10,head_length=10,tail_width=0.01", color = color, zorder = 10) plt.gca().add_patch(arc_arrow_head) ``` To test it: ``` plt.plot([0, 0, 1, 1, 0], [0, 1, 1, 0, 0]) circarrowdraw(1.0, 1.0 , radius=0.1, aspect=0.3, direction=90, closingangle=-345, rotate_head = 0.003) circarrowdraw(0.0, 1.0 , radius=0.1, aspect=1, direction=-90, closingangle=-345, rotate_head = 0.0) circarrowdraw(0.0, 0.0 , radius=0.1, aspect=3.0, direction=90, closingangle=-345, rotate_head = 0.01) circarrowdraw(1.0, 0.0 , radius=0.1, aspect=0.3, direction=-90, closingangle=-345) plt.show() ``` [Picture of image (I don't have a high enough reputation to embed the image in my answer)](https://i.stack.imgur.com/PXEvy.png)
37,512,502
what is the right way to draw an arrow that loops back to point to its origin in matplotlib? i tried: ``` plt.figure() plt.xlim([0, 1]) plt.ylim([0, 1]) plt.annotate("", xy=(0.6, 0.9), xycoords="figure fraction", xytext = (0.6, 0.8), textcoords="figure fraction", fontsize = 10, \ color = "k", arrowprops=dict(edgecolor='black', connectionstyle="angle,angleA=-180,angleB=45", arrowstyle = '<|-', facecolor="k", linewidth=1, shrinkA = 0, shrinkB = 0)) plt.show() ``` this doesn't give the right result: [![arrow](https://i.stack.imgur.com/DfHPl.png)](https://i.stack.imgur.com/DfHPl.png) the `connectionstyle` arguments are hard to follow from this page (<http://matplotlib.org/users/annotations_guide.html>). i'm looking for is something like [this](http://i.istockimg.com/file_thumbview_approve/25282609/6/stock-illustration-25282609-arrow-sign-refresh-reload-loop-rotation-pictogram-black-icon.jpg) or [this](https://cdn0.iconfinder.com/data/icons/arrows-volume-5/48/280-512.png): [![loopy arrow](https://i.stack.imgur.com/nVPdN.png)](https://i.stack.imgur.com/nVPdN.png) **update:** the answer linked to does not show how do this with `plt.annotate` which has other features i want to use. the proposal to use `$\circlearrowleft$` marker is not a real solution.
2016/05/29
[ "https://Stackoverflow.com/questions/37512502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5768196/" ]
I find no way to make a loop using `plt.annotate` only once, but using it four times works : ``` import matplotlib.pyplot as plt fig,ax = plt.subplots() # coordinates of the center of the loop x_center = 0.5 y_center = 0.5 radius = 0.2 # linewidth of the arrow linewidth = 1 ax.annotate("", (x_center + radius, y_center), (x_center, y_center + radius), arrowprops=dict(arrowstyle="-", shrinkA=10, # creates a gap between the start point and end point of the arrow shrinkB=0, linewidth=linewidth, connectionstyle="angle,angleB=-90,angleA=180,rad=10")) ax.annotate("", (x_center, y_center - radius), (x_center + radius, y_center), arrowprops=dict(arrowstyle="-", shrinkA=0, shrinkB=0, linewidth=linewidth, connectionstyle="angle,angleB=180,angleA=-90,rad=10")) ax.annotate("", (x_center - radius, y_center), (x_center, y_center - radius), arrowprops=dict(arrowstyle="-", shrinkA=0, shrinkB=0, linewidth=linewidth, connectionstyle="angle,angleB=-90,angleA=180,rad=10")) ax.annotate("", (x_center, y_center + radius), (x_center - radius, y_center), arrowprops=dict(arrowstyle="-|>", facecolor="k", linewidth=linewidth, shrinkA=0, shrinkB=0, connectionstyle="angle,angleB=180,angleA=-90,rad=10")) plt.show() ``` [![enter image description here](https://i.stack.imgur.com/ZKi97.png)](https://i.stack.imgur.com/ZKi97.png)
Try this: ``` import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.set_xlim(1,3) ax.set_ylim(1,3) ax.plot([2.5],[2.5],marker=r'$\circlearrowleft$',ms=100) plt.show() ``` [![enter image description here](https://i.stack.imgur.com/kyNYr.png)](https://i.stack.imgur.com/kyNYr.png)
37,512,502
what is the right way to draw an arrow that loops back to point to its origin in matplotlib? i tried: ``` plt.figure() plt.xlim([0, 1]) plt.ylim([0, 1]) plt.annotate("", xy=(0.6, 0.9), xycoords="figure fraction", xytext = (0.6, 0.8), textcoords="figure fraction", fontsize = 10, \ color = "k", arrowprops=dict(edgecolor='black', connectionstyle="angle,angleA=-180,angleB=45", arrowstyle = '<|-', facecolor="k", linewidth=1, shrinkA = 0, shrinkB = 0)) plt.show() ``` this doesn't give the right result: [![arrow](https://i.stack.imgur.com/DfHPl.png)](https://i.stack.imgur.com/DfHPl.png) the `connectionstyle` arguments are hard to follow from this page (<http://matplotlib.org/users/annotations_guide.html>). i'm looking for is something like [this](http://i.istockimg.com/file_thumbview_approve/25282609/6/stock-illustration-25282609-arrow-sign-refresh-reload-loop-rotation-pictogram-black-icon.jpg) or [this](https://cdn0.iconfinder.com/data/icons/arrows-volume-5/48/280-512.png): [![loopy arrow](https://i.stack.imgur.com/nVPdN.png)](https://i.stack.imgur.com/nVPdN.png) **update:** the answer linked to does not show how do this with `plt.annotate` which has other features i want to use. the proposal to use `$\circlearrowleft$` marker is not a real solution.
2016/05/29
[ "https://Stackoverflow.com/questions/37512502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5768196/" ]
I find no way to make a loop using `plt.annotate` only once, but using it four times works : ``` import matplotlib.pyplot as plt fig,ax = plt.subplots() # coordinates of the center of the loop x_center = 0.5 y_center = 0.5 radius = 0.2 # linewidth of the arrow linewidth = 1 ax.annotate("", (x_center + radius, y_center), (x_center, y_center + radius), arrowprops=dict(arrowstyle="-", shrinkA=10, # creates a gap between the start point and end point of the arrow shrinkB=0, linewidth=linewidth, connectionstyle="angle,angleB=-90,angleA=180,rad=10")) ax.annotate("", (x_center, y_center - radius), (x_center + radius, y_center), arrowprops=dict(arrowstyle="-", shrinkA=0, shrinkB=0, linewidth=linewidth, connectionstyle="angle,angleB=180,angleA=-90,rad=10")) ax.annotate("", (x_center - radius, y_center), (x_center, y_center - radius), arrowprops=dict(arrowstyle="-", shrinkA=0, shrinkB=0, linewidth=linewidth, connectionstyle="angle,angleB=-90,angleA=180,rad=10")) ax.annotate("", (x_center, y_center + radius), (x_center - radius, y_center), arrowprops=dict(arrowstyle="-|>", facecolor="k", linewidth=linewidth, shrinkA=0, shrinkB=0, connectionstyle="angle,angleB=180,angleA=-90,rad=10")) plt.show() ``` [![enter image description here](https://i.stack.imgur.com/ZKi97.png)](https://i.stack.imgur.com/ZKi97.png)
My suggestion uses just the plot command ``` import matplotlib.pyplot as plt import numpy as np def circarrowdraw(x0, y0, radius=1, aspect=1, direction=270, closingangle=-330, arrowheadrelativesize=0.3, arrowheadopenangle=30, *args): """ Circular arrow drawing. x0 and y0 are the anchor points. direction gives the angle of the circle center relative to the anchor in degrees. closingangle indicates how much of the circle is drawn in degrees with positive being counterclockwise and negative being clockwise. aspect is important to make the aspect of the arrow fit the current figure. """ xc = x0 + radius * np.cos(direction * np.pi / 180) yc = y0 + aspect * radius * np.sin(direction * np.pi / 180) headcorrectionangle = 5 if closingangle < 0: step = -1 else: step = 1 x = [xc + radius * np.cos((ang + 180 + direction) * np.pi / 180) for ang in np.arange(0, closingangle, step)] y = [yc + aspect * radius * np.sin((ang + 180 + direction) * np.pi / 180) for ang in np.arange(0, closingangle, step)] plt.plot(x, y, *args) xlast = x[-1] ylast = y[-1] l = radius * arrowheadrelativesize headangle = (direction + closingangle + (90 - headcorrectionangle) * np.sign(closingangle)) x = [xlast + l * np.cos((headangle + arrowheadopenangle) * np.pi / 180), xlast, xlast + l * np.cos((headangle - arrowheadopenangle) * np.pi / 180)] y = [ylast + aspect * l * np.sin((headangle + arrowheadopenangle) * np.pi / 180), ylast, ylast + aspect * l * np.sin((headangle - arrowheadopenangle) * np.pi / 180)] plt.plot(x, y, *args) ``` To test it: ``` plt.figure() plt.plot(np.arange(10)**2, 'b.') bb = plt.gca().axis() asp = (bb[3] - bb[2]) / (bb[1] - bb[0]) circarrowdraw(6, 36 , radius=0.4, aspect=asp, direction=90) plt.grid() plt.show() ``` [![enter image description here](https://i.stack.imgur.com/xFGmR.png)](https://i.stack.imgur.com/xFGmR.png)
37,512,502
what is the right way to draw an arrow that loops back to point to its origin in matplotlib? i tried: ``` plt.figure() plt.xlim([0, 1]) plt.ylim([0, 1]) plt.annotate("", xy=(0.6, 0.9), xycoords="figure fraction", xytext = (0.6, 0.8), textcoords="figure fraction", fontsize = 10, \ color = "k", arrowprops=dict(edgecolor='black', connectionstyle="angle,angleA=-180,angleB=45", arrowstyle = '<|-', facecolor="k", linewidth=1, shrinkA = 0, shrinkB = 0)) plt.show() ``` this doesn't give the right result: [![arrow](https://i.stack.imgur.com/DfHPl.png)](https://i.stack.imgur.com/DfHPl.png) the `connectionstyle` arguments are hard to follow from this page (<http://matplotlib.org/users/annotations_guide.html>). i'm looking for is something like [this](http://i.istockimg.com/file_thumbview_approve/25282609/6/stock-illustration-25282609-arrow-sign-refresh-reload-loop-rotation-pictogram-black-icon.jpg) or [this](https://cdn0.iconfinder.com/data/icons/arrows-volume-5/48/280-512.png): [![loopy arrow](https://i.stack.imgur.com/nVPdN.png)](https://i.stack.imgur.com/nVPdN.png) **update:** the answer linked to does not show how do this with `plt.annotate` which has other features i want to use. the proposal to use `$\circlearrowleft$` marker is not a real solution.
2016/05/29
[ "https://Stackoverflow.com/questions/37512502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5768196/" ]
I find no way to make a loop using `plt.annotate` only once, but using it four times works : ``` import matplotlib.pyplot as plt fig,ax = plt.subplots() # coordinates of the center of the loop x_center = 0.5 y_center = 0.5 radius = 0.2 # linewidth of the arrow linewidth = 1 ax.annotate("", (x_center + radius, y_center), (x_center, y_center + radius), arrowprops=dict(arrowstyle="-", shrinkA=10, # creates a gap between the start point and end point of the arrow shrinkB=0, linewidth=linewidth, connectionstyle="angle,angleB=-90,angleA=180,rad=10")) ax.annotate("", (x_center, y_center - radius), (x_center + radius, y_center), arrowprops=dict(arrowstyle="-", shrinkA=0, shrinkB=0, linewidth=linewidth, connectionstyle="angle,angleB=180,angleA=-90,rad=10")) ax.annotate("", (x_center - radius, y_center), (x_center, y_center - radius), arrowprops=dict(arrowstyle="-", shrinkA=0, shrinkB=0, linewidth=linewidth, connectionstyle="angle,angleB=-90,angleA=180,rad=10")) ax.annotate("", (x_center, y_center + radius), (x_center - radius, y_center), arrowprops=dict(arrowstyle="-|>", facecolor="k", linewidth=linewidth, shrinkA=0, shrinkB=0, connectionstyle="angle,angleB=180,angleA=-90,rad=10")) plt.show() ``` [![enter image description here](https://i.stack.imgur.com/ZKi97.png)](https://i.stack.imgur.com/ZKi97.png)
@Aguy's answer is useful if you want a smooth arc instead of a complete circle. In Aguy's answer an arrow head is drawn line by line, but instead a FancyArrowPatch can be used. This gives a full arrow head, which might be more suitable. Below gives the code with the FancyArrowPatch arrow head. ``` def circarrowdraw(x0, y0, radius=1, aspect=1, direction=270, closingangle=-330, rotate_head = 0.0, color='b', *args): """ Circular arrow drawing. x0 and y0 are the anchor points. direction gives the angle of the circle center relative to the anchor in degrees. closingangle indicates how much of the circle is drawn in degrees with positive being counterclockwise and negative being clockwise. aspect is important to make the aspect of the arrow fit the current figure. rotate_head is used to rotate the arrow head by increasing the y value of the arrow's tail coordinate. """ # Center of circle xc = x0 + radius * np.cos(direction * np.pi / 180) yc = y0 + aspect * radius * np.sin(direction * np.pi / 180) # Draw circle if closingangle < 0: step = -1 else: step = 1 x = [xc + radius * np.cos((ang + 180 + direction) * np.pi / 180) for ang in np.arange(0, closingangle, step)] y = [yc + aspect * radius * np.sin((ang + 180 + direction) * np.pi / 180) for ang in np.arange(0, closingangle, step)] plt.plot(x, y, *args, color=color) # Draw arrow head arc_arrow_head = patches.FancyArrowPatch((x[-1], y[-1] + rotate_head), (x[0], y[0]), arrowstyle="Simple,head_width=10,head_length=10,tail_width=0.01", color = color, zorder = 10) plt.gca().add_patch(arc_arrow_head) ``` To test it: ``` plt.plot([0, 0, 1, 1, 0], [0, 1, 1, 0, 0]) circarrowdraw(1.0, 1.0 , radius=0.1, aspect=0.3, direction=90, closingangle=-345, rotate_head = 0.003) circarrowdraw(0.0, 1.0 , radius=0.1, aspect=1, direction=-90, closingangle=-345, rotate_head = 0.0) circarrowdraw(0.0, 0.0 , radius=0.1, aspect=3.0, direction=90, closingangle=-345, rotate_head = 0.01) circarrowdraw(1.0, 0.0 , radius=0.1, aspect=0.3, direction=-90, closingangle=-345) plt.show() ``` [Picture of image (I don't have a high enough reputation to embed the image in my answer)](https://i.stack.imgur.com/PXEvy.png)
37,512,502
what is the right way to draw an arrow that loops back to point to its origin in matplotlib? i tried: ``` plt.figure() plt.xlim([0, 1]) plt.ylim([0, 1]) plt.annotate("", xy=(0.6, 0.9), xycoords="figure fraction", xytext = (0.6, 0.8), textcoords="figure fraction", fontsize = 10, \ color = "k", arrowprops=dict(edgecolor='black', connectionstyle="angle,angleA=-180,angleB=45", arrowstyle = '<|-', facecolor="k", linewidth=1, shrinkA = 0, shrinkB = 0)) plt.show() ``` this doesn't give the right result: [![arrow](https://i.stack.imgur.com/DfHPl.png)](https://i.stack.imgur.com/DfHPl.png) the `connectionstyle` arguments are hard to follow from this page (<http://matplotlib.org/users/annotations_guide.html>). i'm looking for is something like [this](http://i.istockimg.com/file_thumbview_approve/25282609/6/stock-illustration-25282609-arrow-sign-refresh-reload-loop-rotation-pictogram-black-icon.jpg) or [this](https://cdn0.iconfinder.com/data/icons/arrows-volume-5/48/280-512.png): [![loopy arrow](https://i.stack.imgur.com/nVPdN.png)](https://i.stack.imgur.com/nVPdN.png) **update:** the answer linked to does not show how do this with `plt.annotate` which has other features i want to use. the proposal to use `$\circlearrowleft$` marker is not a real solution.
2016/05/29
[ "https://Stackoverflow.com/questions/37512502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5768196/" ]
It seems the easiest way to create an easily modifiable looping arrow is to use [patches](http://matplotlib.org/api/patches_api.html). I've pasted code to do this below. Change the variables in the variables section and things should all rotate and scale together. You can play around with the patch that creates the arrow head to make a different shape though I suspect that this triangle will be the easiest one. ``` %matplotlib inline # from __future__ import division #Uncomment for python2.7 import matplotlib.pyplot as plt from matplotlib.patches import Arc, RegularPolygon import numpy as np from numpy import radians as rad fig = plt.figure(figsize=(9,9)) ax = plt.gca() def drawCirc(ax,radius,centX,centY,angle_,theta2_,color_='black'): #========Line arc = Arc([centX,centY],radius,radius,angle=angle_, theta1=0,theta2=theta2_,capstyle='round',linestyle='-',lw=10,color=color_) ax.add_patch(arc) #========Create the arrow head endX=centX+(radius/2)*np.cos(rad(theta2_+angle_)) #Do trig to determine end position endY=centY+(radius/2)*np.sin(rad(theta2_+angle_)) ax.add_patch( #Create triangle as arrow head RegularPolygon( (endX, endY), # (x,y) 3, # number of vertices radius/9, # radius rad(angle_+theta2_), # orientation color=color_ ) ) ax.set_xlim([centX-radius,centY+radius]) and ax.set_ylim([centY-radius,centY+radius]) # Make sure you keep the axes scaled or else arrow will distort drawCirc(ax,1,1,1,0,250) drawCirc(ax,2,1,1,90,330,color_='blue') plt.show() ``` [![enter image description here](https://i.stack.imgur.com/Nvg9M.png)](https://i.stack.imgur.com/Nvg9M.png)
My suggestion uses just the plot command ``` import matplotlib.pyplot as plt import numpy as np def circarrowdraw(x0, y0, radius=1, aspect=1, direction=270, closingangle=-330, arrowheadrelativesize=0.3, arrowheadopenangle=30, *args): """ Circular arrow drawing. x0 and y0 are the anchor points. direction gives the angle of the circle center relative to the anchor in degrees. closingangle indicates how much of the circle is drawn in degrees with positive being counterclockwise and negative being clockwise. aspect is important to make the aspect of the arrow fit the current figure. """ xc = x0 + radius * np.cos(direction * np.pi / 180) yc = y0 + aspect * radius * np.sin(direction * np.pi / 180) headcorrectionangle = 5 if closingangle < 0: step = -1 else: step = 1 x = [xc + radius * np.cos((ang + 180 + direction) * np.pi / 180) for ang in np.arange(0, closingangle, step)] y = [yc + aspect * radius * np.sin((ang + 180 + direction) * np.pi / 180) for ang in np.arange(0, closingangle, step)] plt.plot(x, y, *args) xlast = x[-1] ylast = y[-1] l = radius * arrowheadrelativesize headangle = (direction + closingangle + (90 - headcorrectionangle) * np.sign(closingangle)) x = [xlast + l * np.cos((headangle + arrowheadopenangle) * np.pi / 180), xlast, xlast + l * np.cos((headangle - arrowheadopenangle) * np.pi / 180)] y = [ylast + aspect * l * np.sin((headangle + arrowheadopenangle) * np.pi / 180), ylast, ylast + aspect * l * np.sin((headangle - arrowheadopenangle) * np.pi / 180)] plt.plot(x, y, *args) ``` To test it: ``` plt.figure() plt.plot(np.arange(10)**2, 'b.') bb = plt.gca().axis() asp = (bb[3] - bb[2]) / (bb[1] - bb[0]) circarrowdraw(6, 36 , radius=0.4, aspect=asp, direction=90) plt.grid() plt.show() ``` [![enter image description here](https://i.stack.imgur.com/xFGmR.png)](https://i.stack.imgur.com/xFGmR.png)
40,401,192
I have a multidimensional which is a dynamic array like : ``` Array ( [0] => Array ( [key] => delete [label] => hi Delete ) [1] => Array ( [key] => edit [label] => hi Edit ) [2] => Array ( [key] => update [label] => hi update ) ) ``` now i want to delete an array below from above multidimensional array: ``` Array ( [key] => delete [label] => hi Delete ) ``` finally i want an output like: Array ( ``` [0] => Array ( [key] => edit [label] => hi Edit ) [1] => Array ( [key] => update [label] => hi update ) ) ``` For this i have tried, below is my code: ``` <?php $arr1 = array(array("key" => "delete", "label" => "hi Delete"),array("key" => "edit", "label" => "hi Edit"), array("key" => "update", "label" => "hi update")); $diff = array_diff_assoc($arr1, array("key" => "delete", "label" => "hi Delete")); print_r($diff); ?> ``` But i get full $arr1 in the output: ``` Array ( [0] => Array ( [key] => delete [label] => hi Delete ) [1] => Array ( [key] => edit [label] => hi Edit ) [2] => Array ( [key] => update [label] => hi update ) ) ``` how can i do this please help me
2016/11/03
[ "https://Stackoverflow.com/questions/40401192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5908629/" ]
Use [**array\_filter**](http://php.net/manual/en/function.array-filter.php) with `callback` as ``` $arr1 = array_filter($arr1, function ($var) { return $var['key'] != 'delete'; }); print_r($arr1); ```
You should loop through the array and test for the key you want to remove, like so: (written blind so youll need to test it!) ``` <?php foreach ($arr1 as $thisArrIndex=>$subArray) { if ( $subArray['key'] == "delete" ) { unset($arr1[$thisArrIndex]); } } ?> ``` Suggested edit was to break out of the loop after finding the key. It seems OP may have multiple keys like this (in the multiple sub arrays) and so i chose not to break out of the loop here.
57,070,610
I've got a working setup for a GraphQL API (Spring Boot 2, GraphQL Spring Boot Starter, GraphiQL). Then I tried to introduce a custom scalar provided by the library *graphql-java-extended-scalars* (in this case the *DateScalar* for a member with the type *java.time.LocalDate*): I declared the custom scalar and the type in the schema, ``` scalar Date ... somedate: Date ... ``` I provided `GraphQLScalarType` as a Spring Bean (otherwise the server wouldn't start up): ```java @Bean public GraphQLScalarType date() { return ExtendedScalars.Date; } ``` I executed a mutation query with a *Date*. ```js mutation { createSomething( something:{ ... somedate: "2018-07-20", ... } ) } ``` But unfortunately I get this exception, ``` com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDate` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator) ``` After some hours of research, I have no idea what could be wrong. It seems that the Scalar was not picked up despite provided in the configuration. The `GraphQLInputType` looks like this, ```java @Data public class Something implements GraphQLInputType { ... private LocalDate somedate; ... @Override public String getName() { return "Something"; } } ```
2019/07/17
[ "https://Stackoverflow.com/questions/57070610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9960510/" ]
I think after providing SchemaParserOptions with a adjusted configuration of mapper it works: ``` @Bean public SchemaParserOptions schemaParserOptions(){ return SchemaParserOptions.newOptions().objectMapperConfigurer((mapper, context) -> { mapper.registerModule(new JavaTimeModule()); }).build(); } ``` GraphQL uses its own objectmapper, therefore you have to register the JavaTimeModule on it.
The problem is that the class where you want to deserialize the object it doesn't have a public default constructor.
57,759
In the documentation page for my team's product, there are some articles under the same header that are fairly friendly but some that are definitely not for beginners. My employer wants something that doesn't need to be clicked to show the difference between a normal or advanced article. I was considering a hover pop-up, but then that means the user can't take in the links and immediately tell what's advanced or not. Another option is to place the words "Advanced" (kind of like an icon) right in front of the icons. Another issue to contend with is that everyone who visits this documentation page is a software developer of some sort, so is it even necessary to differentiate between the different types of articles?
2014/05/22
[ "https://ux.stackexchange.com/questions/57759", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/38193/" ]
You could take a search engine approach, when you search for something in a search engine it displays links on the next page with **little snippets of information directly below the link** describing what the link is more in depth. These snippets could have an icon that represents **advanced or normal**. This helps to determine if it is exactly what you are looking for or not. This would remove the need for the pop-up and simplify the page overall. As you also stated all of the people visiting the website will already be software developers so you may not even need the icon to differentiate between advanced and normal, but rather just the snippet of information below to help them browse the information more quickly and find what they need.
I think its hard to tell if the differentiation is neccessary from your information. But if it needs to be "marked" I would expect some sort of "Advanced" keyword or an icon that visualizes the advanced category. The text itself is easier to understand than an icon though... If you pick the keyword approach, I would just mark the advanced content and not writing "normal" in front of all others.
57,759
In the documentation page for my team's product, there are some articles under the same header that are fairly friendly but some that are definitely not for beginners. My employer wants something that doesn't need to be clicked to show the difference between a normal or advanced article. I was considering a hover pop-up, but then that means the user can't take in the links and immediately tell what's advanced or not. Another option is to place the words "Advanced" (kind of like an icon) right in front of the icons. Another issue to contend with is that everyone who visits this documentation page is a software developer of some sort, so is it even necessary to differentiate between the different types of articles?
2014/05/22
[ "https://ux.stackexchange.com/questions/57759", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/38193/" ]
You could take a search engine approach, when you search for something in a search engine it displays links on the next page with **little snippets of information directly below the link** describing what the link is more in depth. These snippets could have an icon that represents **advanced or normal**. This helps to determine if it is exactly what you are looking for or not. This would remove the need for the pop-up and simplify the page overall. As you also stated all of the people visiting the website will already be software developers so you may not even need the icon to differentiate between advanced and normal, but rather just the snippet of information below to help them browse the information more quickly and find what they need.
If there are very high differences in level of skill (understanding) for various content, I would propose using labels as "Beginner", "Intermediate", "Advanced". You may also use only "Advanced" as suggested earlier, if there are only two levels of difficulty. The fewer the better generally. I would refrain from using icons (without text label) as in my experience there are no metaphors clear enough for this. To make the content more accessible, I would suggest breaking it into sections based on the difficulty level with beginner level first. In similar way, documentation is often beginning with "Getting started" guide and than come more advanced topics.
23,371,144
I am using a javascript function that calls another javascript function (zConvertEmplidtoRowid) that uses an ajax call that runs a query to return data in a variable (rowid). My problem is I don't know how to return the data to the original function. Here is a snippet of the original function calling the ajax function (zConvertEmplidtoRowid) ``` var rowid = zConvertEmplidtoRowid(emplid); //the alert should show what the query via ajax returned alert(rowid); zEmployeePortrait(emplid, ajaxlink); } ``` And here is the ajax function...I imagine somewhere in here I need to place the return, but I've never used ajax before, so I'm not sure. ``` function zConvertEmplidtoRowid(emplid, ajaxlink, callback) { if (typeof XMLHttpRequest == 'undefined') { XMLHttpRequest = function() { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} throw new Error('This browser does not support XMLHttpRequest or XMLHTTP.'); }; } var request = new XMLHttpRequest(); request.onreadystatechange = function() { if (request.readyState == 4 && request.status == 200) { var rowid = request.responseText; callback(rowid); } } var ajax_link = ajax_link + "?emplid=" + emplid; request.open('GET', ajax_link); request.send(); } ```
2014/04/29
[ "https://Stackoverflow.com/questions/23371144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3586248/" ]
As @epascarello pointed out, the ajax call is asynchronous and the code you have written is expecting the call to return in a synchronous way. You have two options: 1) Make the ajax call synchronous (I highly recommend not to take this route). 2) Pass a callback function as a parameter to the function making the ajax call and then invoke the callback function once the call returns. e.g: ``` function zConvertEmplidtoRowid(emplid, ajaxlink, callback) { //Added a callback function parameter if (typeof XMLHttpRequest == 'undefined') { XMLHttpRequest = function() { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} throw new Error('This browser does not support XMLHttpRequest or XMLHTTP.'); }; } var request = new XMLHttpRequest(); request.onreadystatechange = function() { if (request.readyState == 4 && request.status == 200) { var rowid = request.responseText; //now you invoke the callback passing the rowid as argument callback(rowid); } } var ajax_link = ajax_link + "?emplid=" + emplid; request.open('GET', ajax_link); request.send(); } zConvertEmplidtoRowid(emplid, ajaxlink, function(rowId) { alert(rowId); zEmployeePortrait(emplid, ajaxlink); }); ```
As epascarello has implied in his comment, you need to make the javascript call synchronously in order to get a return value... I tend to use jquery to assist with the call, but a quick google suggests you can do it your way by changing: request.open('GET', ajax\_link); to: request.open('GET', ajax\_link, false); and the response is then accessible through: request.responseText taken from here: <https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests>
25,059,200
Here is the block of code: ``` {{ Form::open() }} <input type="number" name="part_number" placeholder="Part Number" /> <input type="number" name="quantity" placeholder="Quantity" /> <input type="number" name="annual_usage" placeholder="Annual Usage" /> <input type="submit" value="Add Part" /> {{ Form::close() }} ``` I want to make it so the user can add multiple parts but currently I can only add one. Should I be using a loop or something?
2014/07/31
[ "https://Stackoverflow.com/questions/25059200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3892458/" ]
You can use this syntax: ``` @for ($i = 0; $i < 10; $i++) {{-- form goes here --}} @endfor ``` See the [Blade documentation](http://laravel.com/docs/templates) for more info.
No matter what is in the form, I would suggest you take a look at [Hogan.js](http://twitter.github.io/hogan.js/). This is a neat little templating engine which works with [mustache](http://mustache.github.io/). The latter allows you to write code like this: ``` {{#list_items}} // code repeated for each list item {{/list_items}} {{^list_items}} // code to be executed if there are no list items {{/list_items}} ```
244,865
I'm trying to install a floppy drive in my new desktop. I don't know much about IDE connections/cables but it seems there are multiple types. I've seen some with pins in the middle taken out and others with all their pins. I think I have a newer version of IDE on my motherboard. *Do they sell these newer cables with 3.5" drive connections?*
2011/02/12
[ "https://superuser.com/questions/244865", "https://superuser.com", "https://superuser.com/users/35203/" ]
Floppy drives don't use a normal IDE (PATA) connection; they use a special 34-pin connector. If your motherboard does not have this connector then you'll need to get a USB floppy drive instead.
Floppy drives are not IDE - IDE is a 40 pin connector - Floppy drives use a 34 pin connector. It's possibly your motherboard doesn't have the 34 pin connector since most people no longer use floppy drives. If you get the correct floppy cable it should clearly and easily match up with the connector on the motherboard, assuming the motherboard has one. Otherwise, try using a USB based floppy drive.
244,865
I'm trying to install a floppy drive in my new desktop. I don't know much about IDE connections/cables but it seems there are multiple types. I've seen some with pins in the middle taken out and others with all their pins. I think I have a newer version of IDE on my motherboard. *Do they sell these newer cables with 3.5" drive connections?*
2011/02/12
[ "https://superuser.com/questions/244865", "https://superuser.com", "https://superuser.com/users/35203/" ]
Floppy drives don't use a normal IDE (PATA) connection; they use a special 34-pin connector. If your motherboard does not have this connector then you'll need to get a USB floppy drive instead.
Get a USB floppy. It will be the quickest and simplest way to go. Unless you're looking for the aesthetic value, and then you need to look for the floppy drive connector on your motherboard. You should look in your system BIOS for a floppy controller option - that's one clue if your system supports it. Another one is to look in Device Manager in Windows, or the kernel messages Linux.
244,865
I'm trying to install a floppy drive in my new desktop. I don't know much about IDE connections/cables but it seems there are multiple types. I've seen some with pins in the middle taken out and others with all their pins. I think I have a newer version of IDE on my motherboard. *Do they sell these newer cables with 3.5" drive connections?*
2011/02/12
[ "https://superuser.com/questions/244865", "https://superuser.com", "https://superuser.com/users/35203/" ]
Floppy drives don't use a normal IDE (PATA) connection; they use a special 34-pin connector. If your motherboard does not have this connector then you'll need to get a USB floppy drive instead.
you could also install a floppy controller card if you have the available space in your desktop. that would provide the 34-pin connector you need to attach the drive
244,865
I'm trying to install a floppy drive in my new desktop. I don't know much about IDE connections/cables but it seems there are multiple types. I've seen some with pins in the middle taken out and others with all their pins. I think I have a newer version of IDE on my motherboard. *Do they sell these newer cables with 3.5" drive connections?*
2011/02/12
[ "https://superuser.com/questions/244865", "https://superuser.com", "https://superuser.com/users/35203/" ]
Floppy drives don't use a normal IDE (PATA) connection; they use a special 34-pin connector. If your motherboard does not have this connector then you'll need to get a USB floppy drive instead.
I have just received this 34pin floppy connector to USB adapter cable from : <http://www.ebay.com.au/itm/like/291258378696?limghlpsr=true&hlpv=2&ops=true&viphx=1&hlpht=true&lpid=107> Even though my country was not on the list they posted to a polite query via Ebay solved that problem. My SAMSUNG 1.44 floppy with four port SD card combo now works perferctly again with the floppy as disk A as in the past. I found I can either power the floppy via a molex floppy power connector or use the USB power via the extra floppy power cable supplied. Although the post took two weeks the supplier posted immediately the PayPal payment went thru.
244,865
I'm trying to install a floppy drive in my new desktop. I don't know much about IDE connections/cables but it seems there are multiple types. I've seen some with pins in the middle taken out and others with all their pins. I think I have a newer version of IDE on my motherboard. *Do they sell these newer cables with 3.5" drive connections?*
2011/02/12
[ "https://superuser.com/questions/244865", "https://superuser.com", "https://superuser.com/users/35203/" ]
Floppy drives are not IDE - IDE is a 40 pin connector - Floppy drives use a 34 pin connector. It's possibly your motherboard doesn't have the 34 pin connector since most people no longer use floppy drives. If you get the correct floppy cable it should clearly and easily match up with the connector on the motherboard, assuming the motherboard has one. Otherwise, try using a USB based floppy drive.
you could also install a floppy controller card if you have the available space in your desktop. that would provide the 34-pin connector you need to attach the drive
244,865
I'm trying to install a floppy drive in my new desktop. I don't know much about IDE connections/cables but it seems there are multiple types. I've seen some with pins in the middle taken out and others with all their pins. I think I have a newer version of IDE on my motherboard. *Do they sell these newer cables with 3.5" drive connections?*
2011/02/12
[ "https://superuser.com/questions/244865", "https://superuser.com", "https://superuser.com/users/35203/" ]
I have just received this 34pin floppy connector to USB adapter cable from : <http://www.ebay.com.au/itm/like/291258378696?limghlpsr=true&hlpv=2&ops=true&viphx=1&hlpht=true&lpid=107> Even though my country was not on the list they posted to a polite query via Ebay solved that problem. My SAMSUNG 1.44 floppy with four port SD card combo now works perferctly again with the floppy as disk A as in the past. I found I can either power the floppy via a molex floppy power connector or use the USB power via the extra floppy power cable supplied. Although the post took two weeks the supplier posted immediately the PayPal payment went thru.
Floppy drives are not IDE - IDE is a 40 pin connector - Floppy drives use a 34 pin connector. It's possibly your motherboard doesn't have the 34 pin connector since most people no longer use floppy drives. If you get the correct floppy cable it should clearly and easily match up with the connector on the motherboard, assuming the motherboard has one. Otherwise, try using a USB based floppy drive.
244,865
I'm trying to install a floppy drive in my new desktop. I don't know much about IDE connections/cables but it seems there are multiple types. I've seen some with pins in the middle taken out and others with all their pins. I think I have a newer version of IDE on my motherboard. *Do they sell these newer cables with 3.5" drive connections?*
2011/02/12
[ "https://superuser.com/questions/244865", "https://superuser.com", "https://superuser.com/users/35203/" ]
Get a USB floppy. It will be the quickest and simplest way to go. Unless you're looking for the aesthetic value, and then you need to look for the floppy drive connector on your motherboard. You should look in your system BIOS for a floppy controller option - that's one clue if your system supports it. Another one is to look in Device Manager in Windows, or the kernel messages Linux.
you could also install a floppy controller card if you have the available space in your desktop. that would provide the 34-pin connector you need to attach the drive
244,865
I'm trying to install a floppy drive in my new desktop. I don't know much about IDE connections/cables but it seems there are multiple types. I've seen some with pins in the middle taken out and others with all their pins. I think I have a newer version of IDE on my motherboard. *Do they sell these newer cables with 3.5" drive connections?*
2011/02/12
[ "https://superuser.com/questions/244865", "https://superuser.com", "https://superuser.com/users/35203/" ]
I have just received this 34pin floppy connector to USB adapter cable from : <http://www.ebay.com.au/itm/like/291258378696?limghlpsr=true&hlpv=2&ops=true&viphx=1&hlpht=true&lpid=107> Even though my country was not on the list they posted to a polite query via Ebay solved that problem. My SAMSUNG 1.44 floppy with four port SD card combo now works perferctly again with the floppy as disk A as in the past. I found I can either power the floppy via a molex floppy power connector or use the USB power via the extra floppy power cable supplied. Although the post took two weeks the supplier posted immediately the PayPal payment went thru.
Get a USB floppy. It will be the quickest and simplest way to go. Unless you're looking for the aesthetic value, and then you need to look for the floppy drive connector on your motherboard. You should look in your system BIOS for a floppy controller option - that's one clue if your system supports it. Another one is to look in Device Manager in Windows, or the kernel messages Linux.
244,865
I'm trying to install a floppy drive in my new desktop. I don't know much about IDE connections/cables but it seems there are multiple types. I've seen some with pins in the middle taken out and others with all their pins. I think I have a newer version of IDE on my motherboard. *Do they sell these newer cables with 3.5" drive connections?*
2011/02/12
[ "https://superuser.com/questions/244865", "https://superuser.com", "https://superuser.com/users/35203/" ]
I have just received this 34pin floppy connector to USB adapter cable from : <http://www.ebay.com.au/itm/like/291258378696?limghlpsr=true&hlpv=2&ops=true&viphx=1&hlpht=true&lpid=107> Even though my country was not on the list they posted to a polite query via Ebay solved that problem. My SAMSUNG 1.44 floppy with four port SD card combo now works perferctly again with the floppy as disk A as in the past. I found I can either power the floppy via a molex floppy power connector or use the USB power via the extra floppy power cable supplied. Although the post took two weeks the supplier posted immediately the PayPal payment went thru.
you could also install a floppy controller card if you have the available space in your desktop. that would provide the 34-pin connector you need to attach the drive
74,740
when I try to add line inside `/etc/shadow`: ``` echo -e "admin234:!!:0:0:99999:7:::" >> /etc/shadow 1 2 3 ``` The console show this message: ``` -bash: 0: unrecognized history modifier ``` or ``` -bash: :14790: bad word specifier (when change 3 to :14790: ) ``` Help?
2011/11/02
[ "https://askubuntu.com/questions/74740", "https://askubuntu.com", "https://askubuntu.com/users/31859/" ]
Yeah the `!`s are being interpreted by bash. Switch your `"`s to `'` and it *should* be fine.
@Beginners, might want to ask the purpose of attempting to edit the /etc/shadow by hand in this manner, in other words, what is the desired outcome that you wish to achieve? As for understanding the whole history of the errors you are receiving, depending on your knowledge and understanding of C, there is a wealth of informative documentation [at the source archive.](http://bash.sourcearchive.com/documentation/4.0-4ubuntu1/histexpand_8c-source.html) If you search specifically for the errors you are receiving, you will find them, and see that they relate to errors you are seeing: ``` static char * hist_error(s, start, current, errtype) char *s; int start, current, errtype; { char *temp; const char *emsg; int ll, elen; ll = current - start; switch (errtype) { case EVENT_NOT_FOUND: emsg = "event not found"; elen = 15; break; case BAD_WORD_SPEC: emsg = "bad word specifier"; elen = 18; break; case SUBST_FAILED: emsg = "substitution failed"; elen = 19; break; case BAD_MODIFIER: emsg = "unrecognized history modifier"; elen = 29; break; case NO_PREV_SUBST: emsg = "no previous substitution"; elen = 24; break; default: emsg = "unknown expansion error"; elen = 23; break; } ``` There may be an easier way to achieve the ends you desire, which is why I ask what that may be. If the ends are known, then the path is likely much traveled by many before, and an answer easier to deliver to assist you. ;) Also, in reviewing the command, did not notice usage of the sudo convention, which would be necessary to complete any administrative function successfully. Remember that certain functions will not work without the correct privileges consumed at the time of execution. HTH. Have a nice day. :)
74,740
when I try to add line inside `/etc/shadow`: ``` echo -e "admin234:!!:0:0:99999:7:::" >> /etc/shadow 1 2 3 ``` The console show this message: ``` -bash: 0: unrecognized history modifier ``` or ``` -bash: :14790: bad word specifier (when change 3 to :14790: ) ``` Help?
2011/11/02
[ "https://askubuntu.com/questions/74740", "https://askubuntu.com", "https://askubuntu.com/users/31859/" ]
Yeah the `!`s are being interpreted by bash. Switch your `"`s to `'` and it *should* be fine.
History expansion only affects interactive shells when history expansion is enabled (which it is by default). You can disable history expansion by running `set +H`. I never use history expansion myself, so I put `set +H` in `~/.bashrc`. As for editing /etc/shadow manually, I'd advice against it. If you want to add users from the commandline, use `adduser` or `newusers`. ``` man 8 adduser man 8 newusers ```
74,740
when I try to add line inside `/etc/shadow`: ``` echo -e "admin234:!!:0:0:99999:7:::" >> /etc/shadow 1 2 3 ``` The console show this message: ``` -bash: 0: unrecognized history modifier ``` or ``` -bash: :14790: bad word specifier (when change 3 to :14790: ) ``` Help?
2011/11/02
[ "https://askubuntu.com/questions/74740", "https://askubuntu.com", "https://askubuntu.com/users/31859/" ]
@Beginners, might want to ask the purpose of attempting to edit the /etc/shadow by hand in this manner, in other words, what is the desired outcome that you wish to achieve? As for understanding the whole history of the errors you are receiving, depending on your knowledge and understanding of C, there is a wealth of informative documentation [at the source archive.](http://bash.sourcearchive.com/documentation/4.0-4ubuntu1/histexpand_8c-source.html) If you search specifically for the errors you are receiving, you will find them, and see that they relate to errors you are seeing: ``` static char * hist_error(s, start, current, errtype) char *s; int start, current, errtype; { char *temp; const char *emsg; int ll, elen; ll = current - start; switch (errtype) { case EVENT_NOT_FOUND: emsg = "event not found"; elen = 15; break; case BAD_WORD_SPEC: emsg = "bad word specifier"; elen = 18; break; case SUBST_FAILED: emsg = "substitution failed"; elen = 19; break; case BAD_MODIFIER: emsg = "unrecognized history modifier"; elen = 29; break; case NO_PREV_SUBST: emsg = "no previous substitution"; elen = 24; break; default: emsg = "unknown expansion error"; elen = 23; break; } ``` There may be an easier way to achieve the ends you desire, which is why I ask what that may be. If the ends are known, then the path is likely much traveled by many before, and an answer easier to deliver to assist you. ;) Also, in reviewing the command, did not notice usage of the sudo convention, which would be necessary to complete any administrative function successfully. Remember that certain functions will not work without the correct privileges consumed at the time of execution. HTH. Have a nice day. :)
History expansion only affects interactive shells when history expansion is enabled (which it is by default). You can disable history expansion by running `set +H`. I never use history expansion myself, so I put `set +H` in `~/.bashrc`. As for editing /etc/shadow manually, I'd advice against it. If you want to add users from the commandline, use `adduser` or `newusers`. ``` man 8 adduser man 8 newusers ```
7,118,072
I'm trying to compare files between two labels with cleartool but I can't seem to figure out how to find the preceding label to the label given. As for now my command looks like this ``` cleartool find . -element "{lbtype_sub(TEST_APP_123456-80_1.1.C.004) && lbtype_sub(TEST_APP_123456-80_1.1.C.005)}" -type f -ver "{lbtype(TEST_APP_123456-80_1.1.C.004) && !lbtype(TEST_APP_123456-80_1.1.C.005)}" -exec "cmd /c copy %CLEARCASE_PN% C:\diff" ``` In this case the preceding label is provided but it would be nice if cleartool could find it by itself by just providing the latest label.
2011/08/19
[ "https://Stackoverflow.com/questions/7118072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/886143/" ]
A label can be applied, and even moved to any version. Unless you are talking about **UCM baselines** (in which case a "cleartool diffbl -pred a\_BASELINE@\apvob" can give you the previous baseline, from which the label is named after), you cannot find the previous label. All you can do is to walk back from the version referenced by a label until you find another (previous) version with another label.
Create two views and compare the views with the tool of your choice.
14,305,993
Consider 2 `Scheme` functions ``` ; Define function (define (square n) (* n n )) (square 12) 144 ; Another way to define same function (define square (lambda (n) (* n n))) (square 12) 144 ``` Both seem to produce the same result. Is there any functional difference between these function declarations? Should one be preferred over another in some situations?
2013/01/13
[ "https://Stackoverflow.com/questions/14305993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/359862/" ]
There is no difference between the two definitions - the former is syntactic sugar for the latter. Which one you prefer is a matter of style, but my impression is that the former is generally the preferred way of defining functions as it is somewhat more succinct and perhaps also more readable. Introductory texts often use the latter to make it clear that a named function is simply a variable holding a lambda - something that's not that clear when using the first variant.
sepp2k is absolutely correct in that the two procedures you define are identical. In simple procedure definitions like this either is correct and it comes down to a matter of preference. One case where it does make sense to use an explicit `lambda` statement is if you need to keep track of some sort of state in the procedure. For example, we could make a counter like this: ``` (define counter (let ((count 0)) (lambda () (set! count (+ count 1)) count))) (counter) ;=> 1 (counter) ;=> 2 (counter) ;=> 3 ```