qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
50,611
Exodus 22:16 “If a man seduces a virgin who is not engaged to anyone and has sex with her, he must pay the customary bride price and marry her. 17But if her father refuses to let him marry her, the man must still pay him an amount equal to the bride price of a virgin. How was this different from rape?
2020/09/12
[ "https://hermeneutics.stackexchange.com/questions/50611", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/35953/" ]
The short answer to the question is "NO". The language here is actually one of "enticement" as the operative word is פָּתָה (pathah), which occurs about 28 times in the OT Hebrew (eg, Gen 9:22, Judges 14:15, 16:5, etc) and is always associated with something pleasant or being enticed or deceived and never implies "rape". BDB gives the following meanings for this word: > > persuade, woman Hosea 2:16 (figurative,׳י subject), seduce, virgin > Exodus 22:16; entice, husband Judges 14:15; Judges 16:5; a man to sin > Proverbs 1:10; Proverbs 16:29. > > > Thus, Ex 22:16 might be translated something like: "If a man seduces/entices a virgin ... " If the author had wanted to imply rape, then there are a number of other words available such as: * עָנָה (anah), eg, Gen 34:2, Judges 19:24, 2 Sam 13:12, 14, etc) * כָּבַשׁ (kabash), eg, Est 7:8 * טָמֵא (tame), eg, Gen 34:5
**Exodus 22 Wasn't it a case of rape?** Exodus 22:16-17 > > “If a man seduces a virgin who is not engaged to anyone and has sex > with her, he must pay the customary bride price and marry her. 17But > if her father refuses to let him marry her, the man must still pay him > an amount equal to the bride price of a virgin. > > > Deuteronomy 22:28-29 (NASB) > > 28 “If a man finds a girl who is a virgin, who is not engaged, and > seizes her and lies with her and they are discovered, 29 then the man > who lay with her shall give to the girl’s father fifty shekels of > silver, and she shall become his wife because he has violated her; he > cannot divorce her all his days. > > > How was this different from rape? It is a case of rape whether it is by seduction or seizure, the end result was the same. The serpent seduced Eve by its cunning, Adam was not, yet they both sinned. The same Law penalty applied for Exodus 22:16-17 (seduction) and Deuteronomy 22:28-29 (seizure) Exodus 22:16-17 and Deuteronomy 22:28-29 show that it is premarital fornication, they had to get married and there was no divorce option in such cases. Since there was no longer a divorce option available, this probably would cause a man or a woman to resist in the temptation of sharing in fornication. A man or woman may feel that she/he is beautiful/handsome and so I will have a good time even though she/he is not the type I want to marry. In this way, the Law deterred immorality by causing any would-be offender to weigh the long-term consequences of fornication​ of having to stay with the other party throughout his life. The Law also lessened the problem of illegitimacy. God decreed: Deuteronomy 23:2 (NASB) > > 2 No one of illegitimate birth shall enter the assembly of the Lord; > none of his descendants, even to the tenth generation, shall enter the > assembly of the Lord. > > > Hence if a man who seduced a virgin had to marry her, their fornication would not result in an illegitimate offspring among the Israelites. If a man seduced an unengaged virgin, he had to take her as his wife; even if the father flatly refused to give her to him, he had to pay her father the purchase price for virgins (50 shekels -approx USD 120 ) the usual bride-price, because her diminished value as a bride would now have to be compensated for. **This is so because not many Israelites would want to marry her.**
24,819,330
I am rediscovering OOP through a GUI application I am writing and would like to understand if it is possible to change a characteristic of all objects instantiated from a class. I have the following code: ``` class myclass(): def __init__(self): self.a = 1 x = myclass() y = myclass() print x.a, y.a # outputs 1 1 # the instruction I am looking for, assigns 2 to a in each object at once print x.a, y.a # outputs 2 2 ``` What I am looking for is a way to change `x` and `y` at once by manipulating the parent class. **I know that I can have a method which modifies `self.a`** - I do not want to use that because it means I have to call it separately for each object. My gut feeling is that this is not possible and that I have to cleverly handle my objects to simplify such activities (for instance by storing them in a list I would loop over, applying a method). I just do not want to miss a mechanism which I am not aware of and which would greatly simplify my code.
2014/07/18
[ "https://Stackoverflow.com/questions/24819330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/903011/" ]
You can have all instances share a variable if you define it as a class variable: ``` >>> class myclass(): ... a = 1 ... def __init__(self): ... self.b = 2 ... >>> x = myclass() >>> y = myclass() >>> x.a 1 >>> myclass.a = 2 # modify the class variable >>> x.a 2 >>> y.a 2 >>> x.b = 3 # modify the instance variable >>> x.b 3 >>> y.b 2 >>> x.a = 4 # create new local instance variable a >>> x.a 4 >>> y.a 2 ``` Note that now if you change `myclass.a`, you won't see the change in `x` because the instance variable will be looked up before the class variable - until you remove the instance variable using `del`: ``` >>> myclass.a = 3 >>> x.a 4 >>> y.a 3 >>> del x.a >>> x.a 3 ```
No, you can't. Object data can't be changed without pointer to the object. Possibly you need class variables and [classmethod](https://stackoverflow.com/questions/12179271/python-classmethod-and-staticmethod-for-beginner): ``` class myclass: a = 1 @classmethod def set_a(cls, val): cls.a = val x = myclass() y = myclass() print x.a, y.a # outputs 1 1 myclass.set_a(2) print x.a, y.a # outputs 2 2 ``` But in such case you cant change `a` value of objects separately. If you want such behavior you can save all instances of objects in classdata such follows: ``` class myclass: objects = [] def __init__(self): self.a = 1 # add instantiated object to object list self.__class__.objects.append(self) @classmethod def set_all(cls, val): # go through list and change each object for obj in cls.objects: obj.a = 2 x = myclass() y = myclass() print x.a, y.a # outputs 1 1 myclass.set_all(2) print x.a, y.a # outputs 2 2 # and you cat change data of each object separately: x.a = 3 print x.a, y.a # outputs 3 2 ```
24,819,330
I am rediscovering OOP through a GUI application I am writing and would like to understand if it is possible to change a characteristic of all objects instantiated from a class. I have the following code: ``` class myclass(): def __init__(self): self.a = 1 x = myclass() y = myclass() print x.a, y.a # outputs 1 1 # the instruction I am looking for, assigns 2 to a in each object at once print x.a, y.a # outputs 2 2 ``` What I am looking for is a way to change `x` and `y` at once by manipulating the parent class. **I know that I can have a method which modifies `self.a`** - I do not want to use that because it means I have to call it separately for each object. My gut feeling is that this is not possible and that I have to cleverly handle my objects to simplify such activities (for instance by storing them in a list I would loop over, applying a method). I just do not want to miss a mechanism which I am not aware of and which would greatly simplify my code.
2014/07/18
[ "https://Stackoverflow.com/questions/24819330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/903011/" ]
You can have all instances share a variable if you define it as a class variable: ``` >>> class myclass(): ... a = 1 ... def __init__(self): ... self.b = 2 ... >>> x = myclass() >>> y = myclass() >>> x.a 1 >>> myclass.a = 2 # modify the class variable >>> x.a 2 >>> y.a 2 >>> x.b = 3 # modify the instance variable >>> x.b 3 >>> y.b 2 >>> x.a = 4 # create new local instance variable a >>> x.a 4 >>> y.a 2 ``` Note that now if you change `myclass.a`, you won't see the change in `x` because the instance variable will be looked up before the class variable - until you remove the instance variable using `del`: ``` >>> myclass.a = 3 >>> x.a 4 >>> y.a 3 >>> del x.a >>> x.a 3 ```
``` class myclass(): a=10 def __init__(self): self.b=0 a=myclass() b=myclass() print a.a,b.a #output 10,10 myclass.a=2 a=myclass() b=myclass() print a.a,b.a #output 2,2 ```
24,819,330
I am rediscovering OOP through a GUI application I am writing and would like to understand if it is possible to change a characteristic of all objects instantiated from a class. I have the following code: ``` class myclass(): def __init__(self): self.a = 1 x = myclass() y = myclass() print x.a, y.a # outputs 1 1 # the instruction I am looking for, assigns 2 to a in each object at once print x.a, y.a # outputs 2 2 ``` What I am looking for is a way to change `x` and `y` at once by manipulating the parent class. **I know that I can have a method which modifies `self.a`** - I do not want to use that because it means I have to call it separately for each object. My gut feeling is that this is not possible and that I have to cleverly handle my objects to simplify such activities (for instance by storing them in a list I would loop over, applying a method). I just do not want to miss a mechanism which I am not aware of and which would greatly simplify my code.
2014/07/18
[ "https://Stackoverflow.com/questions/24819330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/903011/" ]
No, you can't. Object data can't be changed without pointer to the object. Possibly you need class variables and [classmethod](https://stackoverflow.com/questions/12179271/python-classmethod-and-staticmethod-for-beginner): ``` class myclass: a = 1 @classmethod def set_a(cls, val): cls.a = val x = myclass() y = myclass() print x.a, y.a # outputs 1 1 myclass.set_a(2) print x.a, y.a # outputs 2 2 ``` But in such case you cant change `a` value of objects separately. If you want such behavior you can save all instances of objects in classdata such follows: ``` class myclass: objects = [] def __init__(self): self.a = 1 # add instantiated object to object list self.__class__.objects.append(self) @classmethod def set_all(cls, val): # go through list and change each object for obj in cls.objects: obj.a = 2 x = myclass() y = myclass() print x.a, y.a # outputs 1 1 myclass.set_all(2) print x.a, y.a # outputs 2 2 # and you cat change data of each object separately: x.a = 3 print x.a, y.a # outputs 3 2 ```
``` class myclass(): a=10 def __init__(self): self.b=0 a=myclass() b=myclass() print a.a,b.a #output 10,10 myclass.a=2 a=myclass() b=myclass() print a.a,b.a #output 2,2 ```
9,379,047
I have a WPF application with 2 log4net appenders in log4net, the first printing to file and the second should print to console. For some reason I am not being able to show the result on log4net, but I do see it in the file. What is wrong? ``` <?xml version="1.0"?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> <log4net debug="true"> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="C:\\Temp\\1.txt" /> <appendToFile value="true" /> <rollingStyle value="Size" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="10MB" /> <staticLogFileName value="true" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" /> </layout> </appender> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" > <layout type="log4net.Layout.PatternLayout"> <param name="Header" value="[Header]\r\n" /> <param name="Footer" value="[Footer]\r\n" /> <param name="ConversionPattern" value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" /> </layout> </appender> <root> <level value="DEBUG" /> <appender-ref ref="RollingLogFileAppender" /> <appender-ref ref="ConsoleAppender" /> </root> </log4net> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> </configuration> ```
2012/02/21
[ "https://Stackoverflow.com/questions/9379047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/829174/" ]
Do you see a console pop up when you start the application. It could be you have to configure your application as a console project to have a console window... Otherwise you can check trace info. Normally an appender tries to leave one error message there if he can't log to the desired location. Output window of visual studio catches trace messages when debugging... Possible duplicate: [Log4net won't log to console (WinForms app)](https://stackoverflow.com/questions/5764159/log4net-wont-log-to-console)
Do you call once `XmlConfigurator.Configure()` ?
9,379,047
I have a WPF application with 2 log4net appenders in log4net, the first printing to file and the second should print to console. For some reason I am not being able to show the result on log4net, but I do see it in the file. What is wrong? ``` <?xml version="1.0"?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> <log4net debug="true"> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="C:\\Temp\\1.txt" /> <appendToFile value="true" /> <rollingStyle value="Size" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="10MB" /> <staticLogFileName value="true" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" /> </layout> </appender> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" > <layout type="log4net.Layout.PatternLayout"> <param name="Header" value="[Header]\r\n" /> <param name="Footer" value="[Footer]\r\n" /> <param name="ConversionPattern" value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" /> </layout> </appender> <root> <level value="DEBUG" /> <appender-ref ref="RollingLogFileAppender" /> <appender-ref ref="ConsoleAppender" /> </root> </log4net> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> </configuration> ```
2012/02/21
[ "https://Stackoverflow.com/questions/9379047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/829174/" ]
If you are wanting to see the messages in the output window in visual studio you should use the following instead: ``` <appender name="TraceAppender" type="log4net.Appender.TraceAppender" > ```
Do you call once `XmlConfigurator.Configure()` ?
9,379,047
I have a WPF application with 2 log4net appenders in log4net, the first printing to file and the second should print to console. For some reason I am not being able to show the result on log4net, but I do see it in the file. What is wrong? ``` <?xml version="1.0"?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> <log4net debug="true"> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="C:\\Temp\\1.txt" /> <appendToFile value="true" /> <rollingStyle value="Size" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="10MB" /> <staticLogFileName value="true" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" /> </layout> </appender> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" > <layout type="log4net.Layout.PatternLayout"> <param name="Header" value="[Header]\r\n" /> <param name="Footer" value="[Footer]\r\n" /> <param name="ConversionPattern" value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" /> </layout> </appender> <root> <level value="DEBUG" /> <appender-ref ref="RollingLogFileAppender" /> <appender-ref ref="ConsoleAppender" /> </root> </log4net> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> </configuration> ```
2012/02/21
[ "https://Stackoverflow.com/questions/9379047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/829174/" ]
Do you see a console pop up when you start the application. It could be you have to configure your application as a console project to have a console window... Otherwise you can check trace info. Normally an appender tries to leave one error message there if he can't log to the desired location. Output window of visual studio catches trace messages when debugging... Possible duplicate: [Log4net won't log to console (WinForms app)](https://stackoverflow.com/questions/5764159/log4net-wont-log-to-console)
If you are wanting to see the messages in the output window in visual studio you should use the following instead: ``` <appender name="TraceAppender" type="log4net.Appender.TraceAppender" > ```
317
I always hear Chinese people making sentences using 而已 - but I've never quite, 100%, understood how to use this in sentences myself. What is the correct way to apply it, and what is the English equivalent?
2011/12/17
[ "https://chinese.stackexchange.com/questions/317", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/62/" ]
“而已” is always used at the end of a sentence and with words like “仅仅”,"只","不过". A similar word in Chinese is "罢了"(actually, this word comes from 满语). You use the structure "......(part A),不过......(part B)而已" to emphasize the expression that A is just limited within B. You could only use "不过", also, and "而已“ weakens your mood and sometimes expresses that you don't have help to (or don't take care of) B. For example: 1. Your girlfriend and you are watching a magic performance. The magician is going to stab a sword into the assistant's body and your girlfriend gets scared. You would say:"别紧张,这不过是魔术表演而已。"(Don't worry, this is just a magic performance[so you don't have to get worried about it]) 2. The famous writer in modern times, 鲁迅(lu3 xun4) has a novel collection called 《而已集》.In the preface, he wrote:"连‘杂感’也被‘放进了应该去的地方’时,我于是只有‘而已’而已" (while my "random thoughts“ are put into the place where it is supposed to go(meaning, he is not allowed to publicize his thoughts, criticisms), I could only say "而已")to show his helpless and sadness. The equivalent for the structure "不过......而已" would be "only","just".
The easy way to understand this is to use an oral English sentence rather than something formal. This is commonly used to mean "...and that's all". For example in English you can say "It's just an exam and that's all". In Chinese this could be said: "这不过是一个考试而已" *Zhè bùguò shì yīgè kǎoshì éryǐ*
1,777
On my WP8 Nokia phone, I have received a audio file ring tone in an email and in a text which I sent to myself from my old phone. How do I save it to be able to use as ring tone?
2013/04/14
[ "https://windowsphone.stackexchange.com/questions/1777", "https://windowsphone.stackexchange.com", "https://windowsphone.stackexchange.com/users/1263/" ]
Technically, you should be able to just "Save as ringtone" when you tap and hold the attachment: > > [Add ringtones to my phone](http://www.windowsphone.com/en-US/how-to/wp8/start/add-ringtones-to-my-phone) > > > To add a ringtone from a text message > > 1. Tap and hold the ringtone file, and then tap Save as ringtone. > > 2. Rename the ringtone, if you want to, then tap OK. > > > If your phone doesn't give you that option, then it's possible (probable) that the file isn't in a format that WP8 supports - WP7 for example [only supported .wma and .mp3 formatted audio](http://www.windowsphone.com/en-us/how-to/wp7/start/create-ringtones). Alternatively, you can try to do it from your PC. Ringtones on WP8 need to be saved in the `Ringtones` folder on your phone there are further details on this howto: > > [Sync music, ringtones, and podcasts using my computer](http://www.windowsphone.com/en-US/how-to/wp8/music/sync-music-ringtones-and-podcasts-using-my-computer) > > >
First the file you want to use as a ring tone must fit the following [requirements](http://www.windowsphone.com/en-us/how-to/wp7/start/create-ringtones): * In MP3 or WMA format. * Less than 40 seconds. * Less than 1 MB. * Not protected with digital rights management (DRM). And most importantly the item that most people miss in the linked article is that the **genre tag** in the song itself be classified as **ringtone**.
1,777
On my WP8 Nokia phone, I have received a audio file ring tone in an email and in a text which I sent to myself from my old phone. How do I save it to be able to use as ring tone?
2013/04/14
[ "https://windowsphone.stackexchange.com/questions/1777", "https://windowsphone.stackexchange.com", "https://windowsphone.stackexchange.com/users/1263/" ]
Technically, you should be able to just "Save as ringtone" when you tap and hold the attachment: > > [Add ringtones to my phone](http://www.windowsphone.com/en-US/how-to/wp8/start/add-ringtones-to-my-phone) > > > To add a ringtone from a text message > > 1. Tap and hold the ringtone file, and then tap Save as ringtone. > > 2. Rename the ringtone, if you want to, then tap OK. > > > If your phone doesn't give you that option, then it's possible (probable) that the file isn't in a format that WP8 supports - WP7 for example [only supported .wma and .mp3 formatted audio](http://www.windowsphone.com/en-us/how-to/wp7/start/create-ringtones). Alternatively, you can try to do it from your PC. Ringtones on WP8 need to be saved in the `Ringtones` folder on your phone there are further details on this howto: > > [Sync music, ringtones, and podcasts using my computer](http://www.windowsphone.com/en-US/how-to/wp8/music/sync-music-ringtones-and-podcasts-using-my-computer) > > >
Save it like plain mp3 file and then use [Ringtone Maker](http://www.windowsphone.com/en-us/store/app/ringtone-maker/5a99cbd9-e82a-4892-8264-17a64f9142e5) to transform it into ringtone. ![enter image description here](https://i.stack.imgur.com/pn5OB.png) > > With Ringtone Maker, you can create ringtones from the music on your phone. Simply open the app, select your favorite song and save it as a ringtone. You can cut your ringtone anyway you like, with editing controls that let you choose the start, end and length of your ringtone. > > > There’s now support for more music file formats: WMA, M4A, M4R, and AAC along with MP3. > > >
11,540,342
I've an iphone app and a web app(in php ), i want to synchronize contacts in iphone app with database records.(from both device and web app ie. user can add/update/delete contacts from device or web app and both database will sync.) Thanks
2012/07/18
[ "https://Stackoverflow.com/questions/11540342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1534593/" ]
Use php-addressbook.sf.net, it includes a Exchange Interface to Sync your iPhone.
your question is not clear anyway I will give you some ideas ``` ABAddressBookRef addressBook = ABAddressBookCreate( ); CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople( addressBook ); CFIndex nPeople = ABAddressBookGetPersonCount( addressBook ); for ( int i = 0; i < nPeople; i++ ) { ABRecordRef ref = CFArrayGetValueAtIndex( allPeople, i );} ``` here the link for editing contacts and managing contacts <http://zcentric.com/2008/09/19/access-the-address-book/> <https://developer.apple.com/library/ios/#samplecode/QuickContacts/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009475>
282,018
**SimpleQueueable.cls**: ``` public with sharing class SimpleQueueable implements System.Queueable{ public void execute(System.QueueableContext ctxt){ //query the record inserted in calling transaction //make some changes on the record and update the record. } } ``` **Sample code of calling transaction**: ``` SimpleQueueable job = new SimpleQueueable(); System.enqueueJob(job); Long start = System.now().getTime(); while(System.now().getTime() - start < 6000 ){ } // Decimal x = 6/0; If I uncomment this line queueable is not running. ``` **Behavior of Queueable job** : 1. Only run if calling transaction completes successfully. 2. Only run after the completion of calling transaction and should not run in parallel with calling transaction. 3. Query the record that is inserted in the calling transaction and do some updates and update the record. **About calling transaction**: Calling transaction starts with custom code and ends with managed package code. So, I don't have a way to know when the calling transaction ends. **What I have noticed**: 1. If the calling transaction is failing then queueuable is not executed. 2. Queueable job is executed after the calling transaction is completed. Can someone confirm this or my findings wrong?
2019/10/19
[ "https://salesforce.stackexchange.com/questions/282018", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/16304/" ]
> > 1. If the calling transaction is failing then queueuable is not executed. > 2. Queueable job is executed after the calling transaction is completed. > > > This is correct. Whenever you invoke Asynchronous Apex (whether Queueable, Batch, Scheduled, or Future), your request is persisted to the queue *when your transaction commits successfully*. If an unhandled exception is thrown (or a rollback operation is otherwise performed), all enqueued asynchronous Apex will be rolled back along with regular sObject DML.
100% - like all async processing this is handled by creating a record in the database which is consumed by the Salesforce runtime at a later point based on processing availability and schedule. For the async processing to happen, therefore, the transaction must have finished since this is when the database transaction itself is finalized.
282,018
**SimpleQueueable.cls**: ``` public with sharing class SimpleQueueable implements System.Queueable{ public void execute(System.QueueableContext ctxt){ //query the record inserted in calling transaction //make some changes on the record and update the record. } } ``` **Sample code of calling transaction**: ``` SimpleQueueable job = new SimpleQueueable(); System.enqueueJob(job); Long start = System.now().getTime(); while(System.now().getTime() - start < 6000 ){ } // Decimal x = 6/0; If I uncomment this line queueable is not running. ``` **Behavior of Queueable job** : 1. Only run if calling transaction completes successfully. 2. Only run after the completion of calling transaction and should not run in parallel with calling transaction. 3. Query the record that is inserted in the calling transaction and do some updates and update the record. **About calling transaction**: Calling transaction starts with custom code and ends with managed package code. So, I don't have a way to know when the calling transaction ends. **What I have noticed**: 1. If the calling transaction is failing then queueuable is not executed. 2. Queueable job is executed after the calling transaction is completed. Can someone confirm this or my findings wrong?
2019/10/19
[ "https://salesforce.stackexchange.com/questions/282018", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/16304/" ]
100% - like all async processing this is handled by creating a record in the database which is consumed by the Salesforce runtime at a later point based on processing availability and schedule. For the async processing to happen, therefore, the transaction must have finished since this is when the database transaction itself is finalized.
As a more generic answer: everything that occurs "at the end of a transaction" will not happen if you fail to reach the natural end of the transaction successfully, either by governor limits, an unhandled exception, or an addError/validation rule that causes the records to roll back. This includes scheduling jobs, sending emails, running Queueable and Batchable jobs, triggering Outbound Messaging (Workflow), and some Platform Events (those configured to fire on successful transactions only). Also, you can achieve similar effects with SavePoint/rollback, such as: ``` SavePoint sp = Database.setSavePoint(); MyUtil.sendSomeEmails(); MyUtil.doSomeBatchableStuff(); MyUtil.doQueueableStuffToo(); // None of the above actually "happened" as far as the database is concerned! Database.rollback(sp); ``` So, because of this behavior, you can guarantee that the Batchable/Queueable/Schedulable/Emails **cannot** occur before the transaction ends, with the exception of the "immediate send" Platform Events.
282,018
**SimpleQueueable.cls**: ``` public with sharing class SimpleQueueable implements System.Queueable{ public void execute(System.QueueableContext ctxt){ //query the record inserted in calling transaction //make some changes on the record and update the record. } } ``` **Sample code of calling transaction**: ``` SimpleQueueable job = new SimpleQueueable(); System.enqueueJob(job); Long start = System.now().getTime(); while(System.now().getTime() - start < 6000 ){ } // Decimal x = 6/0; If I uncomment this line queueable is not running. ``` **Behavior of Queueable job** : 1. Only run if calling transaction completes successfully. 2. Only run after the completion of calling transaction and should not run in parallel with calling transaction. 3. Query the record that is inserted in the calling transaction and do some updates and update the record. **About calling transaction**: Calling transaction starts with custom code and ends with managed package code. So, I don't have a way to know when the calling transaction ends. **What I have noticed**: 1. If the calling transaction is failing then queueuable is not executed. 2. Queueable job is executed after the calling transaction is completed. Can someone confirm this or my findings wrong?
2019/10/19
[ "https://salesforce.stackexchange.com/questions/282018", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/16304/" ]
> > 1. If the calling transaction is failing then queueuable is not executed. > 2. Queueable job is executed after the calling transaction is completed. > > > This is correct. Whenever you invoke Asynchronous Apex (whether Queueable, Batch, Scheduled, or Future), your request is persisted to the queue *when your transaction commits successfully*. If an unhandled exception is thrown (or a rollback operation is otherwise performed), all enqueued asynchronous Apex will be rolled back along with regular sObject DML.
As a more generic answer: everything that occurs "at the end of a transaction" will not happen if you fail to reach the natural end of the transaction successfully, either by governor limits, an unhandled exception, or an addError/validation rule that causes the records to roll back. This includes scheduling jobs, sending emails, running Queueable and Batchable jobs, triggering Outbound Messaging (Workflow), and some Platform Events (those configured to fire on successful transactions only). Also, you can achieve similar effects with SavePoint/rollback, such as: ``` SavePoint sp = Database.setSavePoint(); MyUtil.sendSomeEmails(); MyUtil.doSomeBatchableStuff(); MyUtil.doQueueableStuffToo(); // None of the above actually "happened" as far as the database is concerned! Database.rollback(sp); ``` So, because of this behavior, you can guarantee that the Batchable/Queueable/Schedulable/Emails **cannot** occur before the transaction ends, with the exception of the "immediate send" Platform Events.
8,407,917
Are there service hooks for [GitHub](http://en.wikipedia.org/wiki/GitHub) wiki repositories? Is there some other mechanism that GitHub provides for me to track wiki edits?
2011/12/06
[ "https://Stackoverflow.com/questions/8407917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/288959/" ]
**Push approach:** Within the [GitHub API documentation](http://developer.github.com/v3/), you can find documentation about setting up [service hooks](http://developer.github.com/v3/repos/hooks/) which can be triggered for one or more events. The `gollum` event is especially raised any time a wiki page is updated. **JSON-based pull approach:** You can also leverage the [Events HTTP API](http://developer.github.com/v3/events/) to retrieve a JSON formated output of what happens on GitHub, then apply some filtering in order to isolate the events of type `GollumEvent`. Below a quick jQuery-based sample ``` <html> <head> <title>Gollum events</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script type="text/javascript"> $(function() { $.getJSON('https://api.github.com/repos/holman/spark/events?callback=?', function(data) { var list = $('#gollum-events'); $.each(data.data, function(key, val) { if (val.type == "GollumEvent") { $.each(val.payload.pages, function(key2, val2) { list.append('<li id="' + key + '.' + key2 + '"><a href="' + val2.html_url + '">' + val2.page_name + '</a> [' + val.actor.login + ' @ ' + val.created_at + ']</li>'); }); } }); }); }); </script> </head> <body> <ul id="gollum-events"/> </body> </html> ``` **Atom based pull approach:** Last but not least, you can subscribe to the wiki changes atom feed. Go to the GitHub Wiki section of the repository, select the `Pages` sub tab, hover onto the orange icon, copy the link and paste into your favorite RSS reader. ![Subscribe to changes](https://i.stack.imgur.com/4NZh9.png) Update: ------- It looks like the RSS feed icon is no longer displayed for a wiki. However, you can still build the URL by yourself * **Syntax:** `https://github.com/:user/:repository/wiki.atom` * **Example:** ***<https://github.com/holman/spark/wiki.atom>***
I set up a Jenkins job to pull our GitHub wiki from <https://github.com/IQSS/dvn.wiki.git> with a build trigger of @daily. In a build step, I'm executing a shell command like this to email us: > > echo "The DVN wiki on GitHub has been updated. Please check for new content at <https://github.com/IQSS/dvn/wiki/_history>" | mail -s "[dvn-wiki-notifications] update detected" [email protected] > > > Here's the job if anyone cares to see: <https://build.hmdc.harvard.edu:8443/job/dvn-wiki-notifications/>
26,561,851
How to create extension method for a generic type? The below code returning error > > Extension method can only be declared in non-generic, non-nested static class > > > Code: ``` public static class PagedList<T> where T : BaseEntity { public static IEnumerable<T> ToPagedList(this IEnumerable<T> source, int pageNumber = 0, int pageSize = 5) { return source.Skip(pageNumber * pageSize).Take(pageSize); } } ``` Any further implementation with this makes this work ?
2014/10/25
[ "https://Stackoverflow.com/questions/26561851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Specify generic types directly on the method and make the class as the error says static and non-generic. ``` public static class PagedList { public static IEnumerable<T> ToPagedList<T>(this IEnumerable<T> source, int pageNumber = 0, int pageSize = 5) where T : BaseEntity { return source.Skip(pageNumber * pageSize).Take(pageSize); } } ```
You should listen the error message, you need to declare your extension method inside of a non-generic class.
13,392
I'm excited about the iMac 2011 refresh, but I'm troubled by the news that there are no SATA 3 connections. There's lots of confusion on Mac Rumors and [OWC blogged that there is no SATA 3](http://blog.macsales.com/10002-2011-imacs-no-sata-6gbs-yes-to-multiple-drives). I was wondering if anyone has an iMac 2011 and can confirm that there is in fact no SATA 3 controller. I'm trying to determine if I should get a Vertex 3 or just stick with the Vertex 2. No SATA 3 controller would mean you wouldn't get any benefit from the Vertex 3. Thanks in advance.
2011/05/04
[ "https://apple.stackexchange.com/questions/13392", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/6216/" ]
I don't have a 2011 iMac, however you can trust the statement from OWC that you linked in your question. They bought one, took it apart and unequivocally state that there is NO SATA 3 support. Since they sell the Vertex 3 and the industry is moving towards SATA 3, it would not be in their commercial interest to make this statement were it not true.
Whilst there may be no SATA3 controller on board there is nothing to stop a SATA3 to Thunderbolt interface appearing in the future. The lack of SATA3 on the new iMacs is not stopping me from buying one. Thunderbolt will provide all the expansion opportunities I need.
13,392
I'm excited about the iMac 2011 refresh, but I'm troubled by the news that there are no SATA 3 connections. There's lots of confusion on Mac Rumors and [OWC blogged that there is no SATA 3](http://blog.macsales.com/10002-2011-imacs-no-sata-6gbs-yes-to-multiple-drives). I was wondering if anyone has an iMac 2011 and can confirm that there is in fact no SATA 3 controller. I'm trying to determine if I should get a Vertex 3 or just stick with the Vertex 2. No SATA 3 controller would mean you wouldn't get any benefit from the Vertex 3. Thanks in advance.
2011/05/04
[ "https://apple.stackexchange.com/questions/13392", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/6216/" ]
It turns out that there is SATA 3 on board, it just wasn't enabled until 4 May 2011. The Other World Computing [blog](http://blog.macsales.com/10050-firmware-update-enables-6gbs-in-2011-imacs) has the details: > > While [iMac EFI Update 1.6](http://support.apple.com/kb/DL1380) is described > as including “fixes that improve > performance and stability for > Thunderbolt,” it would also seem that > an unadvertised benefit is that it > also unlocks the full 6Gb/s, SATA 3.0 > capabilities of two of the internal > drive bays. > > > Unfortunately, the optical bay remains > at 3Gb/s. > > >
I don't have a 2011 iMac, however you can trust the statement from OWC that you linked in your question. They bought one, took it apart and unequivocally state that there is NO SATA 3 support. Since they sell the Vertex 3 and the industry is moving towards SATA 3, it would not be in their commercial interest to make this statement were it not true.
13,392
I'm excited about the iMac 2011 refresh, but I'm troubled by the news that there are no SATA 3 connections. There's lots of confusion on Mac Rumors and [OWC blogged that there is no SATA 3](http://blog.macsales.com/10002-2011-imacs-no-sata-6gbs-yes-to-multiple-drives). I was wondering if anyone has an iMac 2011 and can confirm that there is in fact no SATA 3 controller. I'm trying to determine if I should get a Vertex 3 or just stick with the Vertex 2. No SATA 3 controller would mean you wouldn't get any benefit from the Vertex 3. Thanks in advance.
2011/05/04
[ "https://apple.stackexchange.com/questions/13392", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/6216/" ]
It turns out that there is SATA 3 on board, it just wasn't enabled until 4 May 2011. The Other World Computing [blog](http://blog.macsales.com/10050-firmware-update-enables-6gbs-in-2011-imacs) has the details: > > While [iMac EFI Update 1.6](http://support.apple.com/kb/DL1380) is described > as including “fixes that improve > performance and stability for > Thunderbolt,” it would also seem that > an unadvertised benefit is that it > also unlocks the full 6Gb/s, SATA 3.0 > capabilities of two of the internal > drive bays. > > > Unfortunately, the optical bay remains > at 3Gb/s. > > >
Whilst there may be no SATA3 controller on board there is nothing to stop a SATA3 to Thunderbolt interface appearing in the future. The lack of SATA3 on the new iMacs is not stopping me from buying one. Thunderbolt will provide all the expansion opportunities I need.
15,778
There are a number of "[Pay with tweet](https://webmasters.stackexchange.com/questions/15770/service-to-give-access-to-download-after-tweet-fb-like-etc)" type services where you get access to a download (pdf/ebook etc) if you tweet or Facebook like. Are there any services that do similar for 'normal' links (Blogs etc)? If you had an online service that you were planning to give away free if people linked to you for then would this be ( from an SEO perspective) :- * ethical? * effective?
2011/06/23
[ "https://webmasters.stackexchange.com/questions/15778", "https://webmasters.stackexchange.com", "https://webmasters.stackexchange.com/users/3406/" ]
It's not effective if you get caught: > > Google works hard to ensure that it > fully discounts links intended to > manipulate search engine results, such > excessive link exchanges and purchased > links that pass PageRank. > > > <http://www.google.com/support/webmasters/bin/answer.py?answer=66736> However > > Not all paid links violate our > guidelines. Buying and selling links > is a normal part of the economy of the > web when done for advertising > purposes, and not for manipulation of > search results. Links purchased for > advertising should be designated as > such. This can be done in several > ways, such as: > > > * Adding a rel="nofollow" attribute to > the tag > * Redirecting the links to > an intermediate page that is blocked > from search engines with a robots.txt > file > > > So if you follow those guidelines you won't get SEO, but you may get visitors.
This is definitely a grey area and I would think this could very well fall against Google's guidelines. You are manipulating the search engines by buying links. You may not be paying with money but you're giving something of monetary value to users to get backlinks. Those backlinks would never have occurred otherwise. I'd avoid it for the potential to be seen as purchasing links. I also doubt the links you get will be quality links. Sites that can potentially give you quality links almost certainly won't do something like this. Not too mention I would think most links would be from low quality and or off-topic sites. Those links would have very little value.
35,520,208
I went through many questions and answers here in stack over flow about setting the minimum date in **UIDatepicker**, I have tried most of it but I am still not able to set the minimum date in **UIDatepicker**. My exact requirement is that for people who are aged above 70 should not sign up with my app. This is the code which I have tried but didn't give me the exact result. ``` NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDate *currentDate = [NSDate date]; NSDateComponents *comps = [[NSDateComponents alloc] init]; NSDateComponents *compsII = [[NSDateComponents alloc] init]; [comps setYear:-14]; NSDate *maxDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0]; [compsII setYear:1960]; NSDate *minDate = [[NSCalendar currentCalendar] dateFromComponents:compsII]; datePicker =[[UIDatePicker alloc]initWithFrame:CGRectMake(0, 400, self.view.frame.size.width, 200)]; datePicker.datePickerMode = UIDatePickerModeDate; datePicker.hidden=NO; datePicker.maximumDate = maxDate; datePicker.minimumDate = minDate; ```
2016/02/20
[ "https://Stackoverflow.com/questions/35520208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3913001/" ]
I think this is your problem 1. You have your min and max dates the wrong way around. 2. You have set the year to -14. **Update:** Try this code: ``` NSDate *todaysDate = [NSDate date]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; NSDateComponents *minDateComponents = [[NSDateComponents alloc] init]; [minDateComponents setYear:-70]; NSDate *minDate = [gregorian dateByAddingComponents:minDateComponents toDate:todaysDate options:0]; NSDateComponents *maxDateComponents = [[NSDateComponents alloc] init]; [maxDateComponents setYear:-14]; NSDate *maxDate = [gregorian dateByAddingComponents:maxDateComponents toDate:todaysDate options:0]; ```
``` [formatter setDateFormat:@"MMM dd,yyyy"]; NSDate *date = [formatter dateFromString:lblDate.text]; datePicker.minimumDate=date; ```
25,994,048
I have two variables that I have plotted using `matplotlib` scatter function. ![enter image description here](https://i.stack.imgur.com/PR3rb.png) **`I would like to show the 68% confidence region by highlighting it in the plot.`** I know to show it in a histogram, but I don't know how to do it for a 2D plot like this (x vs y). In my case, the `x is Mass` and `y is Ngal Mstar+2`. **An example image of what I am looking for looks like this:** Here they have showed the 68% confidence region using dark blue and 95% confidence region using light blue. **Can it be achieved using one of the**`scipy.stats` modules? ![enter image description here](https://i.stack.imgur.com/j9hj7.jpg)
2014/09/23
[ "https://Stackoverflow.com/questions/25994048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1469380/" ]
To plot a region between two curves, you could use `pyplot.fill_between()`. As for your confidence region, I was not sure what you wanted to achieve, so I exemplified with simultaneous confidence bands, by modifying the code from: <https://en.wikipedia.org/wiki/Confidence_and_prediction_bands#cite_note-2> ``` import numpy as np import matplotlib.pyplot as plt import scipy.special as sp ## Sample size. n = 50 ## Predictor values. XV = np.random.uniform(low=-4, high=4, size=n) XV.sort() ## Design matrix. X = np.ones((n,2)) X[:,1] = XV ## True coefficients. beta = np.array([0, 1.], dtype=np.float64) ## True response values. EY = np.dot(X, beta) ## Observed response values. Y = EY + np.random.normal(size=n)*np.sqrt(20) ## Get the coefficient estimates. u,s,vt = np.linalg.svd(X,0) v = np.transpose(vt) bhat = np.dot(v, np.dot(np.transpose(u), Y)/s) ## The fitted values. Yhat = np.dot(X, bhat) ## The MSE and RMSE. MSE = ((Y-EY)**2).sum()/(n-X.shape[1]) s = np.sqrt(MSE) ## These multipliers are used in constructing the intervals. XtX = np.dot(np.transpose(X), X) V = [np.dot(X[i,:], np.linalg.solve(XtX, X[i,:])) for i in range(n)] V = np.array(V) ## The F quantile used in constructing the Scheffe interval. QF = sp.fdtri(X.shape[1], n-X.shape[1], 0.95) QF_2 = sp.fdtri(X.shape[1], n-X.shape[1], 0.68) ## The lower and upper bounds of the Scheffe band. D = s*np.sqrt(X.shape[1]*QF*V) LB,UB = Yhat-D,Yhat+D D_2 = s*np.sqrt(X.shape[1]*QF_2*V) LB_2,UB_2 = Yhat-D_2,Yhat+D_2 ## Make the plot. plt.clf() plt.plot(XV, Y, 'o', ms=3, color='grey') plt.hold(True) a = plt.plot(XV, EY, '-', color='black', zorder = 4) plt.fill_between(XV, LB_2, UB_2, where = UB_2 >= LB_2, facecolor='blue', alpha= 0.3, zorder = 0) b = plt.plot(XV, LB_2, '-', color='blue', zorder=1) plt.plot(XV, UB_2, '-', color='blue', zorder=1) plt.fill_between(XV, LB, UB, where = UB >= LB, facecolor='blue', alpha= 0.3, zorder = 2) b = plt.plot(XV, LB, '-', color='blue', zorder=3) plt.plot(XV, UB, '-', color='blue', zorder=3) d = plt.plot(XV, Yhat, '-', color='red',zorder=4) plt.ylim([-8,8]) plt.xlim([-4,4]) plt.xlabel("X") plt.ylabel("Y") plt.show() ``` The output looks like this: ![enter image description here](https://i.stack.imgur.com/lrcxt.png)
First of all **thank you @snake\_charmer** for your answer, **but I have found a simpler way of solving the issue using** `curve_fit` from `scipy.optimize` I fit my data sample using `curve_fit` which gives me my best fit parameters. What it also gives me is the estimated covariance of the parameters. The diagonals of the same provide the variance of the parameter estimate. To compute one standard deviation errors on the parameters we can use `np.sqrt(np.diag(pcov))` where `pcov` is the covariance matrix. ``` def fitfunc(M,p1,p2): N = p1+( (M)*p2 ) return N ``` The above is the fit function I use for the data. Now to fit the data using `curve_fit` ``` popt_1,pcov_1 = curve_fit(fitfunc,logx,logn,p0=(10.0,1.0),maxfev=2000) p1_1 = popt_1[0] p1_2 = popt_1[1] sigma1 = [np.sqrt(pcov_1[0,0]),np.sqrt(pcov_1[1,1])] #THE 1 SIGMA CONFIDENCE INTERVALS residuals1 = (logy) - fitfunc((logx),p1_1,p1_2) xi_sq_1 = sum(residuals1**2) #THE CHI-SQUARE OF THE FIT curve_y_1 = fitfunc((logx),p1_1,p1_2) fig = plt.figure() ax1 = fig.add_subplot(111) ax1.scatter(logx,logy,c='r',label='$0.0<z<0.5$') ax1.plot(logx,curve_y_1,'y') ax1.plot(logx,fitfunc(logx,p1_1+sigma1[0],p1_2+sigma1[1]),'m',label='68% conf limits') ax1.plot(logx,fitfunc(logx,p1_1-sigma1[0],p1_2-sigma1[1]),'m') ``` **`So just by using the square root the diagonal elements of the covariance matrix, I can obtain the 1 sigma confidence lines.`** ![enter image description here](https://i.stack.imgur.com/M0V1X.png)
63,185,883
I have two functions in React Native Component, in that one should refresh every 10s and another one should refresh every 1s. I have implemented **`setInterval()`** function for refreshing on `componentDidMount()` and **`clearInterval()`** on `componentWillUnmount()`, but am facing trouble it takes only one function which has the lowest duration. But am achieving result if set duration of both function same duration. Here is the example ```js ... class App extends React.Component { constructor(props) { super(props); this.state = { btLevel: 0, btState: null, }; } componentDidMount() { this.getBtLevels(); this.getBtState(); this.batLS2(); this.batLS10(); } componentWillUnmount() { clearInterval(() => { this.batLSS(); this.batLS10(); }); } getBtLevels = () => { fetch(apiUrl).then((res) => this.setState({btLevel: res.level}), ); }; getBtLevelArcs = () => { fetch(apiUrl).then((res) => this.setState({btLevelArc: res.level}), ); }; getBtState = () => { fetch(apiUrl).then((res) => this.setState({BtState: res.state}), ); }; batLS10 = () => { setInterval(() => { this.getBtLevelArcs(); }, 10000); }; batLS2 = () => { setInterval(() => { this.getBtLevels(); this.getBtState(); }, 1000); }; ... ``` On the above Code `this.getBtLevels(); this.getBtState();` fetch value every 1 seconds and `this.getBtLevelArcs();` fetch value every 10 secounds. In this `this.getBtLevels(); this.getBtLevelArcs();` functions get same value. But one should refresh every 1 second and another one every 10 seconds. Here am getting is 1s *setInterval* function `this.batLS2()` is refresh whole component. How can I achieve this one should refresh value 1s and another 10s. here is the Original Version code. [Expo](https://snack.expo.io/@fussionweb/batlel)
2020/07/31
[ "https://Stackoverflow.com/questions/63185883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4627415/" ]
Issue ===== `clearInterval` works by being passed the reference returned from `setInterval`, i.e. `this.timerId = setInterval(...` and `clearInterval(this.timerId)`. What I suspect is occurring is you edited you code and ran, which set an interval callback (but didn't clear it), and then edited and re-ran your code, which sets another interval callback (again, not cleared), etc... You basically aren't cleaning up the interval callbacks when the component unmounts (like a page refresh). Solution ======== Add a timer variable for each interval timer ``` constructor(props) { super(props); ... this.timer1 = null; this.timer2 = null; } ``` Clear each interval on dismount ``` componentWillUnmount() { clearInterval(this.timer1) clearInterval(this.timer2) } ``` Save the timer ref ``` batLS10 = () => { this.timer2 = setInterval(() => { this.getBtLevelArcs(); }, 10000); }; batLS2 = () => { this.timer1 = setInterval(() => { this.getBtLevels(); this.getBtState(); }, 1000); }; ``` [![Edit nostalgic-snow-iqx3u](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/nostalgic-snow-iqx3u?expanddevtools=1&fontsize=14&hidenavigation=1&module=%2Fsrc%2FApp.js&theme=dark)
What I understood by the example and statement is you want `getBtLevels` and `getBtState` to be called after every 1 sec and `getBtLevelArcs` after every 10 seconds. But what happens is when `getBtState` and `getBtLevels` invoke, their `setState` updates the whole component, which is not acceptable in your case. Ideally this should not be a problem, because all the three functions have different states. `btLevel`, `btLevelArc` and `btState`. Updating one state should not impact the other one. But that totally depends upon your UI logic. If that is still a problem: what you can do. You can split your component into two components. First one will hold the UI related to `getBtLevels` and `getBtState` and second component will contain UI related to `getBtLevelArcs`. This is required because setState will re-render the whole component. Code will be something like this: ``` class App extends React.Component { ... //some common handlers for SubApp1 and SubApp2 ... render() { return ( <React.Fragment> <SubApp1 /> <SubApp2 /> </React.Fragment> ) } class SubApp1 extends React.Component { constructor(props) { super(props); this.state = { btLevel: 0, btState: null, }; } componentDidMount() { this.getBtLevels(); this.getBtState(); this.batLS2(); } componentWillUnmount() { clearInterval(() => { this.batLSS(); }); } getBtLevels = () => { fetch(apiUrl).then((res) => this.setState({ btLevel: res.level }), ); }; getBtState = () => { fetch(apiUrl).then((res) => this.setState({ BtState: res.state }), ); }; batLS2 = () => { setInterval(() => { this.getBtLevels(); this.getBtState(); }, 1000); } ... ... class SubApp2 extends React.Component { constructor(props) { super(props); this.state = { btLevelArc: 'some default value' }; } componentDidMount() { this.batLS10(); } componentWillUnmount() { clearInterval(() => { this.batLS10(); }); } getBtLevels = () => { fetch(apiUrl).then((res) => this.setState({ btLevel: res.level }), ); }; getBtState = () => { fetch(apiUrl).then((res) => this.setState({ BtState: res.state }), ); }; getBtLevelArcs = () => { fetch(apiUrl).then((res) => this.setState({ btLevelArc: res.level }), ); }; ... ... ```
29,709,156
My wife's birthday is coming up and I would like to create a website similar to Ba Ba Dum: <https://babadum.com/> I have learned HTML5 in school but never learned about its ability to create animated websites. How do I go about making a website like that? Do I have to use Flash or is it fully rendered with HTML5? Looking at the source code revealed something about google api and ajax and jquery, are they essential to making an animated website like this? Thanks!
2015/04/17
[ "https://Stackoverflow.com/questions/29709156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4802871/" ]
Although your question is way, way too broad, I'll try to help. The site you linked -as far as I can tell- is made HTML, CSS and JavaScript. There are less and less sites that use Flash, and you shouldn't use that either - it's starting to die out, at last. Be prepared to research a lot - you'll have to learn about CSS3 (style, position and animations), JavaScript ("JS", it's very useful for sites filled with interactive elements - sounds, videos, etc) and jQuery (special JS library, it contains several dozens of pre-written functions that can make web development easier and faster). If I were you, I'd visit [Codecademy](http://www.codecademy.com/), it's a website that teaches these languages, and for free. Completing those courses shouldn't take more than 20-30 hours, and it would give you a solid base to start from. Of course, the required skill level depends on the type of site you want to build. A simple, animated website can be built with only HTML and CSS3. For more complex sites you most likely have to use JS and jQuery. Here is what should you do: * Start out with a fix idea: you want to know what you want to create, especially because (probably) this will be your first serious project. Doodle on paper, write down your ideas about what should happen if you press a button, for example. * Divide the site into smaller pieces: you won't finish it one day, so you should focus on building the site step by step. Create a button, use CSS to make it fancy then give it some animation. If you are satisfied, you can move on to the next part. * Research: most likely you won't be the first person to do the things you want to do the way you want to do. Use google and you'll find hundreds of different tutorials, starting from simple things (building a layout) to more complex one (pure CSS animations, canvas, etc). If you stuck, Stackoverflow will help, but you'll have to be more specific with your questions. This current question is bad, and I'm only writing this response because I too know about needing help and realizing no one will help me just because my question is too broad. And I don't have anything better to do at 23:40 :) Try to find out if someone already asked your question - it's possible, and that way you may find the answer(s) instantly. * Study source codes: if you are using Chrome, you click on any element on a site to view it's code - you just have to select "Inspect element" from the context menu (there are other ways to do it with other browsers). It will show you the HTML, the CSS properties and even the relevant JS code. You can modify these values (especially useful with CSS) if you want to experiment a little - these changes are only visible for you and deleted when you refresh the page. This method is useful if you found the perfect button animation you want to include on your page but don't know how to do it. * Backup your work! Create a backup copy of your site every day, so if you mess something up badly (happens to everyone, especially if you're in a hurry like often I am) you don't have to start from scratch. It happened to me before, and if you are using other people's code (from tutorials, I'm not talking about stealing) it might happen to you too. Also, good luck!
Here are a few places I'd recommend going to, all of these have helped me and are a good place to start. * Codecademy - <http://www.codecademy.com/learn> For basic HTML, CSS, JavaScript and jQuery lessons. Best site on the web, I say. Also, recently released AngularJS lessons, which are quite good. * Code school - <https://www.codeschool.com/> Provides good AngularJS lessons, which you should do once you've finished the Codecademy ones. * Egghead - <https://egghead.io/> Good for AngularJS lessons and HTML5 canvas lessons. The HTML5 canvas lessons are brilliant, the presenter is a genius. What all these things are. HTML5 canvas - A method of drawing graphics to the screen. Great for video games and animations. I've actually made the loading effect of that site you listed with canvas. jQuery - A JavaScript library, which is a bunch of predefined functions for ease in coding. It is good for special effects and event listeners. AngularJS - An awesome library which makes displaying data so much easier. Great for fast single page apps.
806,689
I'm trying to search the DB2 equivalent of [generate\_series()](http://www.postgresql.org/docs/8.3/static/functions-srf.html) (the PostgreSQL-way of generating rows). I obviously don't want to hard-code the rows with a [VALUES](http://www.postgresql.org/docs/8.3/static/sql-values.html) statement. ``` select * from generate_series(2,4); generate_series ----------------- 2 3 4 (3 rows) ```
2009/04/30
[ "https://Stackoverflow.com/questions/806689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24760/" ]
The where clause needs to be a bit more explicit about the bounds of the recursion in order for DB2 to suppress the warning. Here's a slightly adjusted version that does not trigger the warning: ``` with dummy(id) as ( select 2 from SYSIBM.SYSDUMMY1 union all select id + 1 from dummy where id < 4 ) select id from dummy ```
I managed to write a recursive query that fits : ``` with dummy(id) as ( select 2 from SYSIBM.SYSDUMMY1 union all select id + 1 from dummy where id + 1 between 2 and 4 ) select id from dummy ``` The query can be adapted to whatever for(;;) you can dream of.
12,243
I know that the wave like nature of the electrons allows the qubits to interfere with each other amplifying correct answers and canceling out wrong answers. But what kind of problems that use this kind of phenomena? I am still a beginner in the field so please point out any mistake I made along the way. And if there are any research papers or articles regarding my question please let me know.
2020/05/30
[ "https://quantumcomputing.stackexchange.com/questions/12243", "https://quantumcomputing.stackexchange.com", "https://quantumcomputing.stackexchange.com/users/12207/" ]
If you look in this [paper](https://arxiv.org/abs/quant-ph/9608006), section 7, they give an [[11,1,5]] code, and show that it is the smallest you can have. In general, for these sorts of questions, a great starting point is [Gottesman's thesis](https://arxiv.org/abs/quant-ph/9705052). That's where I found this result stated.
Another good place to find codes with your desired parameters is this website: <http://www.codetables.de/> The standard format to describe a quantum code is [[n,k,d]], where n is the number of physical qubits whose joint entangled state stores the logical information, k is the number of logical qubits encoded, and d is the distance to which they are protected. The table is n vs k, where the distance d is the # in the box, so the smallest distance-5 code is the (11,1) entry
35,867,304
I can't get the finalList filled to use in my html file, it wil run the code to fill it before the promise all code. I need to use this array in my html document so it has to be a this.variable I am using Aurelia. ```js activate() { var repoList = []; var repos = this.http.fetch({Link to github api}) .then(response => response.json()) .then(repos => this.repos = repos); var trello = new Trello; trello.getBoards().then(boardList => this.boards = boardList); var boards = trello.getBoards(); //add github repo to the associated trello board (works) Promise.all([boards, repos]).then(function(values) { var count = 0; for (var i in values[0]) { for (var a in values[1]) { if (values[1][a].hasOwnProperty("name")) { var repo = values[1][a].name.toLowerCase(); var board = values[0][i]['name'].toLowerCase(); repoList[count] = repo; count++; if (repo == board) { console.log(repo + " " + board) } } } } }); //this list is always empty (The problem) this.finalList = repoList; this.title = "Trello Boards"; } ```
2016/03/08
[ "https://Stackoverflow.com/questions/35867304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6034220/" ]
Something like this should do it. Hard to decipher what's going on in the for loops. ```js activate() { let reposPromise = this.http.fetch({Link to github api}) .then(response => response.json()); let boardsPromise = new Trello().getBoards(); return Promise.all([boardsPromise, reposPromise]) .then(([boards, repos]) => { this.boards = boards; this.repos = repos; this.finalList = []; for (var i in boards) { for (var a in repos) { if (values[1][a].hasOwnProperty("name")) { var repo = values[1][a].name.toLowerCase(); var board = values[0][i]['name'].toLowerCase(); this.finalList.push(repo); if (repo == board) { console.log(repo + " " + board) } } } } }); this.title = "Trello Boards"; } ```
I believe Your `finalList` should be set inside the promise handler. Like this. ``` activate() { var repoList = []; //I always use this, and I am not sure what do you mean //by this.finalList, but still I assume you know what you are doing //And hence I use this! var that = this; var repos = this.http.fetch({Link to github api}) .then(response => response.json()) .then(repos => this.repos = repos); var trello = new Trello; trello.getBoards().then(boardList => this.boards = boardList); var boards = trello.getBoards(); //add github repo to the associated trello board (works) Promise.all([boards, repos]).then(function(values) { var count = 0; for (var i in values[0]) { for (var a in values[1]) { if (values[1][a].hasOwnProperty("name")) { var repo = values[1][a].name.toLowerCase(); var board = values[0][i]['name'].toLowerCase(); repoList[count] = repo; count++; if (repo == board) { console.log(repo + " " + board) }; } }; }; //I believe when promise resolves. You should set the repoList. that.finalList = repoList; that.title = "Trello Boards"; }); } ``` My question is, do you really wanna set title and finalList to `this`? Just asking. Hope this helps!
21,445,341
It seems that `ic_launcher.png` is the canonical name for launcher icons for Android apps. What does "ic" stand for? My guess is "icon", but that's kind of a strange way to abbreviate it, so I'm wondering if it's something else?
2014/01/30
[ "https://Stackoverflow.com/questions/21445341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/631051/" ]
Your assumption is right. The "ic" stands for "icon".
"It's a 48×48 pixel png file called ic\_launcher.png (ic for icon, launcher for the launcher screen)"
21,445,341
It seems that `ic_launcher.png` is the canonical name for launcher icons for Android apps. What does "ic" stand for? My guess is "icon", but that's kind of a strange way to abbreviate it, so I'm wondering if it's something else?
2014/01/30
[ "https://Stackoverflow.com/questions/21445341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/631051/" ]
Your assumption is right. The "ic" stands for "icon".
From Android's [Icon Design Guidelines: Use common naming conventions for icon assets](https://developer.android.com/guide/practices/ui_guidelines/icon_design#use-common-naming-conventions-for-icon-assets), "ic" stands for "icon".
21,445,341
It seems that `ic_launcher.png` is the canonical name for launcher icons for Android apps. What does "ic" stand for? My guess is "icon", but that's kind of a strange way to abbreviate it, so I'm wondering if it's something else?
2014/01/30
[ "https://Stackoverflow.com/questions/21445341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/631051/" ]
From Android's [Icon Design Guidelines: Use common naming conventions for icon assets](https://developer.android.com/guide/practices/ui_guidelines/icon_design#use-common-naming-conventions-for-icon-assets), "ic" stands for "icon".
"It's a 48×48 pixel png file called ic\_launcher.png (ic for icon, launcher for the launcher screen)"
59,359,100
I have the folowing list : ```py l = [ 'D111_26680270__2019_10.xml', 'D111_26680270__2019_10_generat.PDF', 'D111_26680270__2019_10_generat.xdp', 'D111_32338396__2019_10.xml', 'D111_32338396__2019_10_generat.PDF', 'D111_32338396__2019_10_generat.xdp', 'D111_40037513__2019_10_generat.pdf', 'D111_31123410__2019_10.xml', 'D111_31123410__2019_10_generat.PDF', 'D111_31123410__2019_10_generat.xdp' ] ``` How do i get a list with only the number after `'D111_'` like `'26680270'` and `'40037513'` from all the examples in the list? Thank you.
2019/12/16
[ "https://Stackoverflow.com/questions/59359100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12524425/" ]
You can do this using `str.split` in a list comprehension ``` >>> data = ['D111_26680270__2019_10.xml', 'D111_26680270__2019_10_generat.PDF', 'D111_26680270__2019_10_generat.xdp', 'D111_32338396__2019_10.xml', 'D111_32338396__2019_10_generat.PDF', 'D111_32338396__2019_10_generat.xdp', 'D111_40037513__2019_10_generat.pdf', 'D111_31123410__2019_10.xml', 'D111_31123410__2019_10_generat.PDF', 'D111_31123410__2019_10_generat.xdp'] >>> [i.split('_')[1] for i in data] ['26680270', '26680270', '26680270', '32338396', '32338396', '32338396', '40037513', '31123410', '31123410', '31123410'] ```
As you have fixed number used slicing it's efficient and simple way ```py >>> data = ['D111_26680270__2019_10.xml', 'D111_26680270__2019_10_generat.PDF', 'D111_26680270__2019_10_generat.xdp', 'D111_32338396__2019_10.xml', 'D111_32338396__2019_10_generat.PDF', 'D111_32338396__2019_10_generat.xdp', 'D111_40037513__2019_10_generat.pdf', 'D111_31123410__2019_10.xml', 'D111_31123410__2019_10_generat.PDF', 'D111_31123410__2019_10_generat.xdp'] >>> [item[5:13] for item in data] ['26680270', '26680270', '26680270', '32338396', '32338396', '32338396', '40037513', '31123410', '31123410', '31123410'] ```
33,539,239
I'm trying to automate my Test Cases using Selenium for an OBIEE application. Now, I need to read a value from a tabular report generated. The problem is, the ID of the last cell where the total is, keeps on changing. For example- Currently the id is: db\_saw\_9270\_6\_1610\_0. After refreshing, the ID becomes something else. The 4 numbers in between (9270) changes. The remaining bit are the same. I'm using the following logic to capture this element: ``` driver.findElement(By.xpath(".//*[contains(@id, '_6_1610_0')]")).getText(); ``` But, it is returning org.openqa.selenium.NoSuchElementException: Unable to locate element: Please tell me where did I go wrong and what should I do?
2015/11/05
[ "https://Stackoverflow.com/questions/33539239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3934294/" ]
ANSWER UPADTED: The problem with your code is that the submit event occurs even before ajax is called. The following changes have been done in your code HTML ``` <form method="post" action="sub.php" name="myform" id="myform"> <input type="text" name="name" id="test_txt"> <input type="text" name="code_r" id="code_r"> <input type="button" name="_mail" value="send" onclick="return send_mail_test()" > </form> <br><hr><br> <form method="post" action="xyz.php" name="anotherform" id="anotherform"> <input type="button" name="change" value="Change action of above form" onclick="changeformaction();" > </form> ``` The onsubmit on the form is removed & the submit button is changed to normal button. The send\_mail\_test() function is called on the Send button now. JAVASCRIPT ``` <script> function send_mail_test() { var txt = $("#test_txt").val(); if (txt != "") { $.ajax({ url : "chckvar.php", type : "POST", //async : false, dataType : "JSON", data : { send_mail : 1, txt_val : txt }, success : function(data) { $('#code_r').val(data.a); $('#myform').submit(); } }); }else{ alert("please enter some text"); return false; } } function changeformaction(){ $("#myform").prop('action','newaction.php'); $('#myform').submit(); } </script> ``` Here a small change is made in ajax success callback , after the response is received and the value is set in the input , the form is made to submit then. No change is needed in your ajax file.
Try this: ``` <script> $(function () { $('form[name="myform"]').on('submit', function (e) { e.preventDefault(); var txt = $(this).find("#test_txt").val(); if (txt.length > 0) { $.ajax({ url: "chckvar.php", type: "POST", //async : false, dataType: "JSON", data: { send_mail: 1, txt_val: txt }, success: function (data) { $('#code_r').attr('value', data.a); //$('#code_r').val(data.a); $(this).submit() } }); } else alert("please enter some text"); }); }); </script> <form method="post" action="sub.php" name="myform"> <input type="text" name="name" id="test_txt"> <input type="text" name="code_r" id="code_r"> <input type="submit" name="_mail" value="send" > </form> ```
5,745
Do frames in emacs have a handle the way buffers do? In particular, can I specify that a particular file should be opened in a specified frame? I would like to have two frames where I use one for development and use the other to read documentation and browse tags. (Tagging the question with emacsclient and linux because I am ok with an answer which requires them.)
2014/12/26
[ "https://emacs.stackexchange.com/questions/5745", "https://emacs.stackexchange.com", "https://emacs.stackexchange.com/users/2536/" ]
I think you may want your opened frame in control. If you make certain files automatically opened in another frames, then when you open more than one it will create many frames that becomes unmanageable and defeats your purpose. Since you use Helm and if you use any Helm Projectile command or `helm-find-files` or `helm-mini`... (Helm commands that are related to files), `C-c C-o` opens the selected files/buffers in another frames. For vanilla Emacs solution, anything prefixed with `C-x 5` opens file/buffer in another frame. But you can use another method to achieve your purpose. You can use package like [workgroup](https://github.com/tlh/workgroups.el) to manage your window configurations. What `workgroup` does is allows you to create workspaces, each workspace holds a window configuration with its buffers and you can switch between window configurations easily and persist the workspaces across Emacs sessions. Of course, you can use it along with frame as well, i.e. each frame holds a workspace. Here is my configuration: ``` (setq wg-prefix-key (kbd "C-c v")) (setq wg-morph-on nil ; disable switching animation wg-no-confirm t ; don't ask for confirmation wg-file (concat user-emacs-directory "workgroups") ; save your workspaces in ~/.emacs.d/wokgroups for future sessions wg-switch-on-load nil ; don't switch to first workgroup when it is loaded ) (global-set-key (kbd "C-c c") 'wg-create-workgroup) (global-set-key (kbd "C-c b") 'wg-switch-to-workgroup) (require 'workgroups) (workgroups-mode 1) ``` Why did I choose such key bindings? Because the three keys are close together. `C-c c` and `C-c b` should be frequently used commands when you use `workgroups`, and `C-c v` is for everything else. And the three are close with each other on the keyboard, which makes it easy to remember and fast to work with `workgroups`: `c` `v` `b`. Now, let's try create a workgroup with `C-c c`. Create 3 or 4 windows t hat hold something. Then, create another workgroup with `C-c c`. Also create 3 or 4 windows t hat hold something. Now you can switch back and forth with `C-c v a` between current and previous workgroups. If you want to go next/previous workgroup, use `C-c v n` and `C-c v p`. Basically, `workgroups` is the same as how Emacs handles frames in terminal, which I think is the missing feature in GUI Emacs that I was always wishing for. If you have more than 2 workgroups and want to select one deterministically, press `C-c b`. Since you use Helm, you get a nice and visible list of workgroups. To persist your workgroups between session, you can use `C-c v S` to save all your workgroups into the `wg-file` you defined earlier. You can restore it later with `C-c v C-l`, or automatically when your Emacs starts: ``` (defun wg-load-default () "Run `wg-load' on `wg-file'." (interactive) (when (file-exists-p wg-file) (wg-load wg-file))) ``` Finally, to navigate frame easier, you can select frame by name with `select-frame-by-name` command. I bound it to `C-x 5 s` ``` (global-set-key (kbd "C-x 5 s") 'select-frame-by-name) ``` Again, it gives you a nice visible list with Helm. You can cycle between frames with `C-x 5 o`, similar to how you cycle windows.
I think it's a bit of wasted effort of trying to make this arrangement, i.e. docs in one frame and code in the other. This is because all Emacs frames share the buffers anyway, so all your arranging comes to naught with a single `ido-switch-buffer`. But when that happens, [ace-window](https://github.com/abo-abo/ace-window) can help you restore the balance. Either `C-u` `ace-window`, or a plain `ace-swap-window` can swap the windows on separate frames.
5,745
Do frames in emacs have a handle the way buffers do? In particular, can I specify that a particular file should be opened in a specified frame? I would like to have two frames where I use one for development and use the other to read documentation and browse tags. (Tagging the question with emacsclient and linux because I am ok with an answer which requires them.)
2014/12/26
[ "https://emacs.stackexchange.com/questions/5745", "https://emacs.stackexchange.com", "https://emacs.stackexchange.com/users/2536/" ]
You can customize `display-buffer-alist` to achieve what you want, you can read more about the variable by doing `C-h``v``display-buffer-alist``RET`. Basically this variable allows you to register custom functions to display certain buffers. Below if a non-generic solution to your question. I have assumed certain things, you might want to adopt it your workflow, the assumptions are the buffer containing your documentation match the regexp `Help`, and you want to display them in a dedicated frame `Help`. ``` (defun my-show-doc-in-frame (buffer options) ;; Get the frame named 'Help' or create one if such a frame does not exist (let ((help-frame (select-frame (or (cdr (assoc-string "Help" (make-frame-names-alist))) (make-frame '((name . "Help"))))))) ;; This assumes you want to display just one window in the dedicated frame (set-window-buffer (car (window-list help-frame)) buffer nil))) (add-to-list 'display-buffer-alist (cons "Help" (cons #'my-show-doc-in-frame nil))) ``` Now if you do `C-h``v``display-buffer-alist``RET`, the documentation will appear in a frame called 'Help'
I think it's a bit of wasted effort of trying to make this arrangement, i.e. docs in one frame and code in the other. This is because all Emacs frames share the buffers anyway, so all your arranging comes to naught with a single `ido-switch-buffer`. But when that happens, [ace-window](https://github.com/abo-abo/ace-window) can help you restore the balance. Either `C-u` `ace-window`, or a plain `ace-swap-window` can swap the windows on separate frames.
5,745
Do frames in emacs have a handle the way buffers do? In particular, can I specify that a particular file should be opened in a specified frame? I would like to have two frames where I use one for development and use the other to read documentation and browse tags. (Tagging the question with emacsclient and linux because I am ok with an answer which requires them.)
2014/12/26
[ "https://emacs.stackexchange.com/questions/5745", "https://emacs.stackexchange.com", "https://emacs.stackexchange.com/users/2536/" ]
You can customize `display-buffer-alist` to achieve what you want, you can read more about the variable by doing `C-h``v``display-buffer-alist``RET`. Basically this variable allows you to register custom functions to display certain buffers. Below if a non-generic solution to your question. I have assumed certain things, you might want to adopt it your workflow, the assumptions are the buffer containing your documentation match the regexp `Help`, and you want to display them in a dedicated frame `Help`. ``` (defun my-show-doc-in-frame (buffer options) ;; Get the frame named 'Help' or create one if such a frame does not exist (let ((help-frame (select-frame (or (cdr (assoc-string "Help" (make-frame-names-alist))) (make-frame '((name . "Help"))))))) ;; This assumes you want to display just one window in the dedicated frame (set-window-buffer (car (window-list help-frame)) buffer nil))) (add-to-list 'display-buffer-alist (cons "Help" (cons #'my-show-doc-in-frame nil))) ``` Now if you do `C-h``v``display-buffer-alist``RET`, the documentation will appear in a frame called 'Help'
I think you may want your opened frame in control. If you make certain files automatically opened in another frames, then when you open more than one it will create many frames that becomes unmanageable and defeats your purpose. Since you use Helm and if you use any Helm Projectile command or `helm-find-files` or `helm-mini`... (Helm commands that are related to files), `C-c C-o` opens the selected files/buffers in another frames. For vanilla Emacs solution, anything prefixed with `C-x 5` opens file/buffer in another frame. But you can use another method to achieve your purpose. You can use package like [workgroup](https://github.com/tlh/workgroups.el) to manage your window configurations. What `workgroup` does is allows you to create workspaces, each workspace holds a window configuration with its buffers and you can switch between window configurations easily and persist the workspaces across Emacs sessions. Of course, you can use it along with frame as well, i.e. each frame holds a workspace. Here is my configuration: ``` (setq wg-prefix-key (kbd "C-c v")) (setq wg-morph-on nil ; disable switching animation wg-no-confirm t ; don't ask for confirmation wg-file (concat user-emacs-directory "workgroups") ; save your workspaces in ~/.emacs.d/wokgroups for future sessions wg-switch-on-load nil ; don't switch to first workgroup when it is loaded ) (global-set-key (kbd "C-c c") 'wg-create-workgroup) (global-set-key (kbd "C-c b") 'wg-switch-to-workgroup) (require 'workgroups) (workgroups-mode 1) ``` Why did I choose such key bindings? Because the three keys are close together. `C-c c` and `C-c b` should be frequently used commands when you use `workgroups`, and `C-c v` is for everything else. And the three are close with each other on the keyboard, which makes it easy to remember and fast to work with `workgroups`: `c` `v` `b`. Now, let's try create a workgroup with `C-c c`. Create 3 or 4 windows t hat hold something. Then, create another workgroup with `C-c c`. Also create 3 or 4 windows t hat hold something. Now you can switch back and forth with `C-c v a` between current and previous workgroups. If you want to go next/previous workgroup, use `C-c v n` and `C-c v p`. Basically, `workgroups` is the same as how Emacs handles frames in terminal, which I think is the missing feature in GUI Emacs that I was always wishing for. If you have more than 2 workgroups and want to select one deterministically, press `C-c b`. Since you use Helm, you get a nice and visible list of workgroups. To persist your workgroups between session, you can use `C-c v S` to save all your workgroups into the `wg-file` you defined earlier. You can restore it later with `C-c v C-l`, or automatically when your Emacs starts: ``` (defun wg-load-default () "Run `wg-load' on `wg-file'." (interactive) (when (file-exists-p wg-file) (wg-load wg-file))) ``` Finally, to navigate frame easier, you can select frame by name with `select-frame-by-name` command. I bound it to `C-x 5 s` ``` (global-set-key (kbd "C-x 5 s") 'select-frame-by-name) ``` Again, it gives you a nice visible list with Helm. You can cycle between frames with `C-x 5 o`, similar to how you cycle windows.
61,542,932
Hi I am studying and trying to make my website mobile responsive and no matter what I try have had no luck. So I have tried a range of ways to turn a menu into a mobile menu when I resize. I have also been trying to get the content to centre properly when in smaller screen. I have googled alot and worked out most now I just need help finishing it off properly. Edit: Updated code as per request @<https://stackoverflow.com/users/13447870/tobias-kristensen> ```js /* Toggle between showing and hiding the navigation menu links when the user clicks on the hamburger menu / bar icon */ function myFunction() { var x = document.getElementById("myLinks"); if (x.style.display === "block") { x.style.display = "none"; } else { x.style.display = "block"; } } ``` ```css /* Main Body */ body { background-image: url(Image/footballField.jpg); background-repeat: no-repeat; background-attachment: fixed; min-height: 100hv; min-width: 100hv; background-size: 100% 100%; font-family: "Lucinda Sans", "Arial", sans-serif; text-decoration: none; color: black } /*Header with logo*/ #header { text-align: center; margin-bottom: 20px; margin-top: 20px; padding: 10px; } #container1 { position: relative; background-color: #FFFFFF; position: absolute; min-height: 100vh; width: 70%; margin-left: 15%; margin-right: 15%; padding-bottom:120px; } /* footer for all pages */ #footer { position: absolute; clear: both; color: white; text-align: center; padding-top: 20px; padding-bottom: 20px; font-weight: 300; bottom: 0; background: linear-gradient(to bottom, #C61618 5%, black 100%); width: 100%; height: 100px; /* Footer height */ } .fa-facebook { padding: 10px; font-size: 30px; width: 50px; text-align: center; text-decoration: none; background: #3B5998; color: white; margin-right: 50px; border-radius: 30%; } /* Facebook Icon and link in Footer */ * { box-sizing: border-box; } /*Search Field */ input:focus, textarea:focus, select:focus { outline-color: #C61618; }/* Search Area on Header */ form.search input[type=text] { padding: 10px; font-size: 17px; border: 1px solid black; float: right; width: 20%; background: white; margin-right: 5%; } /* Style the search field from W3Schools*/ form.search button { float: right; width: 5%; padding: 10px; background: #C61618; color: white; font-size: 17px; border: 1px solid black; border-right: none; /* Prevent double borders */ cursor: pointer; } /* Style the submit button from W3Schools */ form.search button:hover { background: #C61618; } /* Search button hover */ form.search::after { content: ""; clear: both; display: table; } /* Clear floats on Search from W3Schools */ /*Nav Bar*/ #navbar { position: relative; margin-top: 40px; margin-right: 5%; margin-left: 8%; }/*Main White Background*/ li a { display: inline; text-decoration: none; color: white; font-size: 16px; } /*link look on Nav Bar */ #navbar ul li { list-style-type: none; display: inline; padding: 15px; text-align: center; border-radius: 30px; /*curved corners on buttons*/ background: linear-gradient(to bottom, #C61618 5%, black 100%); } /*Menu look*/ #navbar ul li:hover { background: black; } /*Menu hover Colour*/ #navbar .btn.active { background: black; } /*Menu active Colour*/ /* Text Styling */ p, h2, a { text-decoration: none; color: black; } /*all paragraph text*/ h1 { text-align: center; margin-top: 5%; }/*position of h1*/ h2 { text-align: center; margin-top: 5%; text-decoration: none; color: black; } /*position of h2*/ h4 a { text-decoration: none; color: black; } p { margin-left: 50px; margin-right: 50px; text-align: justify-all; line-height: 150%; } /*format text <p> */ /*Index Page*/ #image_index { padding-top: 41px; float: left; margin-left: 30px; margin-bottom: 30px; max-width: 30% } /* Image on home page format */ #image_contact { padding-top: 41px; float: left; margin-left: 30px; margin-bottom: 30px; } /* Image on home page format */ #index_table { float: right; padding-right: 10px; padding-bottom: 30px; margin-right: 5%; } /* Table Index Page format */ /*Competitions Page */ table.c { table-layout: auto; width: 80%; margin-left: auto; margin-right: auto; margin-bottom: 30px; } .competition_table p { text-align: center; margin-left: auto; margin-right: auto; }/* format for <p> Competitions Page */ th { text-emphasis: bold; font-size: 20px; height: 10px; background-color: lightgrey; border-color: black; } /* Table Header*/ table, th, td { padding: 10px; border-style: solid; border-color: black; border-width: thin; border-collapse: collapse; } /* Contact Us Page */ #secretary { padding-top: 41px; float: left; margin-left: 30px; margin-bottom: 30px; } .column1 { float: left; width: 40%; padding: 10px; } .right { width: 75%; } .row:after { /* Clear floats after the columns */ content: ""; display: table; clear: both; } #contact_form { float: right; padding-right: 10px; padding-bottom: 30px; margin-right: 5%; width: 50%; } * { box-sizing: border-box; } /*format for Contact Us form*/ input[type=text], [type=email], [type=tel], select, textarea, email { width: 100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; resize: vertical; } /*format for Contact Us form*/ label { padding: 12px 12px 12px 0; display: inline-block; } /*format for Contact Us form*/ input[type=submit] { background-color: black; color: white; padding: 12px 20px; border: none; border-radius: 4px; cursor: pointer; float: right; font-size: 20px; font-weight: bold; } /*format for Contact Us form*/ input[type=submit]:hover { background-color: #C61618; } /*format for Contact Us form*/ .col-25 { float: left; width: 25%; margin-top: 6px; } .col-75 { float: left; width: 75%; margin-top: 6px; } /*Merch Page*/ .merch_order_form { clear:both; text-align: left; margin-bottom: 5%; margin-right: 5%; margin-left: 5%; padding:10px; } .col-50 { float: left; width: 40%; margin-left: 10%; align-content: inline; text-align: center; } /*Column setout for Merch & Information Pages*/ .col-45 { float: right; width: 40%; margin-right: 10%; align-content: inline; text-align: center; } /*Column setout for Merch & Information Pages*/ .row:after { content: ""; display: table; clear: both; } /* Clear floats after the columns */ input[type=submit_merch] { background-color: black; color: white; text-align: center; padding: 12px 20px; font-size: 30px; border-radius: 30px; cursor: pointer; margin-left: 30%; margin-top: 10px; } /* Merch Page Submit Button */ input[type=submit_merch]:hover { background: linear-gradient(to bottom, #C61618 5%, black 100%); } /* Merch Page hover change */ #subject { font-size: 16px; } /* Registration Page Submit Button */ .myButton { box-shadow: inset 0px 0px 0px 2px #0154FA; background: linear-gradient(to bottom, #0154FA 5%, #283966 100%); background-color: #0154FA; border-radius: 30px; border: 1px solid #4e6096; display: inline-block; cursor: pointer; color: #ffffff; font-size: 28px; font-weight: bold; padding: 21px 76px; text-decoration: none; text-shadow: 0px 0px 0px #283966; text-align: center; margin-left: 35%; margin-right: auto; margin-bottom: 70px; } /* Merch Page Registration Button */ .myButton:hover { background: linear-gradient(to bottom, #C61618 5%, black 100%); background-color: #C61618; border: 1px solid #C61618; box-shadow: inset 0px 0px 0px 2px #C61618; } /* Merch Page Registration Button */ .myButton:active { position: relative; top: 1px; } /* Merch Page Registration Button */ @media screen and (min-width: 800px) { .column { width: 100%; background-image: disabled; .navbar li, .navbar li a:last-child { display: none !important; visibility: hidden !important; } } } /* Responsive layout - when the screen is less than 600px wide, make the two columns stack on top of each other instead of next to each other */ @media screen and (max-width: 800px) { background-image: disabled; .mobile_navbar li, .mobile_navbar li:last-child { display: none !important; visibility: hidden !important; font-family: "Lucinda Sans", "Arial", sans-serif; text-decoration: none; color: black; text-align: right; } .col-25, .col-75, .col-50, .col-45, input[type=submit] input [type=submit_merch] { width: 100%; margin-top: 0; margin-left: auto; margin-right: auto; } #body { background-color: white; margin: 0px; } } #container1 { margin="0px"; background-color: ="white"; } #mobile_navbar { display:flex; margin-left: 100px; display: inline; } .mobile-container { min-width: 370px; margin: auto; padding: auto; background-color: white; height: 500px; color: black; border-radius: 10px; } /* TopNav Menu Code from W3Schools.com Dropdown Button */ .dropbtn { background-color: #C61618; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer display: block; position: absolute; right: 0; top: 0; } /* Dropdown button on hover & focus */ .dropbtn:hover, .dropbtn:focus { background-color: black; } /* The container <div> - needed to position the dropdown content */ .dropdown { position: relative; display: inline-block; } /* Dropdown Content (Hidden by Default) */ .dropdown-content { display: none; position: absolute; background-color: black; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } /* Links inside the dropdown */ .dropdown-content a { color: white; padding: 12px 16px; text-decoration: none; display: block; } /* Change color of dropdown links on hover */ .dropdown-content a:hover {background-color: #C61618} /* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */ .show {display:block;} ``` ```html <!DOCTYPE html> <!-- Contact Us page for OaklandFC --> <html lang="en-US"> <head> <title>Oakland Football Club</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta content='width=device-width, initial-scale=1' name='viewport' /> <meta name="viewport" content="minimum-scale=0"> <meta name="viewport" content="user-scalable=yes"> <meta charset="UTF-8"> <meta name="description" content="Oakland Football Club"> <meta name="keywords" content="Football, Soccer, Oakland, Club, family"> <meta name="author" content="Simply Designed for You"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="Oaklandstyle.css" /> <script src="formValidation.js"></script> <script src="jquery-3.5.0.js" type="text/javascript"></script> </head> <body> <div id="container1"> <div id="content-wrap"> <div id="header"> <img src="Image/logo.png" alt="Oakland Football logo" /> <form class="search" action="action_page.php"> <!--from W3Schools --> <input type="text" placeholder="Search.." name="search"> <button type="submit"><i class="fa fa-search"></i></button> </form> </div> <div id="navbar"> <ul> <li class="btn"><a href="index.html">Home</a></li> <li class="btn"><a href="Competitions.html">Competitions</a></li> <li class="btn"><a href="Registration.html">Registration</a></li> <li class="btn"><a href="Merchandise.html">Merchandise</a></li> <li class="btn"><a href="Sponsors.html">Sponsors</a></li> <li class="btn"><a href="Information.html">Information</a></li> <li class="btn active"><a href="Contact%20Us.html">Contact Us</a></li> </ul> </div> <div id="mobile_navbar"> <div class="dropdown"> <button onclick="myFunction()" class="dropbtn">Menu</button> <div id="myDropdown" class="dropdown-content"> <a href="index.html">Home</a> <a href="Competitions.html">Competitions</a> <a href="Registration.html">Registration</a> <a href="Merchandise.html">Merchandise</a> <a href="Information.html">Information</a> <a href="Contact%20Us.html">Contact Us</a> </div> </div> </div> <div id="content"> <div id="text"> <h1>Contact Us</h1> </div> <div class="column1"> <h2>Secretary</h2> <p>Name: Laci Tanner </p> <p>Phone: 02 - 6620 3324</p> <p>Email: <a href="mailto:[email protected]?Subject=Contact%from%Website" target="_top">[email protected]</a></p> <br> <div id="image_contact" show="@media screen and (max-width: 800px)"> <img src="Image/soccer.jpg" alt="Oakland Football Team Photo" width="380px"/> </div> </div> <div class="column2"> <h2>Contact Us</h2> <form action="mailto:[email protected]" method="post" enctype="text/plain"> <div id="contact_form"> <div class="row"> <div class="col-25"> <label for="fname">First Name</label> </div> <div class="col-75"> <input type="text" id="fname" name="firstname" placeholder="Your name" required> </div> </div> <div class="row"> <div class="col-25"> <label for="email">Email</label> </div> <div class="col-75"> <input type="email" id="email" name="email" placeholder="Your email address" required> </div> </div> <div class="row"> <div class="col-25"> <label for="tel">Phone Number</label> </div> <div class="col-75"> <input type="tel" id="tel" name="tel" placeholder="Your phone number" required> </div> </div> <div class="row"> <div class="col-25"> <label for="team">Team</label> </div> <div class="col-75"> <select id="team" name="team"> <option value="PleaseChoose">Please Choose</option> <option value="Adults">Adults</option> <option value="Under%12s">Under 12s</option> <option value="Under%6s">Under 6s</option> <option value="Other">Other</option> </select> </div> </div> <div class="row"> <div class="col-25"> <label for="I%am">I am</label> </div> <div> <form action="/action_page.php"> <input type="radio" id="thinking" name="member" value="thinking"> <label for="thinking">Thinking about joining the club</label><br> <input type="radio" id="member" name="member" value="member"> <label for="member">Already a member</label><br> <br> </form></div> </div> <div class="row"> <div class="col-25"> <label for="subject">Message</label> </div> <div class="col-75"> <textarea id="subject" name="subject" placeholder="Message" required style="height:200px"></textarea> </div> </div> <div class="row"> <input type="submit" value="Send"> </div> </div> </form> </div> </div> </div> <footer id="footer"> <a href="#" class="fa fa-facebook"></a> Copyright &copy; 2020 Simply Designed For You </footer> </div> </body></html> ``` So this is how it shows when I add it all together. Both menu's and columns not stacking.
2020/05/01
[ "https://Stackoverflow.com/questions/61542932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13447516/" ]
You can access the url by typing `zappa status <stage>`, where `<stage>` is probably something like `dev`. See also <https://github.com/Miserlou/Zappa#status> for details. The printout will have your url as well as other status details of your lambda function. This works provided you give full permission access to the IAM user (for testing purpose only) though.
I had to configure my zappa\_settigs.json by adding these lines: ``` "apigateway_enabled": true, "manage_roles": true, "cors": true, **so the final zappa settings:** { "dev": { "django_settings": "zappatest.settings", "apigateway_enabled": true, "manage_roles": true, "role_arn": "Role_name", "role_arn": "arn_name", "profile_name": "default", "project_name": "project_name", "runtime": "python3.8", "s3_bucket": "bucket_name", "aws_region": "region_name", "cors": true, } } ```
51,576,905
I am using NSCoding and NSArchiver to persist my iOS App Data. But I want to know if it is equivalent to using zip / unzip software? If not, how does it work?
2018/07/29
[ "https://Stackoverflow.com/questions/51576905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8637708/" ]
You can read the [docs](https://developer.apple.com/documentation/foundation/nsarchiver) to get a rough idea of how `NSArchiver` works: > > [...] provides a way to encode objects into an architecture-independent format that can be stored in a file > > > Basically, it converts an object in memory (and all the other objects that it references, and the objects that those objects references... i.e. "object graph") into a file that can be stored in a file. This is not the same as compression. `NSArchiver` simply encodes your objects into some format (binary, XML etc.). Compression would be to make that encoded binary file smaller. See this [post](https://stackoverflow.com/q/45657962/5133585) for how to compress files.
In effect, it is a property list. That is why NSKeyedArchiver has an `outputFormat` property that can be an XML property list or a binary property list. See the documentation on the PropertyListSerialization class for more about what that means. You can actually write an archive to disk, open it as XML, and read it.
20,813,881
Seeking best inputs on correct usage of C# using statement. Can I use `using` statement on a parameter object as in the following uncommon example code snippet (viz., multi-layer application)? Although the code snippet is different from what I feel that the using statement should be in `ProcessFileAndReturnNumberFromStream()` method of 'Business' class. Why is it an uncommon practice to use using statement on object passed via parameter? Please correct or elaborate on the flaw? ``` using System; using System.IO; class Data { public double? GetNumberFromStream(StreamReader sr) { double? number; try { using (sr) { number = Convert.ToDouble(sr.ReadToEnd()); return number; } } finally { number = null; } } } class Business { public double? ProcessFileAndReturnNumberFromStream() { string fileName = "Test.txt"; StreamReader sr = new StreamReader(fileName); Data dat = new Data(); return dat.GetNumberFromStream(sr); } } class GUI { static void Main() { Business bus = new Business(); double? number = bus.ProcessFileAndReturnNumberFromStream(); Console.WriteLine(number); Console.ReadKey(); } } ``` Please help. Thanks
2013/12/28
[ "https://Stackoverflow.com/questions/20813881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1660166/" ]
If a method is passed an object that implements `IDisposable`, it's *usually* the responsibility of the caller to manage the lifetime of that object, rather than the callee. ``` public double? ProcessFileAndReturnNumberFromStream() { string fileName = "Test.txt"; Data dat = new Data(); using (StreamReader sr = new StreamReader(fileName)) { return dat.GetNumberFromStream(sr); } } ```
> > Can I use using statement on a parameter object as in the following uncommon example code snippet (viz., multi-layer application)? > > > You can, but it's generally odd to do so. Usually whatever is creating the `StreamReader` would be expecting to "own" it and dispose of it when they're done with it. It would be more usual for your `ProcessFileAndReturnNumberFromStream` method to be: ``` using (StreamReader sr = new StreamReader(fileName)) { Data dat = new Data(); return dat.GetNumberFromStream(sr); } ``` (Although I'd personally use `File.OpenText` instead of explicitly constructing the `StreamReader`.) Your `GetNumberFromStream` method would then not need the `using` statement. It also doesn't need the `try/finally` block at all - it's an odd implementation all round, given that it will never return null, either... It's also odd that you're creating a new instance of `Data` and then doing nothing with it - as your `GetNumberFromStream` method doesn't use an instance variables or override a base class method, you should consider making it static.
20,813,881
Seeking best inputs on correct usage of C# using statement. Can I use `using` statement on a parameter object as in the following uncommon example code snippet (viz., multi-layer application)? Although the code snippet is different from what I feel that the using statement should be in `ProcessFileAndReturnNumberFromStream()` method of 'Business' class. Why is it an uncommon practice to use using statement on object passed via parameter? Please correct or elaborate on the flaw? ``` using System; using System.IO; class Data { public double? GetNumberFromStream(StreamReader sr) { double? number; try { using (sr) { number = Convert.ToDouble(sr.ReadToEnd()); return number; } } finally { number = null; } } } class Business { public double? ProcessFileAndReturnNumberFromStream() { string fileName = "Test.txt"; StreamReader sr = new StreamReader(fileName); Data dat = new Data(); return dat.GetNumberFromStream(sr); } } class GUI { static void Main() { Business bus = new Business(); double? number = bus.ProcessFileAndReturnNumberFromStream(); Console.WriteLine(number); Console.ReadKey(); } } ``` Please help. Thanks
2013/12/28
[ "https://Stackoverflow.com/questions/20813881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1660166/" ]
The caller that is passing the instance of IDisposable should be the one to use the `using` statement. If the callee uses it, the object will be disposed while outside the immediate control of the caller who 'owns' the object.
> > Can I use using statement on a parameter object as in the following uncommon example code snippet (viz., multi-layer application)? > > > You can, but it's generally odd to do so. Usually whatever is creating the `StreamReader` would be expecting to "own" it and dispose of it when they're done with it. It would be more usual for your `ProcessFileAndReturnNumberFromStream` method to be: ``` using (StreamReader sr = new StreamReader(fileName)) { Data dat = new Data(); return dat.GetNumberFromStream(sr); } ``` (Although I'd personally use `File.OpenText` instead of explicitly constructing the `StreamReader`.) Your `GetNumberFromStream` method would then not need the `using` statement. It also doesn't need the `try/finally` block at all - it's an odd implementation all round, given that it will never return null, either... It's also odd that you're creating a new instance of `Data` and then doing nothing with it - as your `GetNumberFromStream` method doesn't use an instance variables or override a base class method, you should consider making it static.
20,813,881
Seeking best inputs on correct usage of C# using statement. Can I use `using` statement on a parameter object as in the following uncommon example code snippet (viz., multi-layer application)? Although the code snippet is different from what I feel that the using statement should be in `ProcessFileAndReturnNumberFromStream()` method of 'Business' class. Why is it an uncommon practice to use using statement on object passed via parameter? Please correct or elaborate on the flaw? ``` using System; using System.IO; class Data { public double? GetNumberFromStream(StreamReader sr) { double? number; try { using (sr) { number = Convert.ToDouble(sr.ReadToEnd()); return number; } } finally { number = null; } } } class Business { public double? ProcessFileAndReturnNumberFromStream() { string fileName = "Test.txt"; StreamReader sr = new StreamReader(fileName); Data dat = new Data(); return dat.GetNumberFromStream(sr); } } class GUI { static void Main() { Business bus = new Business(); double? number = bus.ProcessFileAndReturnNumberFromStream(); Console.WriteLine(number); Console.ReadKey(); } } ``` Please help. Thanks
2013/12/28
[ "https://Stackoverflow.com/questions/20813881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1660166/" ]
> > Can I use using statement on a parameter object as in the following uncommon example code snippet (viz., multi-layer application)? > > > You can, but it's generally odd to do so. Usually whatever is creating the `StreamReader` would be expecting to "own" it and dispose of it when they're done with it. It would be more usual for your `ProcessFileAndReturnNumberFromStream` method to be: ``` using (StreamReader sr = new StreamReader(fileName)) { Data dat = new Data(); return dat.GetNumberFromStream(sr); } ``` (Although I'd personally use `File.OpenText` instead of explicitly constructing the `StreamReader`.) Your `GetNumberFromStream` method would then not need the `using` statement. It also doesn't need the `try/finally` block at all - it's an odd implementation all round, given that it will never return null, either... It's also odd that you're creating a new instance of `Data` and then doing nothing with it - as your `GetNumberFromStream` method doesn't use an instance variables or override a base class method, you should consider making it static.
Such API would be extremely troublesome. You would never know whether or not the object passed to a method is disposed inside the method or not. Thus, if this is you who create the object and pass it there, you would also never know whether or not you should dispose the object you have just created and passed to the method or not. I guess then, while this is technically possible, it would promote the bad programming style.
20,813,881
Seeking best inputs on correct usage of C# using statement. Can I use `using` statement on a parameter object as in the following uncommon example code snippet (viz., multi-layer application)? Although the code snippet is different from what I feel that the using statement should be in `ProcessFileAndReturnNumberFromStream()` method of 'Business' class. Why is it an uncommon practice to use using statement on object passed via parameter? Please correct or elaborate on the flaw? ``` using System; using System.IO; class Data { public double? GetNumberFromStream(StreamReader sr) { double? number; try { using (sr) { number = Convert.ToDouble(sr.ReadToEnd()); return number; } } finally { number = null; } } } class Business { public double? ProcessFileAndReturnNumberFromStream() { string fileName = "Test.txt"; StreamReader sr = new StreamReader(fileName); Data dat = new Data(); return dat.GetNumberFromStream(sr); } } class GUI { static void Main() { Business bus = new Business(); double? number = bus.ProcessFileAndReturnNumberFromStream(); Console.WriteLine(number); Console.ReadKey(); } } ``` Please help. Thanks
2013/12/28
[ "https://Stackoverflow.com/questions/20813881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1660166/" ]
If a method is passed an object that implements `IDisposable`, it's *usually* the responsibility of the caller to manage the lifetime of that object, rather than the callee. ``` public double? ProcessFileAndReturnNumberFromStream() { string fileName = "Test.txt"; Data dat = new Data(); using (StreamReader sr = new StreamReader(fileName)) { return dat.GetNumberFromStream(sr); } } ```
Such API would be extremely troublesome. You would never know whether or not the object passed to a method is disposed inside the method or not. Thus, if this is you who create the object and pass it there, you would also never know whether or not you should dispose the object you have just created and passed to the method or not. I guess then, while this is technically possible, it would promote the bad programming style.
20,813,881
Seeking best inputs on correct usage of C# using statement. Can I use `using` statement on a parameter object as in the following uncommon example code snippet (viz., multi-layer application)? Although the code snippet is different from what I feel that the using statement should be in `ProcessFileAndReturnNumberFromStream()` method of 'Business' class. Why is it an uncommon practice to use using statement on object passed via parameter? Please correct or elaborate on the flaw? ``` using System; using System.IO; class Data { public double? GetNumberFromStream(StreamReader sr) { double? number; try { using (sr) { number = Convert.ToDouble(sr.ReadToEnd()); return number; } } finally { number = null; } } } class Business { public double? ProcessFileAndReturnNumberFromStream() { string fileName = "Test.txt"; StreamReader sr = new StreamReader(fileName); Data dat = new Data(); return dat.GetNumberFromStream(sr); } } class GUI { static void Main() { Business bus = new Business(); double? number = bus.ProcessFileAndReturnNumberFromStream(); Console.WriteLine(number); Console.ReadKey(); } } ``` Please help. Thanks
2013/12/28
[ "https://Stackoverflow.com/questions/20813881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1660166/" ]
The caller that is passing the instance of IDisposable should be the one to use the `using` statement. If the callee uses it, the object will be disposed while outside the immediate control of the caller who 'owns' the object.
Such API would be extremely troublesome. You would never know whether or not the object passed to a method is disposed inside the method or not. Thus, if this is you who create the object and pass it there, you would also never know whether or not you should dispose the object you have just created and passed to the method or not. I guess then, while this is technically possible, it would promote the bad programming style.
2,258,768
Is meaning of **"if and only if"** is different in mathematical aspects and English aspect? let's take an example: > > Example:I will go home **if and only if** it is not raining. > > Now according to me in english aspect ,I cannot comment anything about rain if i did not go home, > > but in mathematical aspect, I am sure that it is raining if i didn't go home,because in mathematics **if and only if** represent equivalence logic. > > >
2017/04/30
[ "https://math.stackexchange.com/questions/2258768", "https://math.stackexchange.com", "https://math.stackexchange.com/users/441862/" ]
In Mathematics "if and only if" gives you information about both sides of the sentence. Using your example "I will go home **if and only if** it is not raining." Assuming you did go home we conclude that it's not raining, and the other way around assuming it's not raining we conclude that indeed you did go home. On the other hand in English it's misunderstood and mostly used like a one way arrow. More of a visual example is the arrow that is a symbol for if and only if $$\alpha \leftrightarrow \beta $$ which can also be written as $\alpha \rightarrow \beta$ and $\beta \rightarrow \alpha$ (when $\rightarrow$ represents if)
The ''if'' part tells you that "it's not raining" implies that "you will go home" and equivalently that "you don't go home" implies that "it's raining." I think this is because we didn't usually use if and only if in our lives so just have more caught on the either part (??
2,258,768
Is meaning of **"if and only if"** is different in mathematical aspects and English aspect? let's take an example: > > Example:I will go home **if and only if** it is not raining. > > Now according to me in english aspect ,I cannot comment anything about rain if i did not go home, > > but in mathematical aspect, I am sure that it is raining if i didn't go home,because in mathematics **if and only if** represent equivalence logic. > > >
2017/04/30
[ "https://math.stackexchange.com/questions/2258768", "https://math.stackexchange.com", "https://math.stackexchange.com/users/441862/" ]
In Mathematics "if and only if" gives you information about both sides of the sentence. Using your example "I will go home **if and only if** it is not raining." Assuming you did go home we conclude that it's not raining, and the other way around assuming it's not raining we conclude that indeed you did go home. On the other hand in English it's misunderstood and mostly used like a one way arrow. More of a visual example is the arrow that is a symbol for if and only if $$\alpha \leftrightarrow \beta $$ which can also be written as $\alpha \rightarrow \beta$ and $\beta \rightarrow \alpha$ (when $\rightarrow$ represents if)
There is indeed a mismatch between the way we typically treat the 'if and only if' statement in English (or any other natural language) and the way we treat the logical $\leftrightarrow$. Take the following example: 'Mary lives in France if and only if Mary lives in Germany' In any natural language would immediately say that this statement is false. But if we suppose that Mary lives in Nigeria, then following the logical biconditional, we would evaluate it to $False \leftrightarrow False = True$!
14,511,923
I have a tasks table with a `task_id` column and `parent_id` column for each task. I am trying to build a query that returns for each `task_id`, the number of times this `id` shows in the parent `id` column. I tried this query: ``` SELECT task_id, parent_id, (SELECT COUNT( * ) FROM `tasks` WHERE parent_id = task_id) AS count_parents FROM tasks ``` This query didn't work. I hope the question is clear enough.
2013/01/24
[ "https://Stackoverflow.com/questions/14511923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1079913/" ]
It seems like you want this: ``` SELECT task_id, parent_id, COUNT(parent_id) AS count_parents FROM tasks GROUP BY task_id, parent_id ```
``` SELECT t2.task_id, t2.parent_id, (SELECT COUNT( * ) FROM `tasks` t1 WHERE t1.parent_id = t2.task_id) AS count_parents FROM tasks t2 ``` I think from your question
14,511,923
I have a tasks table with a `task_id` column and `parent_id` column for each task. I am trying to build a query that returns for each `task_id`, the number of times this `id` shows in the parent `id` column. I tried this query: ``` SELECT task_id, parent_id, (SELECT COUNT( * ) FROM `tasks` WHERE parent_id = task_id) AS count_parents FROM tasks ``` This query didn't work. I hope the question is clear enough.
2013/01/24
[ "https://Stackoverflow.com/questions/14511923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1079913/" ]
If you want to include all tasks whether they are ever a parent or not, ``` select tasks.task_id,count(parent.parent_id) from tasks left join tasks parent on tasks.task_id=parent.parent_id group by tasks.task_id; ``` If you want only tasks that are parents, it is trivial: ``` select parent_id,count(*) from tasks group by parent_id; ``` (the latter possibly needing a `where parent_id is not null` or such, depending how you represent tasks that have no parent).
It seems like you want this: ``` SELECT task_id, parent_id, COUNT(parent_id) AS count_parents FROM tasks GROUP BY task_id, parent_id ```
14,511,923
I have a tasks table with a `task_id` column and `parent_id` column for each task. I am trying to build a query that returns for each `task_id`, the number of times this `id` shows in the parent `id` column. I tried this query: ``` SELECT task_id, parent_id, (SELECT COUNT( * ) FROM `tasks` WHERE parent_id = task_id) AS count_parents FROM tasks ``` This query didn't work. I hope the question is clear enough.
2013/01/24
[ "https://Stackoverflow.com/questions/14511923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1079913/" ]
Try this: ``` select task_id,parent_id, count(parent_id) as count_parents from `tasks` group by task_id,parent_id; ``` In this case you need a group by, hope it helps.
``` SELECT t2.task_id, t2.parent_id, (SELECT COUNT( * ) FROM `tasks` t1 WHERE t1.parent_id = t2.task_id) AS count_parents FROM tasks t2 ``` I think from your question
14,511,923
I have a tasks table with a `task_id` column and `parent_id` column for each task. I am trying to build a query that returns for each `task_id`, the number of times this `id` shows in the parent `id` column. I tried this query: ``` SELECT task_id, parent_id, (SELECT COUNT( * ) FROM `tasks` WHERE parent_id = task_id) AS count_parents FROM tasks ``` This query didn't work. I hope the question is clear enough.
2013/01/24
[ "https://Stackoverflow.com/questions/14511923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1079913/" ]
If you want to include all tasks whether they are ever a parent or not, ``` select tasks.task_id,count(parent.parent_id) from tasks left join tasks parent on tasks.task_id=parent.parent_id group by tasks.task_id; ``` If you want only tasks that are parents, it is trivial: ``` select parent_id,count(*) from tasks group by parent_id; ``` (the latter possibly needing a `where parent_id is not null` or such, depending how you represent tasks that have no parent).
``` SELECT t2.task_id, t2.parent_id, (SELECT COUNT( * ) FROM `tasks` t1 WHERE t1.parent_id = t2.task_id) AS count_parents FROM tasks t2 ``` I think from your question
14,511,923
I have a tasks table with a `task_id` column and `parent_id` column for each task. I am trying to build a query that returns for each `task_id`, the number of times this `id` shows in the parent `id` column. I tried this query: ``` SELECT task_id, parent_id, (SELECT COUNT( * ) FROM `tasks` WHERE parent_id = task_id) AS count_parents FROM tasks ``` This query didn't work. I hope the question is clear enough.
2013/01/24
[ "https://Stackoverflow.com/questions/14511923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1079913/" ]
If you want to include all tasks whether they are ever a parent or not, ``` select tasks.task_id,count(parent.parent_id) from tasks left join tasks parent on tasks.task_id=parent.parent_id group by tasks.task_id; ``` If you want only tasks that are parents, it is trivial: ``` select parent_id,count(*) from tasks group by parent_id; ``` (the latter possibly needing a `where parent_id is not null` or such, depending how you represent tasks that have no parent).
Try this: ``` select task_id,parent_id, count(parent_id) as count_parents from `tasks` group by task_id,parent_id; ``` In this case you need a group by, hope it helps.
29,337,225
``` method - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation ``` Since this method got deprecated I was wondering how you can access the old location in the NSArray. Does the Array store the location each update. I tried the below way but couldnt get it to update ``` - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ CLLocation* location = [locations lastObject]; CLLocation *oldLocation; NSNumber *lat = [NSNumber numberWithDouble:location.coordinate.latitude]; NSNumber *lon = [NSNumber numberWithDouble:location.coordinate.longitude]; [[NSUserDefaults standardUserDefaults] setInteger:counter forKey:@"counter"]; NSDictionary *userLocation=@{@"lat":lat,@"long":lon}; [defaults setObject:userLocation forKey:@"userLocation"]; [defaults synchronize]; if (locations.count > 1) { oldLocation = locations[locations.count - 2]; } NSLog(@"old location(%f,%f)", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude ); // NSLog(@"new location (%f,%f)", location.coordinate.latitude, location.coordinate.longitude ); } ```
2015/03/30
[ "https://Stackoverflow.com/questions/29337225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3882976/" ]
`locationManager:didUpdateLocations:` returns a list of locations that you haven't seen yet. It may batch together several updates into a single notification. But it doesn't send you data you've already received. If you want to keep track of previous locations that you've already received, you need to store those yourself.
I did this using an NSMutableArray that I call locHistory, like this: ``` - (void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { [locHistory addObject:locationManager.location]; if ([locHistory count] > 2) { [locHistory removeObjectAtIndex:0]; } //more code... } ``` For some reason it wouldn't work with [locations lastObject] so instead I add locationManager.location to the array. I initialise the NSMutableArray elsewhere with initWithCapacity:2 which could be 1 since it will just expand it. Every time it updates the location I add the new location and remove first element when the amount of elements exceeds 2. What remains after that is your old location at index 0 and your latest at index 1. Maybe there is a better way to it, but this works for me.
64,148
Ok, I know this may sound dumb but, here is the thing: I recently removed a cpu, ram and hard disk from my 10-ish year old pc. At first, I did that to understand how the pc was built. Now, the next logical step would be to take it further and rebuild it. But I have no idea how to do that. So here is the simplified question: How can I *manually* wire a cpu, ram and hard disk *without* using the old motherboard. What would i need? Adaptors, sockets etc? EDIT: I mean something really simplistic. Like something that executes assembly code only. As I told in the comments below.
2013/04/02
[ "https://electronics.stackexchange.com/questions/64148", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/22009/" ]
You can't, realistically. A long time ago, computers had wires visible to the naked eye, or were even hand-assembled; [someone is doing a re-enactment of this](http://www.homebrewcpu.com/). These days they're held together on a 6-layer PCB which has been carefully routed to ensure that signals can travel at 1GHz without distortion or interference, assembled out of parts that are extremely hard to solder by hand. The support chipset is large and complex; you need all of it to work if you're going to see any results. If you're seriously interested in building your own, it is possible to build 80s-era technology by hand; see ["Veronica"](http://hackaday.com/tag/veronica/)
The parts of a computer such as those you mentioned cannot be used without an appropriate motherboard. Anything that could do the job IS a motherboard. Designing/building one is generally outside the scope of abilities for one person - especially one with no training and experience.
64,148
Ok, I know this may sound dumb but, here is the thing: I recently removed a cpu, ram and hard disk from my 10-ish year old pc. At first, I did that to understand how the pc was built. Now, the next logical step would be to take it further and rebuild it. But I have no idea how to do that. So here is the simplified question: How can I *manually* wire a cpu, ram and hard disk *without* using the old motherboard. What would i need? Adaptors, sockets etc? EDIT: I mean something really simplistic. Like something that executes assembly code only. As I told in the comments below.
2013/04/02
[ "https://electronics.stackexchange.com/questions/64148", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/22009/" ]
The parts of a computer such as those you mentioned cannot be used without an appropriate motherboard. Anything that could do the job IS a motherboard. Designing/building one is generally outside the scope of abilities for one person - especially one with no training and experience.
(Your question seems to have been edited, so I might not be answering the same question that the other answerers did.) Programming in assembly can be done on almost any computer or microcontroller you can get. Of these a PC might be the most readily available, but unfortunately the assembly language of the modern Intel chips is very complex. An alternative is to buy a RaspebrryPi. It uses an ARM chip, which has IMO one of the most elegant assembly architectures ever designed (in the same league as the PDP11 and the 68k). And you might teach yourself some Linux. Another path is to buy a development board for a microcontroller. Darron suggested a few in a comment, there are many many more. Yet another option is to get a simulator that runs on your PC but simulates a processor of your choice.
64,148
Ok, I know this may sound dumb but, here is the thing: I recently removed a cpu, ram and hard disk from my 10-ish year old pc. At first, I did that to understand how the pc was built. Now, the next logical step would be to take it further and rebuild it. But I have no idea how to do that. So here is the simplified question: How can I *manually* wire a cpu, ram and hard disk *without* using the old motherboard. What would i need? Adaptors, sockets etc? EDIT: I mean something really simplistic. Like something that executes assembly code only. As I told in the comments below.
2013/04/02
[ "https://electronics.stackexchange.com/questions/64148", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/22009/" ]
You can't, realistically. A long time ago, computers had wires visible to the naked eye, or were even hand-assembled; [someone is doing a re-enactment of this](http://www.homebrewcpu.com/). These days they're held together on a 6-layer PCB which has been carefully routed to ensure that signals can travel at 1GHz without distortion or interference, assembled out of parts that are extremely hard to solder by hand. The support chipset is large and complex; you need all of it to work if you're going to see any results. If you're seriously interested in building your own, it is possible to build 80s-era technology by hand; see ["Veronica"](http://hackaday.com/tag/veronica/)
(Your question seems to have been edited, so I might not be answering the same question that the other answerers did.) Programming in assembly can be done on almost any computer or microcontroller you can get. Of these a PC might be the most readily available, but unfortunately the assembly language of the modern Intel chips is very complex. An alternative is to buy a RaspebrryPi. It uses an ARM chip, which has IMO one of the most elegant assembly architectures ever designed (in the same league as the PDP11 and the 68k). And you might teach yourself some Linux. Another path is to buy a development board for a microcontroller. Darron suggested a few in a comment, there are many many more. Yet another option is to get a simulator that runs on your PC but simulates a processor of your choice.
4,289,588
I am a new mathematics teacher. $\mathbb R$ stands for set of real numbers. I learned that using set notation, a domain can be written $\{X \in \mathbb R\;|\; 4\leq x\leq7\}.$ However, some students write $\{x\;|\;4\leq x\leq7\}$ or $\{x\;|\;x \in \mathbb R, 4\leq x\leq7\}$. Are they correct? For the domain of $|x|,$ some students write $\{x\;|\;x \in \mathbb R\}$ instead of $\mathbb R.$ Are they correct? What are other ways people use set notation to write domains and ranges?
2021/10/28
[ "https://math.stackexchange.com/questions/4289588", "https://math.stackexchange.com", "https://math.stackexchange.com/users/985272/" ]
In most logics connectives with same precedence are associated to the right by default (see a recent [post](https://math.stackexchange.com/questions/4285935/propositional-logic-confused-on-using-operators-with-equal-precedence/4286148#4286148)), so we need to prove $(¬A ∨ ¬B) → ((C → A ∧ B)→ ¬C)$. I'll sketch a proof below using the most common ND rules, and you should fill in your specific rules for your ND system: Apparently we can try prove by cases: ``` 1 ¬A ∨ ¬B premise 2 ¬A 3 C → A ∧ B assumption 4 C assumption 5 A ∧ B → E 3-4 (MP) 6 A ∧ E 7 ⊥ ¬ E 2, 6 8 (C → A ∧ B) → ¬C ¬ I 4, 7 9 ¬B 10 C → A ∧ B assumption 11 C assumption 12 A ∧ B → E 10-11 13 B ∧ E 14 ⊥ ¬ E 9, 12 15 (C → A ∧ B) → ¬C ¬ I 11, 14 16 (¬A ∨ ¬B) → ((C → A ∧ B)→ ¬C) ∨ E ``` Finally please be aware that $((¬A ∨ ¬B) → (C → A ∧ B)) → ¬C$ is not valid which has an obvious counterexample when $A=B=C=True$.
Those are indeed your targets. So you need raise appropriate assumptions in subproofs aiming for them. The skeleton should look *something* like this (in Fitch style), but will depend somewhat on the rules implemented in your proof system. $$\def\fitch#1#2{~~~~\begin{array}{|l}#1\\\hline#2\end{array}} \fitch{}{\fitch{\neg A\vee\neg B}{\fitch{C\to A\wedge B}{\fitch{C}{\vdots\\\bot}\\\neg C}\\(C\to(A\wedge B)\to\neg C}\\(\neg A\vee\neg B)\to((C\to(A\wedge B)\to\neg C)}$$ At the very least, you'll need a 'proof by cases' to eliminate that disjunction.
4,289,588
I am a new mathematics teacher. $\mathbb R$ stands for set of real numbers. I learned that using set notation, a domain can be written $\{X \in \mathbb R\;|\; 4\leq x\leq7\}.$ However, some students write $\{x\;|\;4\leq x\leq7\}$ or $\{x\;|\;x \in \mathbb R, 4\leq x\leq7\}$. Are they correct? For the domain of $|x|,$ some students write $\{x\;|\;x \in \mathbb R\}$ instead of $\mathbb R.$ Are they correct? What are other ways people use set notation to write domains and ranges?
2021/10/28
[ "https://math.stackexchange.com/questions/4289588", "https://math.stackexchange.com", "https://math.stackexchange.com/users/985272/" ]
In most logics connectives with same precedence are associated to the right by default (see a recent [post](https://math.stackexchange.com/questions/4285935/propositional-logic-confused-on-using-operators-with-equal-precedence/4286148#4286148)), so we need to prove $(¬A ∨ ¬B) → ((C → A ∧ B)→ ¬C)$. I'll sketch a proof below using the most common ND rules, and you should fill in your specific rules for your ND system: Apparently we can try prove by cases: ``` 1 ¬A ∨ ¬B premise 2 ¬A 3 C → A ∧ B assumption 4 C assumption 5 A ∧ B → E 3-4 (MP) 6 A ∧ E 7 ⊥ ¬ E 2, 6 8 (C → A ∧ B) → ¬C ¬ I 4, 7 9 ¬B 10 C → A ∧ B assumption 11 C assumption 12 A ∧ B → E 10-11 13 B ∧ E 14 ⊥ ¬ E 9, 12 15 (C → A ∧ B) → ¬C ¬ I 11, 14 16 (¬A ∨ ¬B) → ((C → A ∧ B)→ ¬C) ∨ E ``` Finally please be aware that $((¬A ∨ ¬B) → (C → A ∧ B)) → ¬C$ is not valid which has an obvious counterexample when $A=B=C=True$.
Here's one way to do it, $$\begin{align} \neg A, C \to (A \wedge B), C &\vdash C &&\text{($\in$)}\\ \neg A, C \to (A \wedge B), C &\vdash C \to (A \wedge B) &&\text{($\in$)}\\ \neg A, C \to (A \wedge B), C &\vdash A \wedge B &&\text{($\to -$)}\\ \neg A, C \to (A \wedge B), C &\vdash A &&\text{($\wedge -$)}\\ \neg A, C \to (A \wedge B), C &\vdash \neg A &&\text{($\in$)}\\ \neg A, C \to (A \wedge B) &\vdash \neg C &&\text{($\neg +$), (4), (5)}\\ \neg A &\vdash (C \to (A \wedge B)) \to \neg C &&\text{($\to +$)}\\ \neg B, C \to (A \wedge B), C &\vdash C &&\text{($\in$)}\\ \neg B, C \to (A \wedge B), C &\vdash C \to (A \wedge B) &&\text{($\in$)}\\ \neg B, C \to (A \wedge B), C &\vdash A \wedge B &&\text{($\to -$)}\\ \neg B, C \to (A \wedge B), C &\vdash B &&\text{($\wedge -$)}\\ \neg B, C \to (A \wedge B), C &\vdash \neg B &&\text{($\in$)}\\ \neg B, C \to (A \wedge B) &\vdash \neg C &&\text{($\neg +$), (11), (12)}\\ \neg B &\vdash (C \to (A \wedge B)) \to \neg C &&\text{($\to +$)}\\ \neg A \vee \neg B &\vdash (C \to (A \wedge B)) \to \neg C &&\text{($\vee -$), (7), (14)}\\ \emptyset &\vdash (\neg A \vee \neg B) \to ((C \to (A \wedge B)) \to \neg C) &&\text{($\to +$)} \end{align}$$
25,168,828
``` matches = [] done = [] for item in matches: dofunctioneveryloop() done.extent(item) dofunctiononce5min() ``` How can I execute dofunctiononce5min() inside this loop once 5 minute? This is backup to file function is this possible?
2014/08/06
[ "https://Stackoverflow.com/questions/25168828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Not sure I understood the question. I'll assume that you want this function to be executed only once every five minutes, no matter how often it is really called. This might be overkill, but why not use a [decorator](https://stackoverflow.com/q/5929107/1639625)? This will create a new function for the 'decorated' function that will execute the original function if X seconds have passed since the last execution. This will make sure the function is not executed more than once every 5 minutes (or whateer time interval in seconds you pass to the decorator), no matter whether it's called in that loop or elsewhere. ``` import time def onceEveryXSeconds(seconds): # this creates the decorator def wrapper(f): # decorator for given 'seconds' f.last_execution = 0 # memorize last execution time def decorated(*args, **kwargs): # the 'decorated' function if f.last_execution < time.time() - seconds: f.last_execution = time.time() return f(*args, **kwargs) return decorated return wrapper ``` Usage: ``` @onceEveryXSeconds(3) def function(foo): print foo while True: print "loop" function("Hello again") time.sleep(1) ``` Output, with `@onceEveryXSeconds(3)` ```none loop Hello again loop loop loop Hello again loop ... ```
It is not recommended that you do this way. Perhaps the best approach could be to schedule it on operation system, and it run it task periodically. Anyway, if want to run a statement every x time, here is an example ``` import time for i in range(5): print i time.sleep(3) # seconds ``` Time as parameter should be fractioned like 0.5 seconds.
25,168,828
``` matches = [] done = [] for item in matches: dofunctioneveryloop() done.extent(item) dofunctiononce5min() ``` How can I execute dofunctiononce5min() inside this loop once 5 minute? This is backup to file function is this possible?
2014/08/06
[ "https://Stackoverflow.com/questions/25168828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Not sure I understood the question. I'll assume that you want this function to be executed only once every five minutes, no matter how often it is really called. This might be overkill, but why not use a [decorator](https://stackoverflow.com/q/5929107/1639625)? This will create a new function for the 'decorated' function that will execute the original function if X seconds have passed since the last execution. This will make sure the function is not executed more than once every 5 minutes (or whateer time interval in seconds you pass to the decorator), no matter whether it's called in that loop or elsewhere. ``` import time def onceEveryXSeconds(seconds): # this creates the decorator def wrapper(f): # decorator for given 'seconds' f.last_execution = 0 # memorize last execution time def decorated(*args, **kwargs): # the 'decorated' function if f.last_execution < time.time() - seconds: f.last_execution = time.time() return f(*args, **kwargs) return decorated return wrapper ``` Usage: ``` @onceEveryXSeconds(3) def function(foo): print foo while True: print "loop" function("Hello again") time.sleep(1) ``` Output, with `@onceEveryXSeconds(3)` ```none loop Hello again loop loop loop Hello again loop ... ```
Assuming the loop takes longer than five minutes, you could use time.time() to determine when 5 minutes has been up. ``` import time matches = [] done = [] starttime = time.time() for item in matches: dofunctioneveryloop() done.extent(item) if time.time() - starttime > 300: dofunctiononce5min() starttime = time.time() ```
18,658,017
I've found a bottleneck in my app that keeps growing as data in my files grow (see attached screenshot of VisualVM below). Below is the `getFileContentsAsList` code. How can this be made better performance-wise? I've read several posts on efficient File I/O and some have suggested `Scanner` as a way to efficiently read from a file. I've also tried Apache Commons `readFileToString` but that's not running fast as well. The data file that's causing the app to run slower is 8 KB...that doesn't seem too big to me. I could convert to an embedded database like Apache Derby if that seems like a better route. Ultimately looking for what will help the application run faster (It's a Java 1.7 Swing app BTW). Here's the code for `getFileContentsAsList`: ``` public static List<String> getFileContentsAsList(String filePath) throws IOException { if (ReceiptPrinterStringUtils.isNullOrEmpty(filePath)) throw new IllegalArgumentException("File path must not be null or empty"); Scanner s = null; List<String> records = new ArrayList<String>(); try { s = new Scanner(new BufferedReader(new FileReader(filePath))); s.useDelimiter(FileDelimiters.RECORD); while (s.hasNext()) { records.add(s.next()); } } finally { if (s != null) { s.close(); } } return records; } ``` ![Application CPU Hot Spots](https://i.stack.imgur.com/gdBjG.jpg)
2013/09/06
[ "https://Stackoverflow.com/questions/18658017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1098361/" ]
The size of an ArrayList is multiplied by 1.5 when necessary. This is O(log(N)). (Doubling was used in Vector.) I would certainly use an O(1) LinkedList here, and BufferedReader.readLine() rather than a Scanner if I was trying to speed it up. It's hard to believe that the time to read one 8k file is seriously a concern. You can read millions of lines in a second.
`ArrayList`s have a good performance at reading and also on writing IF the lenth does not change very often. In your application the length changes very often (size is doubled, when it is full and an element is added) and your application needs to copy your array into an new, longer array. You could use a `LinkedList`, where new elements are appended and no copy actions are needed. `List<String> records = new LinkedList<String>();` Or you could initialize the `ArrayList` with the approximated finished Number of Words. This will reduce the number of copy actions. `List<String> records = new ArrayList<String>(2000);`
18,658,017
I've found a bottleneck in my app that keeps growing as data in my files grow (see attached screenshot of VisualVM below). Below is the `getFileContentsAsList` code. How can this be made better performance-wise? I've read several posts on efficient File I/O and some have suggested `Scanner` as a way to efficiently read from a file. I've also tried Apache Commons `readFileToString` but that's not running fast as well. The data file that's causing the app to run slower is 8 KB...that doesn't seem too big to me. I could convert to an embedded database like Apache Derby if that seems like a better route. Ultimately looking for what will help the application run faster (It's a Java 1.7 Swing app BTW). Here's the code for `getFileContentsAsList`: ``` public static List<String> getFileContentsAsList(String filePath) throws IOException { if (ReceiptPrinterStringUtils.isNullOrEmpty(filePath)) throw new IllegalArgumentException("File path must not be null or empty"); Scanner s = null; List<String> records = new ArrayList<String>(); try { s = new Scanner(new BufferedReader(new FileReader(filePath))); s.useDelimiter(FileDelimiters.RECORD); while (s.hasNext()) { records.add(s.next()); } } finally { if (s != null) { s.close(); } } return records; } ``` ![Application CPU Hot Spots](https://i.stack.imgur.com/gdBjG.jpg)
2013/09/06
[ "https://Stackoverflow.com/questions/18658017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1098361/" ]
So, file.io gets to be REAL expensive if you do it a lot...as seen in my screen shot and original code, `getFileContentsAsList`, which contains file.io calls, gets invoked quite a bit (18.425 times). VisualVM is a real gem of a tool to point out bottlenecks like these! After contemplating over various ways to improve performance, it dawned on me that possibly the best way is to do file.io calls as little as possible. So, I decided to use private static variables to hold the file contents and to only do file.io in the static initializer and when a file is written to. As my application is (fortunately) not doing excessive writing (but excessive reading), this makes for a much better performing application. Here's the source for the entire class that contains the `getFileContentsAsList` method. I took a snapshot of that method and it now runs in 57.2 ms (down from 3116 ms). Also, it was my longest running method and is now my 4th longest running method. The top 5 longest running methods run for a total of 498.8 ms now as opposed to the ones in the original screenshot that ran for a total of 3812.9 ms. That's a percentage decrease of about 85% [100 \* (498.8 - 3812.9) / 3812.9]. ``` package com.mbc.receiptprinter.util; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import org.apache.commons.io.FileUtils; import com.mbc.receiptprinter.constant.FileDelimiters; import com.mbc.receiptprinter.constant.FilePaths; /* * Various File utility functions. This class uses the Apache Commons FileUtils class. */ public class ReceiptPrinterFileUtils { private static Map<String, String> fileContents = new HashMap<String, String>(); private static Map<String, Boolean> fileHasBeenUpdated = new HashMap<String, Boolean>(); static { for (FilePaths fp : FilePaths.values()) { File f = new File(fp.getPath()); try { FileUtils.touch(f); fileHasBeenUpdated.put(fp.getPath(), false); fileContents.put(fp.getPath(), FileUtils.readFileToString(f)); } catch (IOException e) { ReceiptPrinterLogger.logMessage(ReceiptPrinterFileUtils.class, Level.SEVERE, "IOException while performing FileUtils.touch in static block of ReceiptPrinterFileUtils", e); } } } public static String getFileContents(String filePath) throws IOException { if (ReceiptPrinterStringUtils.isNullOrEmpty(filePath)) throw new IllegalArgumentException("File path must not be null or empty"); File f = new File(filePath); if (fileHasBeenUpdated.get(filePath)) { fileContents.put(filePath, FileUtils.readFileToString(f)); fileHasBeenUpdated.put(filePath, false); } return fileContents.get(filePath); } public static List<String> convertFileContentsToList(String fileContents) { List<String> records = new ArrayList<String>(); if (fileContents.contains(FileDelimiters.RECORD)) { records = Arrays.asList(fileContents.split(FileDelimiters.RECORD)); } return records; } public static void writeStringToFile(String filePath, String data) throws IOException { fileHasBeenUpdated.put(filePath, true); FileUtils.writeStringToFile(new File(filePath), data); } public static void writeStringToFile(String filePath, String data, boolean append) throws IOException { fileHasBeenUpdated.put(filePath, true); FileUtils.writeStringToFile(new File(filePath), data, append); } } ```
`ArrayList`s have a good performance at reading and also on writing IF the lenth does not change very often. In your application the length changes very often (size is doubled, when it is full and an element is added) and your application needs to copy your array into an new, longer array. You could use a `LinkedList`, where new elements are appended and no copy actions are needed. `List<String> records = new LinkedList<String>();` Or you could initialize the `ArrayList` with the approximated finished Number of Words. This will reduce the number of copy actions. `List<String> records = new ArrayList<String>(2000);`
18,658,017
I've found a bottleneck in my app that keeps growing as data in my files grow (see attached screenshot of VisualVM below). Below is the `getFileContentsAsList` code. How can this be made better performance-wise? I've read several posts on efficient File I/O and some have suggested `Scanner` as a way to efficiently read from a file. I've also tried Apache Commons `readFileToString` but that's not running fast as well. The data file that's causing the app to run slower is 8 KB...that doesn't seem too big to me. I could convert to an embedded database like Apache Derby if that seems like a better route. Ultimately looking for what will help the application run faster (It's a Java 1.7 Swing app BTW). Here's the code for `getFileContentsAsList`: ``` public static List<String> getFileContentsAsList(String filePath) throws IOException { if (ReceiptPrinterStringUtils.isNullOrEmpty(filePath)) throw new IllegalArgumentException("File path must not be null or empty"); Scanner s = null; List<String> records = new ArrayList<String>(); try { s = new Scanner(new BufferedReader(new FileReader(filePath))); s.useDelimiter(FileDelimiters.RECORD); while (s.hasNext()) { records.add(s.next()); } } finally { if (s != null) { s.close(); } } return records; } ``` ![Application CPU Hot Spots](https://i.stack.imgur.com/gdBjG.jpg)
2013/09/06
[ "https://Stackoverflow.com/questions/18658017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1098361/" ]
So, file.io gets to be REAL expensive if you do it a lot...as seen in my screen shot and original code, `getFileContentsAsList`, which contains file.io calls, gets invoked quite a bit (18.425 times). VisualVM is a real gem of a tool to point out bottlenecks like these! After contemplating over various ways to improve performance, it dawned on me that possibly the best way is to do file.io calls as little as possible. So, I decided to use private static variables to hold the file contents and to only do file.io in the static initializer and when a file is written to. As my application is (fortunately) not doing excessive writing (but excessive reading), this makes for a much better performing application. Here's the source for the entire class that contains the `getFileContentsAsList` method. I took a snapshot of that method and it now runs in 57.2 ms (down from 3116 ms). Also, it was my longest running method and is now my 4th longest running method. The top 5 longest running methods run for a total of 498.8 ms now as opposed to the ones in the original screenshot that ran for a total of 3812.9 ms. That's a percentage decrease of about 85% [100 \* (498.8 - 3812.9) / 3812.9]. ``` package com.mbc.receiptprinter.util; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import org.apache.commons.io.FileUtils; import com.mbc.receiptprinter.constant.FileDelimiters; import com.mbc.receiptprinter.constant.FilePaths; /* * Various File utility functions. This class uses the Apache Commons FileUtils class. */ public class ReceiptPrinterFileUtils { private static Map<String, String> fileContents = new HashMap<String, String>(); private static Map<String, Boolean> fileHasBeenUpdated = new HashMap<String, Boolean>(); static { for (FilePaths fp : FilePaths.values()) { File f = new File(fp.getPath()); try { FileUtils.touch(f); fileHasBeenUpdated.put(fp.getPath(), false); fileContents.put(fp.getPath(), FileUtils.readFileToString(f)); } catch (IOException e) { ReceiptPrinterLogger.logMessage(ReceiptPrinterFileUtils.class, Level.SEVERE, "IOException while performing FileUtils.touch in static block of ReceiptPrinterFileUtils", e); } } } public static String getFileContents(String filePath) throws IOException { if (ReceiptPrinterStringUtils.isNullOrEmpty(filePath)) throw new IllegalArgumentException("File path must not be null or empty"); File f = new File(filePath); if (fileHasBeenUpdated.get(filePath)) { fileContents.put(filePath, FileUtils.readFileToString(f)); fileHasBeenUpdated.put(filePath, false); } return fileContents.get(filePath); } public static List<String> convertFileContentsToList(String fileContents) { List<String> records = new ArrayList<String>(); if (fileContents.contains(FileDelimiters.RECORD)) { records = Arrays.asList(fileContents.split(FileDelimiters.RECORD)); } return records; } public static void writeStringToFile(String filePath, String data) throws IOException { fileHasBeenUpdated.put(filePath, true); FileUtils.writeStringToFile(new File(filePath), data); } public static void writeStringToFile(String filePath, String data, boolean append) throws IOException { fileHasBeenUpdated.put(filePath, true); FileUtils.writeStringToFile(new File(filePath), data, append); } } ```
The size of an ArrayList is multiplied by 1.5 when necessary. This is O(log(N)). (Doubling was used in Vector.) I would certainly use an O(1) LinkedList here, and BufferedReader.readLine() rather than a Scanner if I was trying to speed it up. It's hard to believe that the time to read one 8k file is seriously a concern. You can read millions of lines in a second.
27,683,312
``` n = [3, 5, 7] def double_list(x): for i in range(0, len(x)): x[i] = x[i] * 2 return x[i] print double_list(n) ``` For some reason this python script is only returning the first item in the list instead of all three when it runs... Can someone please help me?!
2014/12/29
[ "https://Stackoverflow.com/questions/27683312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4401036/" ]
Use a **[list comprehension](https://docs.python.org/3.4/tutorial/datastructures.html#list-comprehensions)** instead. ``` double_list = [ x*2 for x in n ] ``` Same result, four times shorter, a trillion times more readable. **[Because readability counts](https://www.python.org/dev/peps/pep-0020/)**.
1. Change the `return` statement so that it is not indented to be part of the `for` block. 2. Return the list instead of an item from the list. ``` def double_list(x): for i in range(0, len(x)): x[i] = x[i] * 2 return x ```
27,683,312
``` n = [3, 5, 7] def double_list(x): for i in range(0, len(x)): x[i] = x[i] * 2 return x[i] print double_list(n) ``` For some reason this python script is only returning the first item in the list instead of all three when it runs... Can someone please help me?!
2014/12/29
[ "https://Stackoverflow.com/questions/27683312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4401036/" ]
Use a **[list comprehension](https://docs.python.org/3.4/tutorial/datastructures.html#list-comprehensions)** instead. ``` double_list = [ x*2 for x in n ] ``` Same result, four times shorter, a trillion times more readable. **[Because readability counts](https://www.python.org/dev/peps/pep-0020/)**.
``` n = [3, 5, 7] def double_list(x): for i in range(0, len(x)): x[i]*=2 return x print double_list(n) ``` Try this.Returning the list, also check how we re-define variables with arithmetical operations.
27,683,312
``` n = [3, 5, 7] def double_list(x): for i in range(0, len(x)): x[i] = x[i] * 2 return x[i] print double_list(n) ``` For some reason this python script is only returning the first item in the list instead of all three when it runs... Can someone please help me?!
2014/12/29
[ "https://Stackoverflow.com/questions/27683312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4401036/" ]
Use a **[list comprehension](https://docs.python.org/3.4/tutorial/datastructures.html#list-comprehensions)** instead. ``` double_list = [ x*2 for x in n ] ``` Same result, four times shorter, a trillion times more readable. **[Because readability counts](https://www.python.org/dev/peps/pep-0020/)**.
``` n = [3, 5, 7] def double_list(x): t=[i*2 for i in x] return t print (double_list(n)) ``` Another short way for that.
27,683,312
``` n = [3, 5, 7] def double_list(x): for i in range(0, len(x)): x[i] = x[i] * 2 return x[i] print double_list(n) ``` For some reason this python script is only returning the first item in the list instead of all three when it runs... Can someone please help me?!
2014/12/29
[ "https://Stackoverflow.com/questions/27683312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4401036/" ]
Use a **[list comprehension](https://docs.python.org/3.4/tutorial/datastructures.html#list-comprehensions)** instead. ``` double_list = [ x*2 for x in n ] ``` Same result, four times shorter, a trillion times more readable. **[Because readability counts](https://www.python.org/dev/peps/pep-0020/)**.
to add to the options: ``` def double_list(x): return map(lambda num: num*2, x) print double_list([2, 3, 4]) ```
27,683,312
``` n = [3, 5, 7] def double_list(x): for i in range(0, len(x)): x[i] = x[i] * 2 return x[i] print double_list(n) ``` For some reason this python script is only returning the first item in the list instead of all three when it runs... Can someone please help me?!
2014/12/29
[ "https://Stackoverflow.com/questions/27683312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4401036/" ]
1. Change the `return` statement so that it is not indented to be part of the `for` block. 2. Return the list instead of an item from the list. ``` def double_list(x): for i in range(0, len(x)): x[i] = x[i] * 2 return x ```
``` n = [3, 5, 7] def double_list(x): for i in range(0, len(x)): x[i]*=2 return x print double_list(n) ``` Try this.Returning the list, also check how we re-define variables with arithmetical operations.
27,683,312
``` n = [3, 5, 7] def double_list(x): for i in range(0, len(x)): x[i] = x[i] * 2 return x[i] print double_list(n) ``` For some reason this python script is only returning the first item in the list instead of all three when it runs... Can someone please help me?!
2014/12/29
[ "https://Stackoverflow.com/questions/27683312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4401036/" ]
1. Change the `return` statement so that it is not indented to be part of the `for` block. 2. Return the list instead of an item from the list. ``` def double_list(x): for i in range(0, len(x)): x[i] = x[i] * 2 return x ```
``` n = [3, 5, 7] def double_list(x): t=[i*2 for i in x] return t print (double_list(n)) ``` Another short way for that.
27,683,312
``` n = [3, 5, 7] def double_list(x): for i in range(0, len(x)): x[i] = x[i] * 2 return x[i] print double_list(n) ``` For some reason this python script is only returning the first item in the list instead of all three when it runs... Can someone please help me?!
2014/12/29
[ "https://Stackoverflow.com/questions/27683312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4401036/" ]
1. Change the `return` statement so that it is not indented to be part of the `for` block. 2. Return the list instead of an item from the list. ``` def double_list(x): for i in range(0, len(x)): x[i] = x[i] * 2 return x ```
to add to the options: ``` def double_list(x): return map(lambda num: num*2, x) print double_list([2, 3, 4]) ```
27,683,312
``` n = [3, 5, 7] def double_list(x): for i in range(0, len(x)): x[i] = x[i] * 2 return x[i] print double_list(n) ``` For some reason this python script is only returning the first item in the list instead of all three when it runs... Can someone please help me?!
2014/12/29
[ "https://Stackoverflow.com/questions/27683312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4401036/" ]
``` n = [3, 5, 7] def double_list(x): t=[i*2 for i in x] return t print (double_list(n)) ``` Another short way for that.
``` n = [3, 5, 7] def double_list(x): for i in range(0, len(x)): x[i]*=2 return x print double_list(n) ``` Try this.Returning the list, also check how we re-define variables with arithmetical operations.
27,683,312
``` n = [3, 5, 7] def double_list(x): for i in range(0, len(x)): x[i] = x[i] * 2 return x[i] print double_list(n) ``` For some reason this python script is only returning the first item in the list instead of all three when it runs... Can someone please help me?!
2014/12/29
[ "https://Stackoverflow.com/questions/27683312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4401036/" ]
to add to the options: ``` def double_list(x): return map(lambda num: num*2, x) print double_list([2, 3, 4]) ```
``` n = [3, 5, 7] def double_list(x): for i in range(0, len(x)): x[i]*=2 return x print double_list(n) ``` Try this.Returning the list, also check how we re-define variables with arithmetical operations.
27,683,312
``` n = [3, 5, 7] def double_list(x): for i in range(0, len(x)): x[i] = x[i] * 2 return x[i] print double_list(n) ``` For some reason this python script is only returning the first item in the list instead of all three when it runs... Can someone please help me?!
2014/12/29
[ "https://Stackoverflow.com/questions/27683312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4401036/" ]
``` n = [3, 5, 7] def double_list(x): t=[i*2 for i in x] return t print (double_list(n)) ``` Another short way for that.
to add to the options: ``` def double_list(x): return map(lambda num: num*2, x) print double_list([2, 3, 4]) ```
19,353,156
In general, what is the performance cost of an equality comparison between two STL container iterators? I'm only talking about defined operations; that is, comparing two iterators referring to the same object. My specific use-case is that I have a `std::map` that could potentially have very large elements, lots of elements, or both. If an equality comparison between two iterators over such a map have hidden penalties that I'm not aware of, it could impact the performance of my code.
2013/10/14
[ "https://Stackoverflow.com/questions/19353156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1830736/" ]
Generally, the *performance* of comparing two iterators depends on the implementation of the STL. However, concerning the *time complexity*, the C++ standard imposes the restriction that comparison of input iterators (and thus forward iterators, bidirectional iterators and random access iterators) takes amortized constant time. Particularly, this means for an `std::map<std::string, int>`, that its iterators cannot be compared by comparing the keys for equality, because that would be linear with respect to the length of the key.
Most of STL containers `operator==()` is just raw pointer comparison. Which is meaningless unless it's for boundaries checking. More over, if you are comparing iterators from different containers - it's undefined behaviour. If you override this operator or use external comparison function, perfomance depends on how large are object you are comparing. Probably I got your question wrong, it's not 100% clear what do you mean by "iterator comparison" and what's your use case.
19,353,156
In general, what is the performance cost of an equality comparison between two STL container iterators? I'm only talking about defined operations; that is, comparing two iterators referring to the same object. My specific use-case is that I have a `std::map` that could potentially have very large elements, lots of elements, or both. If an equality comparison between two iterators over such a map have hidden penalties that I'm not aware of, it could impact the performance of my code.
2013/10/14
[ "https://Stackoverflow.com/questions/19353156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1830736/" ]
The [**draft Standard**](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3691.pdf) states that iterator operations are [**amortized constant time**](https://stackoverflow.com/q/200384/819272) **24.2.1 In general [iterator.requirements.general]** > > 8 All the categories of iterators require only those functions that > are realizable for a given category in constant time (amortized). > Therefore, requirement tables for the iterators do not have a > complexity column. > > > If you look at the signatures of iterator operations, there are no parameters or return types that correspond to the underlying elements `T` themselves, only `T*` and `T&` are required. Even `operator==` does not have to directly compare two arbitrarily large elements `T` themselves. However, this does not give a hard real-time upper-bound for iterator operations. In particular, iterators can do [very costly bounds checking](https://stackoverflow.com/q/6103314/819272), but these Debug mode security guards can usually be left out in Release builds.
Most of STL containers `operator==()` is just raw pointer comparison. Which is meaningless unless it's for boundaries checking. More over, if you are comparing iterators from different containers - it's undefined behaviour. If you override this operator or use external comparison function, perfomance depends on how large are object you are comparing. Probably I got your question wrong, it's not 100% clear what do you mean by "iterator comparison" and what's your use case.
19,709,651
I would like to automate my hive script every day , in order to do that i have an option which is data pipeline. But the problem is there that i am exporting data from dynamo-db to s3 and with a hive script i am manipulating this data. I am giving this input and output in hive-script that's where the problem starts because a hive-activity has to have input and output but i have to give them in script file. I am trying to find a way to automate this hive-script and waiting for some ideas ? Cheers,
2013/10/31
[ "https://Stackoverflow.com/questions/19709651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2834892/" ]
You can disable staging on Hive Activity to run any arbitrary Hive Script. ``` stage = false ``` Do something like: ``` { "name": "DefaultActivity1", "id": "ActivityId_1", "type": "HiveActivity", "stage": "false", "scriptUri": "s3://baucket/query.hql", "scriptVariable": [ "param1=value1", "param2=value2" ], "schedule": { "ref": "ScheduleId_l" }, "runsOn": { "ref": "EmrClusterId_1" } }, ```
Another alternative to the Hive Activity, is to use an EMR activity as in the following example: ``` { "schedule": { "ref": "DefaultSchedule" }, "name": "EMR Activity name", "step": "command-runner.jar,hive-script,--run-hive-script,--args,-f,s3://bucket/path/query.hql", "runsOn": { "ref": "EmrClusterId" }, "id": "EmrActivityId", "type": "EmrActivity" } ```
38,218,952
I am fairly new to the program being used which is MimicView Gambit. From what I know it mimics a node/switch/router to simulate real time activity. What I need to do is using a SNMP walk results to somehow import the .wlk file into mimicview as an agent. An agent is referred to as the node/switch/router. Does anyone have any information on how to approach this or some leads/documentation?
2016/07/06
[ "https://Stackoverflow.com/questions/38218952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6555015/" ]
Thanks for the question. The quickest answer will come from `[email protected]`. The simplest way to create a simulation is to record the device directly, for example, see this [Youtube video](https://www.youtube.com/watch?v=-KctvDus7KU "video"). If you have a walkfile, you can use Simulation->Record File in MIMICView. There are many more ways to import devices into the [SNMP Simulator](http://www.gambitcomm.com) as documented in the online documentation.
I had never heard before about MimicView, but I'm working on similar project. So fast view via Mimic's FAQ seems to give the [answer](http://www.gambitcomm.com/faq/#walkfile). In short, as far as I understand you have to write file using net-snmp `snmpwalk` command with option `-One`, like ``` snmpwalk -One -v2c -cpublic ip.of.your.device > result.wlk ``` and then fed result to MimicRecorder, eg. in MIMICView use Simulation->Record File. In any case you should read that link and the walkfile converters section in the Utilities Guide for more details.
2,182,103
Consider: ``` struct foo { int a; int b; }; void* p = (void*)malloc(sizeof(struct foo)); ((foo*)p)->a; // Do something. free(p); // Is this safe? ```
2010/02/02
[ "https://Stackoverflow.com/questions/2182103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208397/" ]
Yes. The function prototype for `free` is even: ``` void free(void *ptr); ```
Yes, but normally it's a sign of poor design. malloc() is typically used to allocate buffers (large arrays of the same primitive type) or objects (structs with fields initialised). In both cases, the malloc and the free should match so, ``` unsigned char *rgba_buffer = malloc(width * height * 4); /* Use the buffer here */ free(rgba_buffer); BITSTREAM *bs = bitstream("bitfile.boin"); /* Use the bitstream here */ destroy_bitstream(bs); typedef struct { FILE *fp; unsigned char ch; int index; } BITSTREAM; BITSTREAM *bitstream(const char *filename) { BITSTREAM *bs = malloc(sizeof(BITSTREAM)); bs->fp = fopen(filename "rb"); /* etc */ return bs; } void destroybitstream(BITSTREAM *bs) { if(bs) { if(bs->fp) fclose(bs->fp); free(bs); } } ``` In one case, malloc and free match, and in the other the allocated memory is returned. There are also secondary resources, and the constructor and destructor match. It should be rare to allocate a region of memory, but not know what it is used for. And you shouldn't be interleaving allocations and frees chaotically. Modern C++ tightens this all up with unique pointers which "own" the object. While you can have a unique pointer to void, it would be very rare.
2,182,103
Consider: ``` struct foo { int a; int b; }; void* p = (void*)malloc(sizeof(struct foo)); ((foo*)p)->a; // Do something. free(p); // Is this safe? ```
2010/02/02
[ "https://Stackoverflow.com/questions/2182103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208397/" ]
Yes, it's safe. When allocating memory, the runtime library keeps track of the size of each allocation. When you call free(), it looks up the address, and if it finds an allocation for that address, the correct amount of memory is freed (the block that was allocated at that address).
In C it is perfectly safe, because there are no destructors to call. The memory system keeps track of the size of allocations. In C++ you must delete the same type you *new*, including using the `delete[]` operator to delete new'ed arrays. This is just to make sure destructors are called.
2,182,103
Consider: ``` struct foo { int a; int b; }; void* p = (void*)malloc(sizeof(struct foo)); ((foo*)p)->a; // Do something. free(p); // Is this safe? ```
2010/02/02
[ "https://Stackoverflow.com/questions/2182103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208397/" ]
Yes. malloc returns `void *` and free takes `void *`, so some of your casts are meaningless, and you're always freeing a `void *` even if you're starting with some other sort of pointer.
yes it is safe.
2,182,103
Consider: ``` struct foo { int a; int b; }; void* p = (void*)malloc(sizeof(struct foo)); ((foo*)p)->a; // Do something. free(p); // Is this safe? ```
2010/02/02
[ "https://Stackoverflow.com/questions/2182103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208397/" ]
Yes -- `free` takes a pointer to void, so when you call it, the pointer is (implicitly) cast to a pointer to void in any case. The rest of your code isn't quite so safe: ``` void* p = (void*)malloc(sizeof(foo)); ``` You should *not* cast the return from malloc (in C). This can cover up the mistake of forgetting to `#include <stdlib.h>`
In C it is perfectly safe, because there are no destructors to call. The memory system keeps track of the size of allocations. In C++ you must delete the same type you *new*, including using the `delete[]` operator to delete new'ed arrays. This is just to make sure destructors are called.
2,182,103
Consider: ``` struct foo { int a; int b; }; void* p = (void*)malloc(sizeof(struct foo)); ((foo*)p)->a; // Do something. free(p); // Is this safe? ```
2010/02/02
[ "https://Stackoverflow.com/questions/2182103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208397/" ]
Yes, it's safe. When allocating memory, the runtime library keeps track of the size of each allocation. When you call free(), it looks up the address, and if it finds an allocation for that address, the correct amount of memory is freed (the block that was allocated at that address).
Yes, but normally it's a sign of poor design. malloc() is typically used to allocate buffers (large arrays of the same primitive type) or objects (structs with fields initialised). In both cases, the malloc and the free should match so, ``` unsigned char *rgba_buffer = malloc(width * height * 4); /* Use the buffer here */ free(rgba_buffer); BITSTREAM *bs = bitstream("bitfile.boin"); /* Use the bitstream here */ destroy_bitstream(bs); typedef struct { FILE *fp; unsigned char ch; int index; } BITSTREAM; BITSTREAM *bitstream(const char *filename) { BITSTREAM *bs = malloc(sizeof(BITSTREAM)); bs->fp = fopen(filename "rb"); /* etc */ return bs; } void destroybitstream(BITSTREAM *bs) { if(bs) { if(bs->fp) fclose(bs->fp); free(bs); } } ``` In one case, malloc and free match, and in the other the allocated memory is returned. There are also secondary resources, and the constructor and destructor match. It should be rare to allocate a region of memory, but not know what it is used for. And you shouldn't be interleaving allocations and frees chaotically. Modern C++ tightens this all up with unique pointers which "own" the object. While you can have a unique pointer to void, it would be very rare.
2,182,103
Consider: ``` struct foo { int a; int b; }; void* p = (void*)malloc(sizeof(struct foo)); ((foo*)p)->a; // Do something. free(p); // Is this safe? ```
2010/02/02
[ "https://Stackoverflow.com/questions/2182103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208397/" ]
Yes. malloc returns `void *` and free takes `void *`, so some of your casts are meaningless, and you're always freeing a `void *` even if you're starting with some other sort of pointer.
Perhaps it doesn't *feel* safe because of the magic happening behind the scenes. The C runtime and/or the OS itself is actively tracking the memory returned by malloc including its size and location. See though it feels like you are passing a typeless pointer back to free(), you in fact passing back a reference to an object the memory manager is actively tracking.
2,182,103
Consider: ``` struct foo { int a; int b; }; void* p = (void*)malloc(sizeof(struct foo)); ((foo*)p)->a; // Do something. free(p); // Is this safe? ```
2010/02/02
[ "https://Stackoverflow.com/questions/2182103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208397/" ]
Yes, it's safe. When allocating memory, the runtime library keeps track of the size of each allocation. When you call free(), it looks up the address, and if it finds an allocation for that address, the correct amount of memory is freed (the block that was allocated at that address).
yes it is safe.
2,182,103
Consider: ``` struct foo { int a; int b; }; void* p = (void*)malloc(sizeof(struct foo)); ((foo*)p)->a; // Do something. free(p); // Is this safe? ```
2010/02/02
[ "https://Stackoverflow.com/questions/2182103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208397/" ]
Yes -- `free` takes a pointer to void, so when you call it, the pointer is (implicitly) cast to a pointer to void in any case. The rest of your code isn't quite so safe: ``` void* p = (void*)malloc(sizeof(foo)); ``` You should *not* cast the return from malloc (in C). This can cover up the mistake of forgetting to `#include <stdlib.h>`
yes it is safe.
2,182,103
Consider: ``` struct foo { int a; int b; }; void* p = (void*)malloc(sizeof(struct foo)); ((foo*)p)->a; // Do something. free(p); // Is this safe? ```
2010/02/02
[ "https://Stackoverflow.com/questions/2182103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208397/" ]
Yes. malloc returns `void *` and free takes `void *`, so some of your casts are meaningless, and you're always freeing a `void *` even if you're starting with some other sort of pointer.
Yes, but normally it's a sign of poor design. malloc() is typically used to allocate buffers (large arrays of the same primitive type) or objects (structs with fields initialised). In both cases, the malloc and the free should match so, ``` unsigned char *rgba_buffer = malloc(width * height * 4); /* Use the buffer here */ free(rgba_buffer); BITSTREAM *bs = bitstream("bitfile.boin"); /* Use the bitstream here */ destroy_bitstream(bs); typedef struct { FILE *fp; unsigned char ch; int index; } BITSTREAM; BITSTREAM *bitstream(const char *filename) { BITSTREAM *bs = malloc(sizeof(BITSTREAM)); bs->fp = fopen(filename "rb"); /* etc */ return bs; } void destroybitstream(BITSTREAM *bs) { if(bs) { if(bs->fp) fclose(bs->fp); free(bs); } } ``` In one case, malloc and free match, and in the other the allocated memory is returned. There are also secondary resources, and the constructor and destructor match. It should be rare to allocate a region of memory, but not know what it is used for. And you shouldn't be interleaving allocations and frees chaotically. Modern C++ tightens this all up with unique pointers which "own" the object. While you can have a unique pointer to void, it would be very rare.
2,182,103
Consider: ``` struct foo { int a; int b; }; void* p = (void*)malloc(sizeof(struct foo)); ((foo*)p)->a; // Do something. free(p); // Is this safe? ```
2010/02/02
[ "https://Stackoverflow.com/questions/2182103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208397/" ]
Yes, it's safe. When allocating memory, the runtime library keeps track of the size of each allocation. When you call free(), it looks up the address, and if it finds an allocation for that address, the correct amount of memory is freed (the block that was allocated at that address).
Yes -- `free` takes a pointer to void, so when you call it, the pointer is (implicitly) cast to a pointer to void in any case. The rest of your code isn't quite so safe: ``` void* p = (void*)malloc(sizeof(foo)); ``` You should *not* cast the return from malloc (in C). This can cover up the mistake of forgetting to `#include <stdlib.h>`
26,879,981
I wanted to try out the python BytesIO class. As an experiment I tried writing to a zip file in memory, and then reading the bytes back out of that zip file. So instead of passing in a file-object to `gzip`, I pass in a `BytesIO` object. Here is the entire script: ``` from io import BytesIO import gzip # write bytes to zip file in memory myio = BytesIO() with gzip.GzipFile(fileobj=myio, mode='wb') as g: g.write(b"does it work") # read bytes from zip file in memory with gzip.GzipFile(fileobj=myio, mode='rb') as g: result = g.read() print(result) ``` But it is returning an empty `bytes` object for `result`. This happens in both Python 2.7 and 3.4. What am I missing?
2014/11/12
[ "https://Stackoverflow.com/questions/26879981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2213647/" ]
You need to [`seek`](https://docs.python.org/3/library/io.html#io.IOBase.seek) back to the beginning of the file after writing the initial in memory file... ``` myio.seek(0) ```
How about we write and read gzip content in the same context like this? ``` #!/usr/bin/env python from io import BytesIO import gzip content = b"does it work" # write bytes to zip file in memory gzipped_content = None with BytesIO() as myio: with gzip.GzipFile(fileobj=myio, mode='wb') as g: g.write(content) gzipped_content = myio.getvalue() print(gzipped_content) print(content == gzip.decompress(gzipped_content)) ```
26,879,981
I wanted to try out the python BytesIO class. As an experiment I tried writing to a zip file in memory, and then reading the bytes back out of that zip file. So instead of passing in a file-object to `gzip`, I pass in a `BytesIO` object. Here is the entire script: ``` from io import BytesIO import gzip # write bytes to zip file in memory myio = BytesIO() with gzip.GzipFile(fileobj=myio, mode='wb') as g: g.write(b"does it work") # read bytes from zip file in memory with gzip.GzipFile(fileobj=myio, mode='rb') as g: result = g.read() print(result) ``` But it is returning an empty `bytes` object for `result`. This happens in both Python 2.7 and 3.4. What am I missing?
2014/11/12
[ "https://Stackoverflow.com/questions/26879981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2213647/" ]
You need to [`seek`](https://docs.python.org/3/library/io.html#io.IOBase.seek) back to the beginning of the file after writing the initial in memory file... ``` myio.seek(0) ```
`myio.getvalue()` is an alternative to `seek` that *returns the bytes containing the entire contents of the buffer* ([docs](https://docs.python.org/3/library/io.html#io.BytesIO.getvalue)). It worked for me after facing a similar issue.
26,879,981
I wanted to try out the python BytesIO class. As an experiment I tried writing to a zip file in memory, and then reading the bytes back out of that zip file. So instead of passing in a file-object to `gzip`, I pass in a `BytesIO` object. Here is the entire script: ``` from io import BytesIO import gzip # write bytes to zip file in memory myio = BytesIO() with gzip.GzipFile(fileobj=myio, mode='wb') as g: g.write(b"does it work") # read bytes from zip file in memory with gzip.GzipFile(fileobj=myio, mode='rb') as g: result = g.read() print(result) ``` But it is returning an empty `bytes` object for `result`. This happens in both Python 2.7 and 3.4. What am I missing?
2014/11/12
[ "https://Stackoverflow.com/questions/26879981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2213647/" ]
How about we write and read gzip content in the same context like this? ``` #!/usr/bin/env python from io import BytesIO import gzip content = b"does it work" # write bytes to zip file in memory gzipped_content = None with BytesIO() as myio: with gzip.GzipFile(fileobj=myio, mode='wb') as g: g.write(content) gzipped_content = myio.getvalue() print(gzipped_content) print(content == gzip.decompress(gzipped_content)) ```
`myio.getvalue()` is an alternative to `seek` that *returns the bytes containing the entire contents of the buffer* ([docs](https://docs.python.org/3/library/io.html#io.BytesIO.getvalue)). It worked for me after facing a similar issue.
52,171,760
Suppose I do the following: ``` $ echo {10..20} 10 11 12 13 14 15 16 17 18 19 20 $ A=10 $ B=20 $ echo {${A}..${B}} {10..20} ``` Why does this not expand as it did the first time? I am trying to set up a "for" loop in a script: ``` for i in {10..20} do echo ${i} done 10 11 12 13 14 15 16 17 18 19 20 ``` But if I use variables... ``` for i in {${A}..${B}} do echo ${i} done {10..20} ``` I tried using "eval". Didn't work. ``` for i in `eval {${A}..${B}}` ... ``` I tried parentheses. Didn't work. ``` for i in "{${A}..${B}}" ... ``` What else can I try, other than ``` seq ${A} ${B} ``` ?
2018/09/04
[ "https://Stackoverflow.com/questions/52171760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3366758/" ]
It does not expand by definition. Taken from the bash manual: > > A sequence expression takes the form {x..y[..incr]}, where x and y are > either integers or single characters, and incr, an optional increment, > is an integer. > > > And > > Brace expansion is performed before any other expansions, and any > characters special to other expansions are preserved in the result. It > is strictly textual. Bash does not apply any syntactic interpretation > to the context of the expansion or the text between the braces. > > > So you must provide integers or characters, and the interpretation is textual, no interpretation of the text between the braces. I think you have no other option besides using `seq` or another approach like a loop where you take care of incrementing a variable from start to end.
Try: ``` for ((i=A; i<=B; i++)) ; do echo $i done ```
64,777,280
I'm making an app in JS with Node.js. I'm trying to use the async/await function. When I execute the code below, the first time that I make a get request it gives to me an empty array, if I make a second get request, it gives to me the array fully. Why did this happen? ``` var sql = `SELECT * FROM Pietanza`; await db.query(sql, (error, result, fields)=>{ if(error){ throw error; } //console.log(JSON.stringify(result)); result.forEach(j => { var temp = j; //retrieving indicatori (spicy, vegan for example) sql = `SELECT indicatore FROM pietanza_indicatore WHERE pietanza = '${temp.nome}'`; db.query(sql, (error, result, fields)=>{ if(error) throw error; temp.indicatori = new Array(); result.forEach(ind => { temp.indicatori.push(ind.indicatore); //console.log(temp); }); }); pietanze.menu.push(temp); }); //console.log(pietanze); }); //sends the JSON menu //console.log(pietanze); res.json(pietanze); });``` Thank you in advance. ```
2020/11/10
[ "https://Stackoverflow.com/questions/64777280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13511892/" ]
You are mixing `async/await` and callbacks. That won't work, because `await` won't wait for callbacks to finish. If you want to do it with `await` the syntax is roughly as follows (assuming the database package supports promises) ``` try { let outerresult = await db.query(outersql); ... for (let row of outerresult) { ... let innerresult = await db.query(innersql); ... } } catch (error) { // Do the error handling } ``` You also can't use `Array.forEach` with `async/await` because it doesn't support asynchronous callbacks.
It's due to the nature of the **async** request you're making. async requests will run whenever they can run, so you need to wait for them to return their values before you can use them (e.g. to loop through them and display them)
64,777,280
I'm making an app in JS with Node.js. I'm trying to use the async/await function. When I execute the code below, the first time that I make a get request it gives to me an empty array, if I make a second get request, it gives to me the array fully. Why did this happen? ``` var sql = `SELECT * FROM Pietanza`; await db.query(sql, (error, result, fields)=>{ if(error){ throw error; } //console.log(JSON.stringify(result)); result.forEach(j => { var temp = j; //retrieving indicatori (spicy, vegan for example) sql = `SELECT indicatore FROM pietanza_indicatore WHERE pietanza = '${temp.nome}'`; db.query(sql, (error, result, fields)=>{ if(error) throw error; temp.indicatori = new Array(); result.forEach(ind => { temp.indicatori.push(ind.indicatore); //console.log(temp); }); }); pietanze.menu.push(temp); }); //console.log(pietanze); }); //sends the JSON menu //console.log(pietanze); res.json(pietanze); });``` Thank you in advance. ```
2020/11/10
[ "https://Stackoverflow.com/questions/64777280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13511892/" ]
The problem is that `db.query` is asynchronous, but since you're using callbacks, it's unlikely that it's returning Promises, so await won't do what you're expecting. If you want to use `await`, you may have to adapt this API. ``` const query = sql => new Promise((resolve, reject) => { db.query(sql, (error, result, fields) => { if (error) { return reject(error); } resolve(result); }); }); const result = await query(`SELECT * FROM Pietanza`); const menu = await Promise.all(result.map(temp => { //retrieving indicatori (spicy, vegan for example) const indicatori = await query(` SELECT indicatore FROM pietanza_indicatore WHERE pietanza = '${temp.nome}' `); return { ...temp, indicatori: indicatori.map(ind => ind.indicatore) }; })); res.json({ ...pietanze, menu }); ```
It's due to the nature of the **async** request you're making. async requests will run whenever they can run, so you need to wait for them to return their values before you can use them (e.g. to loop through them and display them)
53,229,448
I had created a static variable to save app context since I was going to use it at other places in the class. This variable was getting assigned in the constructor of the class and I was getting the following error - "Do not place Android context classes in static fields (static reference to MyClass which has field appContext pointing to Context); this is a memory leak (and also breaks Instant Run) [StaticFieldLeak]" ***Below is the code within MyClass:*** ``` private static Context appContext; public MyClass(Context context) { appContext = context; } ``` To fix this issue I thought of making appContext as a weak reference variable. But I am unable to call any methods on that variable because it's of weak reference. Below is the updated code and the error I get while I tried to call a method on weak object. ***Updated code:*** ``` private final WeakReference<Context> appContext; public MyClass(Context context) { appContext = new WeakReference<Context>(context); } ``` At some places in my class am trying to call appContext.getPackageManager() and appContext.getString() and I am seeing below errors: ``` error: cannot find symbol symbol: method getPackageManager() location: variable appContext of type WeakReference<Context> error: cannot find symbol symbol: method getString(int) location: variable appContext of type WeakReference<Context> ``` How can I fix the memory leak issue if I don't make the variable a weak reference? Or if I make a weak reference, how do I execute methods on it?
2018/11/09
[ "https://Stackoverflow.com/questions/53229448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/697033/" ]
You need to call the `get()` method on the `WeakReference<Context>` in order to extrapolate the `Context` value. `WeakReference<Context>` has no `getPackageManager()` method, that's why you're getting that error.
The whole "context" thing really makes it hard to do layering in Android. Without seeing the class you are trying to access, it is hard to say for certain but one option is to make all the functions static and call them with the context from your other classes. You can pass context to a static function and use it within, you just can't save it to a static variable. For example: ``` static void doStuff(Context context){ //do context stuff } MyClass.doStuff(myCurrentClass.this); ``` If you instantiating the class as an object, you don't even need to make the global context variable static at all.
925,225
I'm new to JQuery In my App, I have some 5 divs. While clicking any one of the div, I want to check whether any other divs have been clicked before Actually in my code I have ``` Text Textarea Dropdown ``` while clicking on Text/textarea/dropdown for the first time (i.e. I need to check whether any of the others including its own has been clicked before) so that I can proceed based on that. Even if I use what you said having a variable=1 there arose an issue that while clicking on any of text/textarea/dropdown, I want to check whether the one I'm clicking and the others have clicked before.
2009/05/29
[ "https://Stackoverflow.com/questions/925225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/79980/" ]
Just track it in a variable. The example assumes that "clicked" is defined something (a closure that generates the event handler function would be good) and initilised to a value of "0" or other non-true value. ``` if (clicked) { a(); } else { b(); } clicked = 1; ```
I don't know what exactly you are trying to do. But one possible solution could be to define new attribute for each div, let say "was\_clicked" and when you can do the following: ``` div.click( function(event) { if ( $( "div[was_clicked=true]").length > 0) // some of the div was clicked // you can iterate over each clicked div by $( "div[was_clicked=true]").each( ...) $(this).attr( "was_clicked", "true"); }); ```
13,981,621
I have a program that sets proxy settings and it has worked through prior versions of Windows until Windows 8 and IE 10. It sets the keys below. In Windows 8, other browsers (like firefox) recognize the change and use the proxy settings. For IE 10, the global policy goes into effect (settings greyed out) but not the proxy settings themselves. If I set ProxySettingsPerUser to 1 and copy the same keys inth HKCU, then IE uses them for the current user ... but I need this to cover all users. ``` HKLM "SOFTWARE\Policies\Microsoft\Internet Explorer\Control Panel" "Proxy" = 1 HKLM "SOFTWARE\Policies\Microsoft\Internet Explorer\Control Panel" "AutoConfig" = 1 HKLM "SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings" "ProxySettingsPerUser" = 0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings" "DialupUseLanSettings" = 1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings" "WarnOnIntranet" = 0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings" "ProxyEnable" = 1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings" "MigrateProxy" = 1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings" "ProxyServer" = <server name> HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings" "ProxyOverride" = <list of exceptions> ```
2012/12/20
[ "https://Stackoverflow.com/questions/13981621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1389528/" ]
[HKEY\_LOCAL\_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings] "ProxySettingsPerUser"=dword:00000000
Create a .reg file containing your proxy settings for your users. Create a batch file setting it to setting it to run the .reg file with the extension /s On a server using a logon script, tell the logon to run the batch file. Jason
13,981,621
I have a program that sets proxy settings and it has worked through prior versions of Windows until Windows 8 and IE 10. It sets the keys below. In Windows 8, other browsers (like firefox) recognize the change and use the proxy settings. For IE 10, the global policy goes into effect (settings greyed out) but not the proxy settings themselves. If I set ProxySettingsPerUser to 1 and copy the same keys inth HKCU, then IE uses them for the current user ... but I need this to cover all users. ``` HKLM "SOFTWARE\Policies\Microsoft\Internet Explorer\Control Panel" "Proxy" = 1 HKLM "SOFTWARE\Policies\Microsoft\Internet Explorer\Control Panel" "AutoConfig" = 1 HKLM "SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings" "ProxySettingsPerUser" = 0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings" "DialupUseLanSettings" = 1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings" "WarnOnIntranet" = 0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings" "ProxyEnable" = 1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings" "MigrateProxy" = 1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings" "ProxyServer" = <server name> HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings" "ProxyOverride" = <list of exceptions> ```
2012/12/20
[ "https://Stackoverflow.com/questions/13981621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1389528/" ]
[HKEY\_LOCAL\_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings] "ProxySettingsPerUser"=dword:00000000
TRY HKEY\_LOCAL\_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings EnableAutoProxyResultCache = dword: 0
2,619,207
is $$(\frac{\partial P}{\partial T})^2=\frac{\partial^2P}{\partial T ^2}$$ holds? thank you
2018/01/24
[ "https://math.stackexchange.com/questions/2619207", "https://math.stackexchange.com", "https://math.stackexchange.com/users/114138/" ]
That equality does not hold; their perceived similarity comes from notation alone. The $^2$ in the RHS refers to the fact that it's a *second* derivative. $$(\frac{\partial P}{\partial T})^2=\frac{\partial P}{\partial T}\cdot\frac{\partial P}{\partial T}$$ and $$\frac{\partial^2P}{\partial T ^2} = \frac{\partial}{\partial T}\bigg[\frac{\partial P}{\partial T}\bigg]$$ Paul's example is a good one: Let $P = T + c$. Then $$(\frac{\partial P}{\partial T})^2=\frac{\partial P}{\partial T}\cdot\frac{\partial P}{\partial T} = (1)(1) = 1$$ and $$\frac{\partial^2P}{\partial T ^2} = \frac{\partial}{\partial T}\bigg[\frac{\partial P}{\partial T}\bigg] = \frac{\partial}{\partial T}\bigg[1\bigg] = 0$$
No. Counterexample: $P(T)=T$ $$ \left(\frac{\partial P}{\partial T}\right)^2=1\neq 0=\frac{\partial^2P}{\partial T^2}. $$
2,619,207
is $$(\frac{\partial P}{\partial T})^2=\frac{\partial^2P}{\partial T ^2}$$ holds? thank you
2018/01/24
[ "https://math.stackexchange.com/questions/2619207", "https://math.stackexchange.com", "https://math.stackexchange.com/users/114138/" ]
That equality does not hold; their perceived similarity comes from notation alone. The $^2$ in the RHS refers to the fact that it's a *second* derivative. $$(\frac{\partial P}{\partial T})^2=\frac{\partial P}{\partial T}\cdot\frac{\partial P}{\partial T}$$ and $$\frac{\partial^2P}{\partial T ^2} = \frac{\partial}{\partial T}\bigg[\frac{\partial P}{\partial T}\bigg]$$ Paul's example is a good one: Let $P = T + c$. Then $$(\frac{\partial P}{\partial T})^2=\frac{\partial P}{\partial T}\cdot\frac{\partial P}{\partial T} = (1)(1) = 1$$ and $$\frac{\partial^2P}{\partial T ^2} = \frac{\partial}{\partial T}\bigg[\frac{\partial P}{\partial T}\bigg] = \frac{\partial}{\partial T}\bigg[1\bigg] = 0$$
No. $\dfrac{\partial^2P}{\partial T^2}\;$ is denoted with the ewponent at a different place in the numerator and the denominator because it is a contraction for $$\dfrac{\partial }{\partial T}\biggl(\dfrac{\partial }{\partial T}\biggr)(P). $$ For functions of a single variable, equality would mean that $$f''=(f')^2, $$ which is clearly absurd: a polynomial of degree $n$ would have a second derivative of degree both $n-2$ and $2(n-1)$.
2,619,207
is $$(\frac{\partial P}{\partial T})^2=\frac{\partial^2P}{\partial T ^2}$$ holds? thank you
2018/01/24
[ "https://math.stackexchange.com/questions/2619207", "https://math.stackexchange.com", "https://math.stackexchange.com/users/114138/" ]
That equality does not hold; their perceived similarity comes from notation alone. The $^2$ in the RHS refers to the fact that it's a *second* derivative. $$(\frac{\partial P}{\partial T})^2=\frac{\partial P}{\partial T}\cdot\frac{\partial P}{\partial T}$$ and $$\frac{\partial^2P}{\partial T ^2} = \frac{\partial}{\partial T}\bigg[\frac{\partial P}{\partial T}\bigg]$$ Paul's example is a good one: Let $P = T + c$. Then $$(\frac{\partial P}{\partial T})^2=\frac{\partial P}{\partial T}\cdot\frac{\partial P}{\partial T} = (1)(1) = 1$$ and $$\frac{\partial^2P}{\partial T ^2} = \frac{\partial}{\partial T}\bigg[\frac{\partial P}{\partial T}\bigg] = \frac{\partial}{\partial T}\bigg[1\bigg] = 0$$
No. For example, let $P(T,V)=aT+bV$... Then $\frac {\partial P} {\partial T}=A$, so $(\frac {\partial P} {\partial T})^2=a^2$, but $\frac {\partial ^2 P}{\partial T ^2}=0$...
28,386,890
Has anyone successfully set up VSO & Jenkins & TFS? Server URL: `https://<myproject>.visualstudio.com/DefaultCollection` Login name and user password (using alternative credentials) What domain name did you use? `<domain>\username` If I run the tf command in Command Prompt, it succeeds, but Jenkins shows the same command as failing. I'm lost as to how to debug this. I also tried setting cached credentials for TFS, and not caching them. It seems as though Jenkins does not have cached credentials, but my command prompt does? Why would my system have stored credentials for me, but not Jenkins? Error from Jenkins: `TF30063: You are not authorized to access https://windwardstudios.visualstudio.com/DefaultCollection`
2015/02/07
[ "https://Stackoverflow.com/questions/28386890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3653785/" ]
This is an answer, but may not be what you want to hear. This used to work for us about a year ago. It required someone to stay logged into VisualStudio.com with his MSDN credentials on the build server. Then we simply didn't use credentials in the Jenkins TFS plug-in. Then one day, that simply stopped working. We tried alternative credentials, as @MrHinsh suggested, but never got it to work. Eventually we gave up and switched all of our TFS repositories to git (but still hosted on VisualStudio.com). That **does** work with the alternate credentials, and we have been very pleased since.
You need to configure Jenkins yo use the alternate credentials. It will not work with any other configuration and the credentials are never stored. Every command that you pass must include the same creds.
28,386,890
Has anyone successfully set up VSO & Jenkins & TFS? Server URL: `https://<myproject>.visualstudio.com/DefaultCollection` Login name and user password (using alternative credentials) What domain name did you use? `<domain>\username` If I run the tf command in Command Prompt, it succeeds, but Jenkins shows the same command as failing. I'm lost as to how to debug this. I also tried setting cached credentials for TFS, and not caching them. It seems as though Jenkins does not have cached credentials, but my command prompt does? Why would my system have stored credentials for me, but not Jenkins? Error from Jenkins: `TF30063: You are not authorized to access https://windwardstudios.visualstudio.com/DefaultCollection`
2015/02/07
[ "https://Stackoverflow.com/questions/28386890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3653785/" ]
With the release of [version 4.0.0](https://github.com/jenkinsci/tfs-plugin/releases/tag/tfs-4.0.0 "Release notes on GitHub") of the [Jenkins Team Foundation Server plugin](https://wiki.jenkins-ci.org/display/JENKINS/Team+Foundation+Server+Plugin "TFS plugin wiki page"), Team Foundation Version Control (TFVC) from Visual Studio Online (VSO) is now officially supported and both Personal Access Tokens (PAT) & alternate credentials can be used. See the section [User name and password](https://github.com/jenkinsci/tfs-plugin#user-name-and-password "How to configure the user name and user password") in the wiki page.
You need to configure Jenkins yo use the alternate credentials. It will not work with any other configuration and the credentials are never stored. Every command that you pass must include the same creds.
28,386,890
Has anyone successfully set up VSO & Jenkins & TFS? Server URL: `https://<myproject>.visualstudio.com/DefaultCollection` Login name and user password (using alternative credentials) What domain name did you use? `<domain>\username` If I run the tf command in Command Prompt, it succeeds, but Jenkins shows the same command as failing. I'm lost as to how to debug this. I also tried setting cached credentials for TFS, and not caching them. It seems as though Jenkins does not have cached credentials, but my command prompt does? Why would my system have stored credentials for me, but not Jenkins? Error from Jenkins: `TF30063: You are not authorized to access https://windwardstudios.visualstudio.com/DefaultCollection`
2015/02/07
[ "https://Stackoverflow.com/questions/28386890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3653785/" ]
With the release of [version 4.0.0](https://github.com/jenkinsci/tfs-plugin/releases/tag/tfs-4.0.0 "Release notes on GitHub") of the [Jenkins Team Foundation Server plugin](https://wiki.jenkins-ci.org/display/JENKINS/Team+Foundation+Server+Plugin "TFS plugin wiki page"), Team Foundation Version Control (TFVC) from Visual Studio Online (VSO) is now officially supported and both Personal Access Tokens (PAT) & alternate credentials can be used. See the section [User name and password](https://github.com/jenkinsci/tfs-plugin#user-name-and-password "How to configure the user name and user password") in the wiki page.
This is an answer, but may not be what you want to hear. This used to work for us about a year ago. It required someone to stay logged into VisualStudio.com with his MSDN credentials on the build server. Then we simply didn't use credentials in the Jenkins TFS plug-in. Then one day, that simply stopped working. We tried alternative credentials, as @MrHinsh suggested, but never got it to work. Eventually we gave up and switched all of our TFS repositories to git (but still hosted on VisualStudio.com). That **does** work with the alternate credentials, and we have been very pleased since.