qid
int64
1
74.7M
question
stringlengths
15
55.4k
date
stringlengths
10
10
metadata
sequencelengths
3
3
response_j
stringlengths
2
32.4k
response_k
stringlengths
9
40.5k
37,990,519
Any idea how to use Carrierwave to upload images with Heroku. I added this to the uploader file: ``` def cache_dir "#{Rails.root}/tmp/uploads" end ``` but images still don't save! After uploading an image, it saves and once you refresh the page, the image breaks. Any help would be appreciated! Thanks
2016/06/23
[ "https://Stackoverflow.com/questions/37990519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6094382/" ]
I do not think you can use Heroku and upload images without 3rd party storage service like Amazon S3. <https://devcenter.heroku.com/articles/s3> Heroku allows you store files inside tmp but just in order to send to a 3rd party service. Inside carrierwave uploader class you can set for example storage :fog instead of default :file and setup uploads to AWS S3. There are other options as well. One thing is that if you are using a free tier instance on Heroku your upload needs to finish in abut a minute - I would recommend setup where you upload files directly to s3 account. <https://github.com/dwilkie/carrierwave_direct> Hope it helps
The filesystem on Heroku is not persisted. Only files uploaded through deployment mechanisms (git push) are "persisted". Others like the ones in your `"#{Rails.root}/tmp/uploads"` folder will be erased. That's why they are disappearing. --- I have answered a [similar question here](https://stackoverflow.com/a/37361940/52317). Here is a quote: Your dyno on Heroku has a "read-only" filesystem. In a sense, your files will not be persisted between your dyno restarts and there is no guarantee that they will persist between any two requests. Here is an [excerpt from the docs](https://devcenter.heroku.com/articles/one-off-dynos#formation-dynos-vs-one-off-dynos): > > Each dyno has its own ephemeral file system, not shared with any other dyno, that is discarded as soon as you disconnect. This file system is populated with the slug archive so one-off dynos can make full use of anything deployed in the application. > > > You can use the `#{Rails.root}/tmp` folder as temporary folder, but you need to upload your files to some external storage (S3, some CDN, etc.). Heroku has some addons that makes it easy to handle.
28,834,395
I have written code to display a simple alert popup when a button is clicked. When trying the app in simulator iPhone 4s (8.1), it's working as expected, but when trying in simulator iPhone 4s (7.1), the app keeps crashing. Here the code: @IBAction func buttonPressed(sender: UIButton) { ``` let controller = UIAlertController(title: "This is a title", message: "Hello, my friend", preferredStyle: UIAlertControllerStyle.Alert) let cancelAction = UIAlertAction(title: "Phew!", style: .Cancel, handler: nil) controller.addAction(cancelAction) self.presentViewController(controller, animated: true, completion: nil) } ``` Here's the error message: The first line code (the one creating the "controller" constant) is highlighted in green with the message "Thread 1: EXC\_BAD\_ACCESS(Code=1,address=0x10)" I would appreciate any help
2015/03/03
[ "https://Stackoverflow.com/questions/28834395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1903379/" ]
UIAlertController is available for iOS >= 8.0 You have to use UIAlertView for iOS < 8.0
Thanks to recommended links from Dom Bryan, I managed the following solution: @IBAction func buttonPressed(sender: UIButton) { ``` if NSClassFromString("UIAlertController") == nil{ let alert = UIAlertView(title: "This is a title", message: "I am an iOS7 alert", delegate: self, cancelButtonTitle: "Phew!") alert.show() }else{ let controller = UIAlertController(title: "This is a title", message: "Hello, my friend", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Phew!", style: .Cancel, handler: nil) controller.addAction(cancelAction) self.presentViewController(controller, animated: true, completion: nil) } } ``` And it's working fine on iOS7 and iOS8 devices
28,834,395
I have written code to display a simple alert popup when a button is clicked. When trying the app in simulator iPhone 4s (8.1), it's working as expected, but when trying in simulator iPhone 4s (7.1), the app keeps crashing. Here the code: @IBAction func buttonPressed(sender: UIButton) { ``` let controller = UIAlertController(title: "This is a title", message: "Hello, my friend", preferredStyle: UIAlertControllerStyle.Alert) let cancelAction = UIAlertAction(title: "Phew!", style: .Cancel, handler: nil) controller.addAction(cancelAction) self.presentViewController(controller, animated: true, completion: nil) } ``` Here's the error message: The first line code (the one creating the "controller" constant) is highlighted in green with the message "Thread 1: EXC\_BAD\_ACCESS(Code=1,address=0x10)" I would appreciate any help
2015/03/03
[ "https://Stackoverflow.com/questions/28834395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1903379/" ]
UIAlertController is only available in iOS 8.0 and on wards unfortunately, here is documentation and it states this on the right: <https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIAlertController_class/#//apple_ref/doc/uid/TP40014538-CH1-SW2> I believe this replaced the now deprecated UIAlertView which can be found here in Apple Documentation: <https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIAlertView_Class/index.html#//apple_ref/occ/cl/UIAlertView> Swift doesn't like the old but consider and "if" clause and create both a UIAlertView and UIAlertController for the respective iOS system using the app.
Thanks to recommended links from Dom Bryan, I managed the following solution: @IBAction func buttonPressed(sender: UIButton) { ``` if NSClassFromString("UIAlertController") == nil{ let alert = UIAlertView(title: "This is a title", message: "I am an iOS7 alert", delegate: self, cancelButtonTitle: "Phew!") alert.show() }else{ let controller = UIAlertController(title: "This is a title", message: "Hello, my friend", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Phew!", style: .Cancel, handler: nil) controller.addAction(cancelAction) self.presentViewController(controller, animated: true, completion: nil) } } ``` And it's working fine on iOS7 and iOS8 devices
13,034,468
This would seem stupid but i can't seem to understand the documentation. I'm talking about [This](https://github.com/blueimp/jQuery-File-Upload) plugin for file upload. Now according to the documentation there's an option : > > **formData** > > > Additional form data to be sent along with the file uploads can be set using this > option, which accepts an array of objects with name and value properties, a function > returning such an array, a FormData object (for XHR file uploads), or a simple object. > The form of the first fileInput is given as parameter to the function. > > > **Note**: Additional form data is ignored when the multipart option is set to false. > > > Type: Array, Object, function or FormData Default: A function > returning the form fields as serialized Array: > > > > ``` > function (form) { > return form.serializeArray(); > } > > ``` > > **Example:** > > > [ > { > name: 'a', > value: 1 > }, > { > name: 'b', > value: 2 > } ] > > > Which i fail to understand what i'm suppoused to do with that. This is how i initialize the plugin : ``` $('#add_image_upload').fileupload({ dataType: 'json', sequentialUploads: true, formData : getDate }); ``` And this is my attempt to the function : ``` function getDate(){ //if user didn't selected a date if(!selectedDate || selectedDate=="undefined"){ selectedDate = "1/1/"+$('#timeline').html(); } var date= new Array(selectedDate); return date; } ```
2012/10/23
[ "https://Stackoverflow.com/questions/13034468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1026199/" ]
try turning your data into in object - with what they showed in their example ``` $('#add_image_upload').fileupload({ dataType: 'json', sequentialUploads: true, formData : {name:'thedate',value:getDate} }); ``` Then to add more params ``` //name of param // value formData : [{name:'thedate',value:getDate},{name:'thedate2',value:'seconddate'},etc..] ``` > > Example: > > > [ { name: 'a', value: 1 }, { name: 'b', value: 2 } ] > > > Changing `thedate` with whatever you want to name the param Though it sounds like a simple object should work fine ``` //name:value formData : {thedate:getDate} ```
Do you have `multipart` set to `false` on your form? Also, ensure the format of what you're sending back is acceptable. Try hard-coding the following line and sending back the info: ``` new dateobject = { "date": "1/1/2012" } ```
26,881,665
I have a certain number of files for which I need the filenames in my program. The files have a fixed naming fashion i.e. (prefix + digits).jpg. For e.g.: `head001.jpg`, `head002.jpg`, `head003.jpg` etc. etc. The number of digits, in the end, can be varying - so the program has variables to change where the file naming starts from, where it ends and how many number digits are used in the naming. For e.g: A second scenario could be - `tail00001.jpg`, `tail00002.jpg`, `tail00003.jpg` etc. until `tail00100.jpg` And in this case: start digit would be 0, end digit would be 100 and numDigits would be 5 In C++, I’ve seen this formatting being done as follows: `format <<prefix<<"%0"<<numDigits<<"d."<<filetype;` //where `format` is a `stringstream` However, I’m not quite sure about the best way to do this in C# and would like to know how to solve this.
2014/11/12
[ "https://Stackoverflow.com/questions/26881665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1240679/" ]
Just use `string.Format`, with a *precision specifier* saying how many digits you want: ``` string name = string.Format("tail{0:d6}.jpg", index); ``` See the MSDN documentation for [standard numeric string formats](http://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx) for more details. You can build the string format up programmatically of course: ``` string name = string.Format("tail{0:d" + digits + "}.jpg", index); ``` Or use `PadLeft` as suggested by Vano. You might still want to use `string.Format` though: ``` string name = string.Format("tail{0}.jpg", index.ToString().PadLeft(digits, '0')); ``` Using `PadLeft` has the advantage that it's easier to change the padding value, although I would imagine you'd always want it to be `0` anyway.
string has *PadLeft* method: ``` int n1 = 1; string t1 = n1.ToString().PadLeft(5, '0'); // This will return 00001 int n10 = 10; string t2 = n10.ToString().PadLeft(5, '0'); // This will return 00010 and so on... ```
26,881,665
I have a certain number of files for which I need the filenames in my program. The files have a fixed naming fashion i.e. (prefix + digits).jpg. For e.g.: `head001.jpg`, `head002.jpg`, `head003.jpg` etc. etc. The number of digits, in the end, can be varying - so the program has variables to change where the file naming starts from, where it ends and how many number digits are used in the naming. For e.g: A second scenario could be - `tail00001.jpg`, `tail00002.jpg`, `tail00003.jpg` etc. until `tail00100.jpg` And in this case: start digit would be 0, end digit would be 100 and numDigits would be 5 In C++, I’ve seen this formatting being done as follows: `format <<prefix<<"%0"<<numDigits<<"d."<<filetype;` //where `format` is a `stringstream` However, I’m not quite sure about the best way to do this in C# and would like to know how to solve this.
2014/11/12
[ "https://Stackoverflow.com/questions/26881665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1240679/" ]
Just use `string.Format`, with a *precision specifier* saying how many digits you want: ``` string name = string.Format("tail{0:d6}.jpg", index); ``` See the MSDN documentation for [standard numeric string formats](http://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx) for more details. You can build the string format up programmatically of course: ``` string name = string.Format("tail{0:d" + digits + "}.jpg", index); ``` Or use `PadLeft` as suggested by Vano. You might still want to use `string.Format` though: ``` string name = string.Format("tail{0}.jpg", index.ToString().PadLeft(digits, '0')); ``` Using `PadLeft` has the advantage that it's easier to change the padding value, although I would imagine you'd always want it to be `0` anyway.
> > ..and in this case: start digit would be 0, end digit would be 100 and > numDigits would be 5 > > > You could use [`String.Format`](http://msdn.microsoft.com/en-us/library/b1csw23d(v=vs.110).aspx) and the [decimal format/precision specifier "D"`](http://msdn.microsoft.com/en-us/library/vstudio/dwhawy9k(v=vs.100).aspx#DFormatString) and a for-loop: ``` int start = 0; int end = 100; int numDigits = 5; string name = "tail"; string extension = ".jpg"; for(int i = start; i <= end; i++) { string fileName = string.Format( "{0}{1}{2}", name, i.ToString("D" + numDigits), extension); Console.WriteLine(fileName); } ``` Outputs: ``` tail00000.jpg tail00001.jpg tail00002.jpg tail00003.jpg tail00004.jpg tail00005.jpg tail00006.jpg tail00007.jpg tail00008.jpg tail00009.jpg tail00010.jpg .... tail100.jpg ```
26,881,665
I have a certain number of files for which I need the filenames in my program. The files have a fixed naming fashion i.e. (prefix + digits).jpg. For e.g.: `head001.jpg`, `head002.jpg`, `head003.jpg` etc. etc. The number of digits, in the end, can be varying - so the program has variables to change where the file naming starts from, where it ends and how many number digits are used in the naming. For e.g: A second scenario could be - `tail00001.jpg`, `tail00002.jpg`, `tail00003.jpg` etc. until `tail00100.jpg` And in this case: start digit would be 0, end digit would be 100 and numDigits would be 5 In C++, I’ve seen this formatting being done as follows: `format <<prefix<<"%0"<<numDigits<<"d."<<filetype;` //where `format` is a `stringstream` However, I’m not quite sure about the best way to do this in C# and would like to know how to solve this.
2014/11/12
[ "https://Stackoverflow.com/questions/26881665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1240679/" ]
Just use `string.Format`, with a *precision specifier* saying how many digits you want: ``` string name = string.Format("tail{0:d6}.jpg", index); ``` See the MSDN documentation for [standard numeric string formats](http://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx) for more details. You can build the string format up programmatically of course: ``` string name = string.Format("tail{0:d" + digits + "}.jpg", index); ``` Or use `PadLeft` as suggested by Vano. You might still want to use `string.Format` though: ``` string name = string.Format("tail{0}.jpg", index.ToString().PadLeft(digits, '0')); ``` Using `PadLeft` has the advantage that it's easier to change the padding value, although I would imagine you'd always want it to be `0` anyway.
You can do this using string.Format ``` var result = string.Format("{0}{1:00000}{2}", prefix, number, filetype) ``` Or you could use padleft ``` var result = prefix + number.ToString().PadLeft('0', numDigits) + "." + extension; ``` Or you can use a mix of the two :)
26,881,665
I have a certain number of files for which I need the filenames in my program. The files have a fixed naming fashion i.e. (prefix + digits).jpg. For e.g.: `head001.jpg`, `head002.jpg`, `head003.jpg` etc. etc. The number of digits, in the end, can be varying - so the program has variables to change where the file naming starts from, where it ends and how many number digits are used in the naming. For e.g: A second scenario could be - `tail00001.jpg`, `tail00002.jpg`, `tail00003.jpg` etc. until `tail00100.jpg` And in this case: start digit would be 0, end digit would be 100 and numDigits would be 5 In C++, I’ve seen this formatting being done as follows: `format <<prefix<<"%0"<<numDigits<<"d."<<filetype;` //where `format` is a `stringstream` However, I’m not quite sure about the best way to do this in C# and would like to know how to solve this.
2014/11/12
[ "https://Stackoverflow.com/questions/26881665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1240679/" ]
Just use `string.Format`, with a *precision specifier* saying how many digits you want: ``` string name = string.Format("tail{0:d6}.jpg", index); ``` See the MSDN documentation for [standard numeric string formats](http://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx) for more details. You can build the string format up programmatically of course: ``` string name = string.Format("tail{0:d" + digits + "}.jpg", index); ``` Or use `PadLeft` as suggested by Vano. You might still want to use `string.Format` though: ``` string name = string.Format("tail{0}.jpg", index.ToString().PadLeft(digits, '0')); ``` Using `PadLeft` has the advantage that it's easier to change the padding value, although I would imagine you'd always want it to be `0` anyway.
**For modern .NET 5.0+** (2021 update) ``` int myint = 100; string zeroPadded = $"{myint:d8}"; // "00000100" string spacePadded = $"{myint,8}"; // " 100" ```
26,881,665
I have a certain number of files for which I need the filenames in my program. The files have a fixed naming fashion i.e. (prefix + digits).jpg. For e.g.: `head001.jpg`, `head002.jpg`, `head003.jpg` etc. etc. The number of digits, in the end, can be varying - so the program has variables to change where the file naming starts from, where it ends and how many number digits are used in the naming. For e.g: A second scenario could be - `tail00001.jpg`, `tail00002.jpg`, `tail00003.jpg` etc. until `tail00100.jpg` And in this case: start digit would be 0, end digit would be 100 and numDigits would be 5 In C++, I’ve seen this formatting being done as follows: `format <<prefix<<"%0"<<numDigits<<"d."<<filetype;` //where `format` is a `stringstream` However, I’m not quite sure about the best way to do this in C# and would like to know how to solve this.
2014/11/12
[ "https://Stackoverflow.com/questions/26881665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1240679/" ]
string has *PadLeft* method: ``` int n1 = 1; string t1 = n1.ToString().PadLeft(5, '0'); // This will return 00001 int n10 = 10; string t2 = n10.ToString().PadLeft(5, '0'); // This will return 00010 and so on... ```
> > ..and in this case: start digit would be 0, end digit would be 100 and > numDigits would be 5 > > > You could use [`String.Format`](http://msdn.microsoft.com/en-us/library/b1csw23d(v=vs.110).aspx) and the [decimal format/precision specifier "D"`](http://msdn.microsoft.com/en-us/library/vstudio/dwhawy9k(v=vs.100).aspx#DFormatString) and a for-loop: ``` int start = 0; int end = 100; int numDigits = 5; string name = "tail"; string extension = ".jpg"; for(int i = start; i <= end; i++) { string fileName = string.Format( "{0}{1}{2}", name, i.ToString("D" + numDigits), extension); Console.WriteLine(fileName); } ``` Outputs: ``` tail00000.jpg tail00001.jpg tail00002.jpg tail00003.jpg tail00004.jpg tail00005.jpg tail00006.jpg tail00007.jpg tail00008.jpg tail00009.jpg tail00010.jpg .... tail100.jpg ```
26,881,665
I have a certain number of files for which I need the filenames in my program. The files have a fixed naming fashion i.e. (prefix + digits).jpg. For e.g.: `head001.jpg`, `head002.jpg`, `head003.jpg` etc. etc. The number of digits, in the end, can be varying - so the program has variables to change where the file naming starts from, where it ends and how many number digits are used in the naming. For e.g: A second scenario could be - `tail00001.jpg`, `tail00002.jpg`, `tail00003.jpg` etc. until `tail00100.jpg` And in this case: start digit would be 0, end digit would be 100 and numDigits would be 5 In C++, I’ve seen this formatting being done as follows: `format <<prefix<<"%0"<<numDigits<<"d."<<filetype;` //where `format` is a `stringstream` However, I’m not quite sure about the best way to do this in C# and would like to know how to solve this.
2014/11/12
[ "https://Stackoverflow.com/questions/26881665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1240679/" ]
string has *PadLeft* method: ``` int n1 = 1; string t1 = n1.ToString().PadLeft(5, '0'); // This will return 00001 int n10 = 10; string t2 = n10.ToString().PadLeft(5, '0'); // This will return 00010 and so on... ```
You can do this using string.Format ``` var result = string.Format("{0}{1:00000}{2}", prefix, number, filetype) ``` Or you could use padleft ``` var result = prefix + number.ToString().PadLeft('0', numDigits) + "." + extension; ``` Or you can use a mix of the two :)
26,881,665
I have a certain number of files for which I need the filenames in my program. The files have a fixed naming fashion i.e. (prefix + digits).jpg. For e.g.: `head001.jpg`, `head002.jpg`, `head003.jpg` etc. etc. The number of digits, in the end, can be varying - so the program has variables to change where the file naming starts from, where it ends and how many number digits are used in the naming. For e.g: A second scenario could be - `tail00001.jpg`, `tail00002.jpg`, `tail00003.jpg` etc. until `tail00100.jpg` And in this case: start digit would be 0, end digit would be 100 and numDigits would be 5 In C++, I’ve seen this formatting being done as follows: `format <<prefix<<"%0"<<numDigits<<"d."<<filetype;` //where `format` is a `stringstream` However, I’m not quite sure about the best way to do this in C# and would like to know how to solve this.
2014/11/12
[ "https://Stackoverflow.com/questions/26881665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1240679/" ]
string has *PadLeft* method: ``` int n1 = 1; string t1 = n1.ToString().PadLeft(5, '0'); // This will return 00001 int n10 = 10; string t2 = n10.ToString().PadLeft(5, '0'); // This will return 00010 and so on... ```
**For modern .NET 5.0+** (2021 update) ``` int myint = 100; string zeroPadded = $"{myint:d8}"; // "00000100" string spacePadded = $"{myint,8}"; // " 100" ```
58,690,044
I wanted to have pound sign in sql query result as £ , but when I am executing this query, it is not displaying expected symbol: ``` select chr(169) from dual; ``` Actual result is: � Expected Result:£
2019/11/04
[ "https://Stackoverflow.com/questions/58690044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2758176/" ]
This work for me: ``` select '£' from dual; select concat('£' , 500) from dual; ``` Regards!
There is no ASCII value for £ sign that why it's not showing pound sign but if you want to show pound your need to change your `NLS_TERRITORY` setting then use below ``` select to_char(123, 'L999,999.00') from dual; ``` right now it will show $ because oracle by default setting is american $ [list of parameter for NLS\_TERRITORY](https://www.oracle.com/webfolder/community/oracle_database/4039558.html)
58,690,044
I wanted to have pound sign in sql query result as £ , but when I am executing this query, it is not displaying expected symbol: ``` select chr(169) from dual; ``` Actual result is: � Expected Result:£
2019/11/04
[ "https://Stackoverflow.com/questions/58690044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2758176/" ]
This work for me: ``` select '£' from dual; select concat('£' , 500) from dual; ``` Regards!
Try This. ``` SELECT CHAR(0163) FROM TABLE_NAME; ```
4,509,658
I am trying to decide on the best branching strategy for a web application project. Here is what I have come up with until now and I would greatly appreciate any comments and experiences. The way I see it there are two main branching strategies: "branch by release" and "branch by feature". **"Branch by release"**: Development takes place on the trunk. When the time for a release is near, a branch is made for that release. This branch is then stabilized/tested and finally a release is made. After the release, the branch is merged back into the trunk, while keeping the release branch alive for bug-fixing. Is a bug-fix applied, then it is merged into the trunk ( if the development on the trunk hasn't eclipsed the bug in other means). New features are added to the trunk and don't affect the release branch. When a new release time nears, a new release branch is created a.s.o. **"Branch by feature"**: The trunk is always the "production" trunk (the code that is live). Bugfixes are commited directly to the trunk. Features for the next release are developed in feature branches.Bugfixes are merged from time-to-time into the feature branches. When release time comes, the features branches are merged into the trunk and the cycle of life continues. Now the way I see it the big practical difference between these two strategies is that "by release" allows you to maintane different production versions of you software ( when client A has version 1 and client B version 1.5, client is the paying customer in this case). In contrast using the "by feature" strategy you can only support the current production version ( all clients are using latest version). Since in a typical *web application* all clients are using the same "latest" version (since they all access the same server), I would assume that the "by feature" approach is the most commonly used. It removes the need to merge "across the hierarchy", say when a bugfix has to be applied to all 3 release versions. So my current status is that I should go with "branch by feature". If it matters, my team is not very skilled.
2010/12/22
[ "https://Stackoverflow.com/questions/4509658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110453/" ]
If you only have one release live at any time, and you do all development in a single feature branch, then these approaches are effectively the same. If branch-by-feature to you means having a several branches on the go at once, i'd avoid it like the plague. More branches means more merging, which is a pain in itself, and more integration hell. It's far better to do continuous integration to a single codeline. If your deployment process is any more involved than branch, test, go live, then an advantage of branch-by-release is that you can have multiple release branches going at once, in different phases: one live and being bugfixed as necessary, and another one being stabilised, tested, going through acceptance, etc, while development continues on the trunk. If you have a live trunk, on the other hand, once you merge a feature branch in with a view to taking it live, you've lost your ability to do bugfixes to the current live system. The feature branch merge becomes a point of no return.
I tend to use Git for my projects, but the process I tend to follow goes like this (and should work for Subversion as well): * for each new feature, create a branch for that feature. * When everything works, merge it into the `staging` branch, and deploy it to the staging server (you do have one of those, right?) * Once we're sure the client is happy with what's on staging, we merge the staging branch into the production branch, tag it as something like `production_release_22` or `production_release_new_feature_x`, and then deploy that tag to the production server. Tags are *never*, *ever* updated - once something gets deployed, it stays that way until more changes are built, tested, and tagged - and then the new tag is deployed. By making sure that it's *tags* getting deployed and not *branches*, I keep myself (or others) from doing things like "I'll just commit this one quick change and update the server without testing it". It's worked pretty well for me so far.
4,509,658
I am trying to decide on the best branching strategy for a web application project. Here is what I have come up with until now and I would greatly appreciate any comments and experiences. The way I see it there are two main branching strategies: "branch by release" and "branch by feature". **"Branch by release"**: Development takes place on the trunk. When the time for a release is near, a branch is made for that release. This branch is then stabilized/tested and finally a release is made. After the release, the branch is merged back into the trunk, while keeping the release branch alive for bug-fixing. Is a bug-fix applied, then it is merged into the trunk ( if the development on the trunk hasn't eclipsed the bug in other means). New features are added to the trunk and don't affect the release branch. When a new release time nears, a new release branch is created a.s.o. **"Branch by feature"**: The trunk is always the "production" trunk (the code that is live). Bugfixes are commited directly to the trunk. Features for the next release are developed in feature branches.Bugfixes are merged from time-to-time into the feature branches. When release time comes, the features branches are merged into the trunk and the cycle of life continues. Now the way I see it the big practical difference between these two strategies is that "by release" allows you to maintane different production versions of you software ( when client A has version 1 and client B version 1.5, client is the paying customer in this case). In contrast using the "by feature" strategy you can only support the current production version ( all clients are using latest version). Since in a typical *web application* all clients are using the same "latest" version (since they all access the same server), I would assume that the "by feature" approach is the most commonly used. It removes the need to merge "across the hierarchy", say when a bugfix has to be applied to all 3 release versions. So my current status is that I should go with "branch by feature". If it matters, my team is not very skilled.
2010/12/22
[ "https://Stackoverflow.com/questions/4509658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110453/" ]
If you only have one release live at any time, and you do all development in a single feature branch, then these approaches are effectively the same. If branch-by-feature to you means having a several branches on the go at once, i'd avoid it like the plague. More branches means more merging, which is a pain in itself, and more integration hell. It's far better to do continuous integration to a single codeline. If your deployment process is any more involved than branch, test, go live, then an advantage of branch-by-release is that you can have multiple release branches going at once, in different phases: one live and being bugfixed as necessary, and another one being stabilised, tested, going through acceptance, etc, while development continues on the trunk. If you have a live trunk, on the other hand, once you merge a feature branch in with a view to taking it live, you've lost your ability to do bugfixes to the current live system. The feature branch merge becomes a point of no return.
***These choices are not mutually exclusive - use both.*** They solve different problems: **"Branch by release"** - release branch is used to ensure you can back to the source used to produce the current live version (or previous released versions) while the next version is in development. E.g. This is in order to make changes to the release version for bug fixes or backpatch features from the current development trunk. **"Branch by feature"** - used to keep a stable development trunk at all times, which is particularly useful for multiple developers and for experimental "maybe" features. I would use both, but you can forego one of the approaches if the problem it solves doesn't apply to you or if you have a different solution that problem. I strongly recommend using a modern DVCS like git or Mercurial. They are geared at parallel development, so they store changes differently than older systems, which makes merging much saner.
4,509,658
I am trying to decide on the best branching strategy for a web application project. Here is what I have come up with until now and I would greatly appreciate any comments and experiences. The way I see it there are two main branching strategies: "branch by release" and "branch by feature". **"Branch by release"**: Development takes place on the trunk. When the time for a release is near, a branch is made for that release. This branch is then stabilized/tested and finally a release is made. After the release, the branch is merged back into the trunk, while keeping the release branch alive for bug-fixing. Is a bug-fix applied, then it is merged into the trunk ( if the development on the trunk hasn't eclipsed the bug in other means). New features are added to the trunk and don't affect the release branch. When a new release time nears, a new release branch is created a.s.o. **"Branch by feature"**: The trunk is always the "production" trunk (the code that is live). Bugfixes are commited directly to the trunk. Features for the next release are developed in feature branches.Bugfixes are merged from time-to-time into the feature branches. When release time comes, the features branches are merged into the trunk and the cycle of life continues. Now the way I see it the big practical difference between these two strategies is that "by release" allows you to maintane different production versions of you software ( when client A has version 1 and client B version 1.5, client is the paying customer in this case). In contrast using the "by feature" strategy you can only support the current production version ( all clients are using latest version). Since in a typical *web application* all clients are using the same "latest" version (since they all access the same server), I would assume that the "by feature" approach is the most commonly used. It removes the need to merge "across the hierarchy", say when a bugfix has to be applied to all 3 release versions. So my current status is that I should go with "branch by feature". If it matters, my team is not very skilled.
2010/12/22
[ "https://Stackoverflow.com/questions/4509658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110453/" ]
If you only have one release live at any time, and you do all development in a single feature branch, then these approaches are effectively the same. If branch-by-feature to you means having a several branches on the go at once, i'd avoid it like the plague. More branches means more merging, which is a pain in itself, and more integration hell. It's far better to do continuous integration to a single codeline. If your deployment process is any more involved than branch, test, go live, then an advantage of branch-by-release is that you can have multiple release branches going at once, in different phases: one live and being bugfixed as necessary, and another one being stabilised, tested, going through acceptance, etc, while development continues on the trunk. If you have a live trunk, on the other hand, once you merge a feature branch in with a view to taking it live, you've lost your ability to do bugfixes to the current live system. The feature branch merge becomes a point of no return.
At the risk of confusing you further: you can have release branches **and** make all changes on feature branches. These things are not mutually exclusive. That being said, it sounds like you don't need parallel release families and you want to deploy often, perhaps even [continuously](http://radar.oreilly.com/2009/03/continuous-deployment-5-eas.html). So you would want to have a "stable trunk" that you can release at any time. Feature branches help to keep the trunk stable, because you only merge back to the trunk when the changes are done and have proven themselves. So I'd say that your choice is a good fit.
4,509,658
I am trying to decide on the best branching strategy for a web application project. Here is what I have come up with until now and I would greatly appreciate any comments and experiences. The way I see it there are two main branching strategies: "branch by release" and "branch by feature". **"Branch by release"**: Development takes place on the trunk. When the time for a release is near, a branch is made for that release. This branch is then stabilized/tested and finally a release is made. After the release, the branch is merged back into the trunk, while keeping the release branch alive for bug-fixing. Is a bug-fix applied, then it is merged into the trunk ( if the development on the trunk hasn't eclipsed the bug in other means). New features are added to the trunk and don't affect the release branch. When a new release time nears, a new release branch is created a.s.o. **"Branch by feature"**: The trunk is always the "production" trunk (the code that is live). Bugfixes are commited directly to the trunk. Features for the next release are developed in feature branches.Bugfixes are merged from time-to-time into the feature branches. When release time comes, the features branches are merged into the trunk and the cycle of life continues. Now the way I see it the big practical difference between these two strategies is that "by release" allows you to maintane different production versions of you software ( when client A has version 1 and client B version 1.5, client is the paying customer in this case). In contrast using the "by feature" strategy you can only support the current production version ( all clients are using latest version). Since in a typical *web application* all clients are using the same "latest" version (since they all access the same server), I would assume that the "by feature" approach is the most commonly used. It removes the need to merge "across the hierarchy", say when a bugfix has to be applied to all 3 release versions. So my current status is that I should go with "branch by feature". If it matters, my team is not very skilled.
2010/12/22
[ "https://Stackoverflow.com/questions/4509658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110453/" ]
If you only have one release live at any time, and you do all development in a single feature branch, then these approaches are effectively the same. If branch-by-feature to you means having a several branches on the go at once, i'd avoid it like the plague. More branches means more merging, which is a pain in itself, and more integration hell. It's far better to do continuous integration to a single codeline. If your deployment process is any more involved than branch, test, go live, then an advantage of branch-by-release is that you can have multiple release branches going at once, in different phases: one live and being bugfixed as necessary, and another one being stabilised, tested, going through acceptance, etc, while development continues on the trunk. If you have a live trunk, on the other hand, once you merge a feature branch in with a view to taking it live, you've lost your ability to do bugfixes to the current live system. The feature branch merge becomes a point of no return.
What kind of software are you developing? Shrink wrap? Open Source Project? If so, then go with the "branch by release" or "unstable trunk" approach. Especially if your release cycles are every six months to a year apart. But if your maintaining a web-based project that has changes going out on shorter frequencies, like once every few weeks or less, then go with the "branch by feature" or "stable trunk" approach. The problem with this approach is integrating multiple feature changes that have sweeping changes make the merge process less than fun. It just really gets difficult. But both of those work well, but what if you need both? That is, you have a project that deploys says once every couple of weeks with big feature changes, but you find that you have a number of bug fixes that you cannot wait for those feature changes to be ready. Trunk is your release branch with the "branch by feature" approach. What if you could get both releases and features their own branch? Check out this [blog entry](http://blogs.open.collab.net/svn/2007/11/branching-strat.html) by CollabNet's Bob Archer. His Agile Release strategy gives you best of both. I've used this. It's extremely flexible. Even though Bob doesn't show it in his diagram, you can have multiple release branches going at the same time. This means you could have one release branch that is ready for rollout to production, and another that is being prepared for final QA checks. But two things to consider: First, how good are your developers at merging? You cannot do the the agile release strategy approach by yourself, even if it is a small team. Everyone has to do their part and they really have to understand merging and the tools they are using to do the merge. Secondly, you are going to need a good grasp on changes that ready and those that are about to be. Release management is key to making this work like clock work. Each feature when ready will need to get assigned to a release branch and merged to it. **Whatever approach you choose, it comes down to what you are developing and the frequency of changes you are releasing for that development.**
4,509,658
I am trying to decide on the best branching strategy for a web application project. Here is what I have come up with until now and I would greatly appreciate any comments and experiences. The way I see it there are two main branching strategies: "branch by release" and "branch by feature". **"Branch by release"**: Development takes place on the trunk. When the time for a release is near, a branch is made for that release. This branch is then stabilized/tested and finally a release is made. After the release, the branch is merged back into the trunk, while keeping the release branch alive for bug-fixing. Is a bug-fix applied, then it is merged into the trunk ( if the development on the trunk hasn't eclipsed the bug in other means). New features are added to the trunk and don't affect the release branch. When a new release time nears, a new release branch is created a.s.o. **"Branch by feature"**: The trunk is always the "production" trunk (the code that is live). Bugfixes are commited directly to the trunk. Features for the next release are developed in feature branches.Bugfixes are merged from time-to-time into the feature branches. When release time comes, the features branches are merged into the trunk and the cycle of life continues. Now the way I see it the big practical difference between these two strategies is that "by release" allows you to maintane different production versions of you software ( when client A has version 1 and client B version 1.5, client is the paying customer in this case). In contrast using the "by feature" strategy you can only support the current production version ( all clients are using latest version). Since in a typical *web application* all clients are using the same "latest" version (since they all access the same server), I would assume that the "by feature" approach is the most commonly used. It removes the need to merge "across the hierarchy", say when a bugfix has to be applied to all 3 release versions. So my current status is that I should go with "branch by feature". If it matters, my team is not very skilled.
2010/12/22
[ "https://Stackoverflow.com/questions/4509658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110453/" ]
***These choices are not mutually exclusive - use both.*** They solve different problems: **"Branch by release"** - release branch is used to ensure you can back to the source used to produce the current live version (or previous released versions) while the next version is in development. E.g. This is in order to make changes to the release version for bug fixes or backpatch features from the current development trunk. **"Branch by feature"** - used to keep a stable development trunk at all times, which is particularly useful for multiple developers and for experimental "maybe" features. I would use both, but you can forego one of the approaches if the problem it solves doesn't apply to you or if you have a different solution that problem. I strongly recommend using a modern DVCS like git or Mercurial. They are geared at parallel development, so they store changes differently than older systems, which makes merging much saner.
I tend to use Git for my projects, but the process I tend to follow goes like this (and should work for Subversion as well): * for each new feature, create a branch for that feature. * When everything works, merge it into the `staging` branch, and deploy it to the staging server (you do have one of those, right?) * Once we're sure the client is happy with what's on staging, we merge the staging branch into the production branch, tag it as something like `production_release_22` or `production_release_new_feature_x`, and then deploy that tag to the production server. Tags are *never*, *ever* updated - once something gets deployed, it stays that way until more changes are built, tested, and tagged - and then the new tag is deployed. By making sure that it's *tags* getting deployed and not *branches*, I keep myself (or others) from doing things like "I'll just commit this one quick change and update the server without testing it". It's worked pretty well for me so far.
4,509,658
I am trying to decide on the best branching strategy for a web application project. Here is what I have come up with until now and I would greatly appreciate any comments and experiences. The way I see it there are two main branching strategies: "branch by release" and "branch by feature". **"Branch by release"**: Development takes place on the trunk. When the time for a release is near, a branch is made for that release. This branch is then stabilized/tested and finally a release is made. After the release, the branch is merged back into the trunk, while keeping the release branch alive for bug-fixing. Is a bug-fix applied, then it is merged into the trunk ( if the development on the trunk hasn't eclipsed the bug in other means). New features are added to the trunk and don't affect the release branch. When a new release time nears, a new release branch is created a.s.o. **"Branch by feature"**: The trunk is always the "production" trunk (the code that is live). Bugfixes are commited directly to the trunk. Features for the next release are developed in feature branches.Bugfixes are merged from time-to-time into the feature branches. When release time comes, the features branches are merged into the trunk and the cycle of life continues. Now the way I see it the big practical difference between these two strategies is that "by release" allows you to maintane different production versions of you software ( when client A has version 1 and client B version 1.5, client is the paying customer in this case). In contrast using the "by feature" strategy you can only support the current production version ( all clients are using latest version). Since in a typical *web application* all clients are using the same "latest" version (since they all access the same server), I would assume that the "by feature" approach is the most commonly used. It removes the need to merge "across the hierarchy", say when a bugfix has to be applied to all 3 release versions. So my current status is that I should go with "branch by feature". If it matters, my team is not very skilled.
2010/12/22
[ "https://Stackoverflow.com/questions/4509658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110453/" ]
At the risk of confusing you further: you can have release branches **and** make all changes on feature branches. These things are not mutually exclusive. That being said, it sounds like you don't need parallel release families and you want to deploy often, perhaps even [continuously](http://radar.oreilly.com/2009/03/continuous-deployment-5-eas.html). So you would want to have a "stable trunk" that you can release at any time. Feature branches help to keep the trunk stable, because you only merge back to the trunk when the changes are done and have proven themselves. So I'd say that your choice is a good fit.
I tend to use Git for my projects, but the process I tend to follow goes like this (and should work for Subversion as well): * for each new feature, create a branch for that feature. * When everything works, merge it into the `staging` branch, and deploy it to the staging server (you do have one of those, right?) * Once we're sure the client is happy with what's on staging, we merge the staging branch into the production branch, tag it as something like `production_release_22` or `production_release_new_feature_x`, and then deploy that tag to the production server. Tags are *never*, *ever* updated - once something gets deployed, it stays that way until more changes are built, tested, and tagged - and then the new tag is deployed. By making sure that it's *tags* getting deployed and not *branches*, I keep myself (or others) from doing things like "I'll just commit this one quick change and update the server without testing it". It's worked pretty well for me so far.
4,509,658
I am trying to decide on the best branching strategy for a web application project. Here is what I have come up with until now and I would greatly appreciate any comments and experiences. The way I see it there are two main branching strategies: "branch by release" and "branch by feature". **"Branch by release"**: Development takes place on the trunk. When the time for a release is near, a branch is made for that release. This branch is then stabilized/tested and finally a release is made. After the release, the branch is merged back into the trunk, while keeping the release branch alive for bug-fixing. Is a bug-fix applied, then it is merged into the trunk ( if the development on the trunk hasn't eclipsed the bug in other means). New features are added to the trunk and don't affect the release branch. When a new release time nears, a new release branch is created a.s.o. **"Branch by feature"**: The trunk is always the "production" trunk (the code that is live). Bugfixes are commited directly to the trunk. Features for the next release are developed in feature branches.Bugfixes are merged from time-to-time into the feature branches. When release time comes, the features branches are merged into the trunk and the cycle of life continues. Now the way I see it the big practical difference between these two strategies is that "by release" allows you to maintane different production versions of you software ( when client A has version 1 and client B version 1.5, client is the paying customer in this case). In contrast using the "by feature" strategy you can only support the current production version ( all clients are using latest version). Since in a typical *web application* all clients are using the same "latest" version (since they all access the same server), I would assume that the "by feature" approach is the most commonly used. It removes the need to merge "across the hierarchy", say when a bugfix has to be applied to all 3 release versions. So my current status is that I should go with "branch by feature". If it matters, my team is not very skilled.
2010/12/22
[ "https://Stackoverflow.com/questions/4509658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110453/" ]
What kind of software are you developing? Shrink wrap? Open Source Project? If so, then go with the "branch by release" or "unstable trunk" approach. Especially if your release cycles are every six months to a year apart. But if your maintaining a web-based project that has changes going out on shorter frequencies, like once every few weeks or less, then go with the "branch by feature" or "stable trunk" approach. The problem with this approach is integrating multiple feature changes that have sweeping changes make the merge process less than fun. It just really gets difficult. But both of those work well, but what if you need both? That is, you have a project that deploys says once every couple of weeks with big feature changes, but you find that you have a number of bug fixes that you cannot wait for those feature changes to be ready. Trunk is your release branch with the "branch by feature" approach. What if you could get both releases and features their own branch? Check out this [blog entry](http://blogs.open.collab.net/svn/2007/11/branching-strat.html) by CollabNet's Bob Archer. His Agile Release strategy gives you best of both. I've used this. It's extremely flexible. Even though Bob doesn't show it in his diagram, you can have multiple release branches going at the same time. This means you could have one release branch that is ready for rollout to production, and another that is being prepared for final QA checks. But two things to consider: First, how good are your developers at merging? You cannot do the the agile release strategy approach by yourself, even if it is a small team. Everyone has to do their part and they really have to understand merging and the tools they are using to do the merge. Secondly, you are going to need a good grasp on changes that ready and those that are about to be. Release management is key to making this work like clock work. Each feature when ready will need to get assigned to a release branch and merged to it. **Whatever approach you choose, it comes down to what you are developing and the frequency of changes you are releasing for that development.**
I tend to use Git for my projects, but the process I tend to follow goes like this (and should work for Subversion as well): * for each new feature, create a branch for that feature. * When everything works, merge it into the `staging` branch, and deploy it to the staging server (you do have one of those, right?) * Once we're sure the client is happy with what's on staging, we merge the staging branch into the production branch, tag it as something like `production_release_22` or `production_release_new_feature_x`, and then deploy that tag to the production server. Tags are *never*, *ever* updated - once something gets deployed, it stays that way until more changes are built, tested, and tagged - and then the new tag is deployed. By making sure that it's *tags* getting deployed and not *branches*, I keep myself (or others) from doing things like "I'll just commit this one quick change and update the server without testing it". It's worked pretty well for me so far.
4,509,658
I am trying to decide on the best branching strategy for a web application project. Here is what I have come up with until now and I would greatly appreciate any comments and experiences. The way I see it there are two main branching strategies: "branch by release" and "branch by feature". **"Branch by release"**: Development takes place on the trunk. When the time for a release is near, a branch is made for that release. This branch is then stabilized/tested and finally a release is made. After the release, the branch is merged back into the trunk, while keeping the release branch alive for bug-fixing. Is a bug-fix applied, then it is merged into the trunk ( if the development on the trunk hasn't eclipsed the bug in other means). New features are added to the trunk and don't affect the release branch. When a new release time nears, a new release branch is created a.s.o. **"Branch by feature"**: The trunk is always the "production" trunk (the code that is live). Bugfixes are commited directly to the trunk. Features for the next release are developed in feature branches.Bugfixes are merged from time-to-time into the feature branches. When release time comes, the features branches are merged into the trunk and the cycle of life continues. Now the way I see it the big practical difference between these two strategies is that "by release" allows you to maintane different production versions of you software ( when client A has version 1 and client B version 1.5, client is the paying customer in this case). In contrast using the "by feature" strategy you can only support the current production version ( all clients are using latest version). Since in a typical *web application* all clients are using the same "latest" version (since they all access the same server), I would assume that the "by feature" approach is the most commonly used. It removes the need to merge "across the hierarchy", say when a bugfix has to be applied to all 3 release versions. So my current status is that I should go with "branch by feature". If it matters, my team is not very skilled.
2010/12/22
[ "https://Stackoverflow.com/questions/4509658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110453/" ]
What kind of software are you developing? Shrink wrap? Open Source Project? If so, then go with the "branch by release" or "unstable trunk" approach. Especially if your release cycles are every six months to a year apart. But if your maintaining a web-based project that has changes going out on shorter frequencies, like once every few weeks or less, then go with the "branch by feature" or "stable trunk" approach. The problem with this approach is integrating multiple feature changes that have sweeping changes make the merge process less than fun. It just really gets difficult. But both of those work well, but what if you need both? That is, you have a project that deploys says once every couple of weeks with big feature changes, but you find that you have a number of bug fixes that you cannot wait for those feature changes to be ready. Trunk is your release branch with the "branch by feature" approach. What if you could get both releases and features their own branch? Check out this [blog entry](http://blogs.open.collab.net/svn/2007/11/branching-strat.html) by CollabNet's Bob Archer. His Agile Release strategy gives you best of both. I've used this. It's extremely flexible. Even though Bob doesn't show it in his diagram, you can have multiple release branches going at the same time. This means you could have one release branch that is ready for rollout to production, and another that is being prepared for final QA checks. But two things to consider: First, how good are your developers at merging? You cannot do the the agile release strategy approach by yourself, even if it is a small team. Everyone has to do their part and they really have to understand merging and the tools they are using to do the merge. Secondly, you are going to need a good grasp on changes that ready and those that are about to be. Release management is key to making this work like clock work. Each feature when ready will need to get assigned to a release branch and merged to it. **Whatever approach you choose, it comes down to what you are developing and the frequency of changes you are releasing for that development.**
***These choices are not mutually exclusive - use both.*** They solve different problems: **"Branch by release"** - release branch is used to ensure you can back to the source used to produce the current live version (or previous released versions) while the next version is in development. E.g. This is in order to make changes to the release version for bug fixes or backpatch features from the current development trunk. **"Branch by feature"** - used to keep a stable development trunk at all times, which is particularly useful for multiple developers and for experimental "maybe" features. I would use both, but you can forego one of the approaches if the problem it solves doesn't apply to you or if you have a different solution that problem. I strongly recommend using a modern DVCS like git or Mercurial. They are geared at parallel development, so they store changes differently than older systems, which makes merging much saner.
4,509,658
I am trying to decide on the best branching strategy for a web application project. Here is what I have come up with until now and I would greatly appreciate any comments and experiences. The way I see it there are two main branching strategies: "branch by release" and "branch by feature". **"Branch by release"**: Development takes place on the trunk. When the time for a release is near, a branch is made for that release. This branch is then stabilized/tested and finally a release is made. After the release, the branch is merged back into the trunk, while keeping the release branch alive for bug-fixing. Is a bug-fix applied, then it is merged into the trunk ( if the development on the trunk hasn't eclipsed the bug in other means). New features are added to the trunk and don't affect the release branch. When a new release time nears, a new release branch is created a.s.o. **"Branch by feature"**: The trunk is always the "production" trunk (the code that is live). Bugfixes are commited directly to the trunk. Features for the next release are developed in feature branches.Bugfixes are merged from time-to-time into the feature branches. When release time comes, the features branches are merged into the trunk and the cycle of life continues. Now the way I see it the big practical difference between these two strategies is that "by release" allows you to maintane different production versions of you software ( when client A has version 1 and client B version 1.5, client is the paying customer in this case). In contrast using the "by feature" strategy you can only support the current production version ( all clients are using latest version). Since in a typical *web application* all clients are using the same "latest" version (since they all access the same server), I would assume that the "by feature" approach is the most commonly used. It removes the need to merge "across the hierarchy", say when a bugfix has to be applied to all 3 release versions. So my current status is that I should go with "branch by feature". If it matters, my team is not very skilled.
2010/12/22
[ "https://Stackoverflow.com/questions/4509658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110453/" ]
What kind of software are you developing? Shrink wrap? Open Source Project? If so, then go with the "branch by release" or "unstable trunk" approach. Especially if your release cycles are every six months to a year apart. But if your maintaining a web-based project that has changes going out on shorter frequencies, like once every few weeks or less, then go with the "branch by feature" or "stable trunk" approach. The problem with this approach is integrating multiple feature changes that have sweeping changes make the merge process less than fun. It just really gets difficult. But both of those work well, but what if you need both? That is, you have a project that deploys says once every couple of weeks with big feature changes, but you find that you have a number of bug fixes that you cannot wait for those feature changes to be ready. Trunk is your release branch with the "branch by feature" approach. What if you could get both releases and features their own branch? Check out this [blog entry](http://blogs.open.collab.net/svn/2007/11/branching-strat.html) by CollabNet's Bob Archer. His Agile Release strategy gives you best of both. I've used this. It's extremely flexible. Even though Bob doesn't show it in his diagram, you can have multiple release branches going at the same time. This means you could have one release branch that is ready for rollout to production, and another that is being prepared for final QA checks. But two things to consider: First, how good are your developers at merging? You cannot do the the agile release strategy approach by yourself, even if it is a small team. Everyone has to do their part and they really have to understand merging and the tools they are using to do the merge. Secondly, you are going to need a good grasp on changes that ready and those that are about to be. Release management is key to making this work like clock work. Each feature when ready will need to get assigned to a release branch and merged to it. **Whatever approach you choose, it comes down to what you are developing and the frequency of changes you are releasing for that development.**
At the risk of confusing you further: you can have release branches **and** make all changes on feature branches. These things are not mutually exclusive. That being said, it sounds like you don't need parallel release families and you want to deploy often, perhaps even [continuously](http://radar.oreilly.com/2009/03/continuous-deployment-5-eas.html). So you would want to have a "stable trunk" that you can release at any time. Feature branches help to keep the trunk stable, because you only merge back to the trunk when the changes are done and have proven themselves. So I'd say that your choice is a good fit.
9,802,812
I know that in ASP.NET web application, changing a DLL file located in the `bin` folder causes an application recycle. But I wonder, as the subject implies, whether **any** file changes cause such behavior? Are simple text files included in this scenario? And what about sub folders to `bin` folder? And their contents? I know I can try it out myself, but more importantly, I'm looking for proper documentation for this.
2012/03/21
[ "https://Stackoverflow.com/questions/9802812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17772/" ]
First, i can not provide a link to an official documentation. But from what i've read **every** change in the bin-folder(incl. subfolders) will cause the IIS to recycle the application domain. Abrupt Application Pool Recycling 1. Any modifications in the Application’s BIN Directory 2. Making changes in any Configuration File/s, like Web.config or others ( if you have any specific config file in your application say in a directory called App\_Config). 3. Making modifications in the Source code files in APP\_CODE Directory. This maybe change in any Source code files, or adding or deleting files from this directory. 4. Making changes in the Global.asax file 5. Making Changes in the Machine.config file. 6. Making any modifications in the Web Application’s Root Directory. This means creating files/subdirectories on the fly can lead to application pool recycling. 7. Modifications for references of Web Services of App\_WebReferences directory. 8. Modifying the Security Settings of any directory in the Root directory. (Like specifying read security rights for everyone or any other specific user or user group.) Here's some reading: 1. [What causes an application pool in IIS to recycle?](https://stackoverflow.com/questions/302110/what-causes-an-application-pool-in-iis-to-recycle) 2. <http://christopherdeweese.com/blog2/post/beware-writing-to-the-bin-folder-in-iis-hosted-services> 3. [What does an IISReset do?](https://stackoverflow.com/questions/23566/what-does-an-iisreset-do) 4. <http://www.iis.net/ConfigReference/system.applicationHost/applicationPools/add/recycling> 5. [Managing, Tuning, and Configuring Application Pools in IIS 7.0](http://technet.microsoft.com/en-us/library/cc745955.aspx) 6. <http://varunvns.wordpress.com/2011/07/04/application-pool-restarts/>
NOPE, updating a dll file in the bin folder DOES NOT cause a recycle. At least not with .NET 4.7 on IIS 10 and later First, what is a "recycle"? --------------------------- It's when IIS launches a new instance of `w3wp` process and the old one is being "politely" terminated (after finishing up on all the requests and background tasks registered with `IRegisteredObject`) What happens when you update a file in /bin? -------------------------------------------- ASP.NET does a hot-reload: it detects the update and uses the new version of the .dll for new page requests from then on. I.e. reloads the "app-domain". But this happens within the same `w3wp` process. ([source](https://learn.microsoft.com/en-us/previous-versions/t990ks23(v=vs.140)?redirectedfrom=MSDN)) I just checked this on IIS 10 windows 2016 machine: launched Task Manager and repalce the main .dll file - the `w3wp` process kept running, nothing happened.
6,549,970
How would I go about implementing the MainPage class? ``` import cgi import os import logging from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db class Greeting(db.Model): #setting up database a = db.StringProperty(multiline=True) b = db.StringProperty(multiline=True) c = db.StringProperty(multiline=True) d = db.StringProperty(multiline=True) class MainPage(webapp.RequestHandler): def get(self): ##I want to access the content of the database here which is defined in Downloader class. ##For example let the value of greeting.a be assigned to alpha variable. #Entering data to the database class Downloader(webapp.RequestHandler): def get(self): greeting=Greeting() greeting.a=self.request.GET.get('a') greeting.b=self.request.GET.get('b') greeting.c=self.request.GET.get('c') greeting.d=self.request.GET.get('d') greeting.put() ```
2011/07/01
[ "https://Stackoverflow.com/questions/6549970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730047/" ]
Here is an alternate approach using `plyr`. It directly works with the original data frame `foo` and does not require converting `NA` into a date. The code is self-explanatory and very readable. Any comments are welcome. ``` dates = seq(as.POSIXct('2006-01-01'), as.POSIXct('2009-12-01'), by = "month") count = ldply(dates, function(d) with(foo, sum((Start < d) + (d < End | is.na(End)) == 2))) data.frame(dates, count) ```
Here's a *different* way that you might find easier: ``` foo<-data.frame(name=c("Bob","Sue", "Richard", "Jane"), Start=as.POSIXct(c("2006-03-23 GMT", "2007-01-20 GMT", "2007-01-20 GMT", "2006-03-23 GMT")), End=as.POSIXct(c("2009-01-20 GMT", NA, "2006-03-23 GMT", NA))) tmp <- expand.grid(foo$name,seq.POSIXt(as.POSIXct('2006-01-01'), as.POSIXct('2009-12-01'),by="month")) colnames(tmp) <- c('name','date') foo[is.na(foo)] <- max(tmp$date) + 1 tmp1 <- merge(tmp,foo,by="name") tmp2 <- tmp1$Start <= tmp1$date & tmp1$End >= tmp1$date aggregate(tmp2,by=list(date=tmp1$date),sum) ``` My two cents here are to use `seq.*` rather than `paste`ing dates together and that `ddply` is kind of an awkward tool if you're really just taking daterange one element at a time. I used `aggregate`, but you could have used `lapply` or something like that. You could compress this into fewer lines if you really want to, but readability will suffer.
276,816
It's not obvious to me..
2008/11/10
[ "https://Stackoverflow.com/questions/276816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209/" ]
If you do kill TSVNCache, you don't need to manually restart it, the shell-extension will do that next time it needs it. If you're trying to restart the shell-extension, you might achieve it by killing all Explorer.exe processes, and anything else which has ended-up with TSVN in-process. This is basically any app which has asked the shell about icons, or has used the common file/directory dialogs. You may need to use something like "Process Explorer" (sysinternals) to find which processes have the TSVN DLLs loaded.
The background process that watches your file system for SVN related files and folders is TSVNCache.exe. You can kill that process and start it again, or just reboot your machine :)
276,816
It's not obvious to me..
2008/11/10
[ "https://Stackoverflow.com/questions/276816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209/" ]
If you don't see the TortoiseSVN icons anymore you can restart `TSVNCache.exe` by navigating to TortoiseSVN's `bin` directory, e.g. `C:\Program Files\TortoiseSVN\bin`, and double clicking on it. Note that if you restart it in this way it will be killed when you logout. Otherwise follow the suggestions from the other answers.
The background process that watches your file system for SVN related files and folders is TSVNCache.exe. You can kill that process and start it again, or just reboot your machine :)
276,816
It's not obvious to me..
2008/11/10
[ "https://Stackoverflow.com/questions/276816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209/" ]
If you do kill TSVNCache, you don't need to manually restart it, the shell-extension will do that next time it needs it. If you're trying to restart the shell-extension, you might achieve it by killing all Explorer.exe processes, and anything else which has ended-up with TSVN in-process. This is basically any app which has asked the shell about icons, or has used the common file/directory dialogs. You may need to use something like "Process Explorer" (sysinternals) to find which processes have the TSVN DLLs loaded.
If you don't see the TortoiseSVN icons anymore you can restart `TSVNCache.exe` by navigating to TortoiseSVN's `bin` directory, e.g. `C:\Program Files\TortoiseSVN\bin`, and double clicking on it. Note that if you restart it in this way it will be killed when you logout. Otherwise follow the suggestions from the other answers.
24,795,198
In Selenium with Python is it possible to get all the children of a WebElement as a list?
2014/07/17
[ "https://Stackoverflow.com/questions/24795198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1672428/" ]
Another variation of `find_elements_by_xpath(".//*")` is: ``` from selenium.webdriver.common.by import By find_elements(By.XPATH, ".//*") ```
You can't use ``` all_children_by_css = header.find_elements_by_css_selector("*") ``` You now need to use ``` all_children_by_css = header.find_elements(By.XPATH, "*') ```
24,795,198
In Selenium with Python is it possible to get all the children of a WebElement as a list?
2014/07/17
[ "https://Stackoverflow.com/questions/24795198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1672428/" ]
Yes, you can achieve it by `find_elements_by_css_selector("*")` or `find_elements_by_xpath(".//*")`. However, this doesn't sound like a valid use case to find **all children** of an element. It is an expensive operation to get all direct/indirect children. Please further explain what you are trying to do. There should be a better way. ``` from selenium import webdriver driver = webdriver.Firefox() driver.get("http://www.stackoverflow.com") header = driver.find_element_by_id("header") # start from your target element, here for example, "header" all_children_by_css = header.find_elements_by_css_selector("*") all_children_by_xpath = header.find_elements_by_xpath(".//*") print 'len(all_children_by_css): ' + str(len(all_children_by_css)) print 'len(all_children_by_xpath): ' + str(len(all_children_by_xpath)) ```
Another variation of `find_elements_by_xpath(".//*")` is: ``` from selenium.webdriver.common.by import By find_elements(By.XPATH, ".//*") ```
24,795,198
In Selenium with Python is it possible to get all the children of a WebElement as a list?
2014/07/17
[ "https://Stackoverflow.com/questions/24795198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1672428/" ]
You can't use ``` all_children_by_css = header.find_elements_by_css_selector("*") ``` You now need to use ``` all_children_by_css = header.find_elements(By.XPATH, "*') ```
In 2022, with `selenium==4.2.0`, @Richard's answer will need to be rewritten as: ``` from selenium.webdriver.common.by import By parentElement = driver.find_element(By.CLASS_NAME,"bar") elementList = parentElement.find_elements(By.TAG_NAME,"li") ```
24,795,198
In Selenium with Python is it possible to get all the children of a WebElement as a list?
2014/07/17
[ "https://Stackoverflow.com/questions/24795198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1672428/" ]
Yes, you can use `find_elements_by_` to retrieve children elements into a list. See the python bindings here: <http://selenium-python.readthedocs.io/locating-elements.html> Example HTML: ```html <ul class="bar"> <li>one</li> <li>two</li> <li>three</li> </ul> ``` You can use the `find_elements_by_` like so: ```py parentElement = driver.find_element_by_class_name("bar") elementList = parentElement.find_elements_by_tag_name("li") ``` If you want help with a specific case, you can edit your post with the HTML you're looking to get parent and children elements from.
You can use `get_attribute` and `BeautifulSoup` ``` html_str = el.get_attribute('innerHTML') bs = BeautifulSoup(html_str, 'lxml') ```
24,795,198
In Selenium with Python is it possible to get all the children of a WebElement as a list?
2014/07/17
[ "https://Stackoverflow.com/questions/24795198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1672428/" ]
Yes, you can achieve it by `find_elements_by_css_selector("*")` or `find_elements_by_xpath(".//*")`. However, this doesn't sound like a valid use case to find **all children** of an element. It is an expensive operation to get all direct/indirect children. Please further explain what you are trying to do. There should be a better way. ``` from selenium import webdriver driver = webdriver.Firefox() driver.get("http://www.stackoverflow.com") header = driver.find_element_by_id("header") # start from your target element, here for example, "header" all_children_by_css = header.find_elements_by_css_selector("*") all_children_by_xpath = header.find_elements_by_xpath(".//*") print 'len(all_children_by_css): ' + str(len(all_children_by_css)) print 'len(all_children_by_xpath): ' + str(len(all_children_by_xpath)) ```
In 2022, with `selenium==4.2.0`, @Richard's answer will need to be rewritten as: ``` from selenium.webdriver.common.by import By parentElement = driver.find_element(By.CLASS_NAME,"bar") elementList = parentElement.find_elements(By.TAG_NAME,"li") ```
24,795,198
In Selenium with Python is it possible to get all the children of a WebElement as a list?
2014/07/17
[ "https://Stackoverflow.com/questions/24795198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1672428/" ]
Yes, you can achieve it by `find_elements_by_css_selector("*")` or `find_elements_by_xpath(".//*")`. However, this doesn't sound like a valid use case to find **all children** of an element. It is an expensive operation to get all direct/indirect children. Please further explain what you are trying to do. There should be a better way. ``` from selenium import webdriver driver = webdriver.Firefox() driver.get("http://www.stackoverflow.com") header = driver.find_element_by_id("header") # start from your target element, here for example, "header" all_children_by_css = header.find_elements_by_css_selector("*") all_children_by_xpath = header.find_elements_by_xpath(".//*") print 'len(all_children_by_css): ' + str(len(all_children_by_css)) print 'len(all_children_by_xpath): ' + str(len(all_children_by_xpath)) ```
Yes, you can use `find_elements_by_` to retrieve children elements into a list. See the python bindings here: <http://selenium-python.readthedocs.io/locating-elements.html> Example HTML: ```html <ul class="bar"> <li>one</li> <li>two</li> <li>three</li> </ul> ``` You can use the `find_elements_by_` like so: ```py parentElement = driver.find_element_by_class_name("bar") elementList = parentElement.find_elements_by_tag_name("li") ``` If you want help with a specific case, you can edit your post with the HTML you're looking to get parent and children elements from.
24,795,198
In Selenium with Python is it possible to get all the children of a WebElement as a list?
2014/07/17
[ "https://Stackoverflow.com/questions/24795198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1672428/" ]
You can use `get_attribute` and `BeautifulSoup` ``` html_str = el.get_attribute('innerHTML') bs = BeautifulSoup(html_str, 'lxml') ```
In 2022, with `selenium==4.2.0`, @Richard's answer will need to be rewritten as: ``` from selenium.webdriver.common.by import By parentElement = driver.find_element(By.CLASS_NAME,"bar") elementList = parentElement.find_elements(By.TAG_NAME,"li") ```
24,795,198
In Selenium with Python is it possible to get all the children of a WebElement as a list?
2014/07/17
[ "https://Stackoverflow.com/questions/24795198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1672428/" ]
Yes, you can use `find_elements_by_` to retrieve children elements into a list. See the python bindings here: <http://selenium-python.readthedocs.io/locating-elements.html> Example HTML: ```html <ul class="bar"> <li>one</li> <li>two</li> <li>three</li> </ul> ``` You can use the `find_elements_by_` like so: ```py parentElement = driver.find_element_by_class_name("bar") elementList = parentElement.find_elements_by_tag_name("li") ``` If you want help with a specific case, you can edit your post with the HTML you're looking to get parent and children elements from.
You can't use ``` all_children_by_css = header.find_elements_by_css_selector("*") ``` You now need to use ``` all_children_by_css = header.find_elements(By.XPATH, "*') ```
24,795,198
In Selenium with Python is it possible to get all the children of a WebElement as a list?
2014/07/17
[ "https://Stackoverflow.com/questions/24795198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1672428/" ]
Yes, you can achieve it by `find_elements_by_css_selector("*")` or `find_elements_by_xpath(".//*")`. However, this doesn't sound like a valid use case to find **all children** of an element. It is an expensive operation to get all direct/indirect children. Please further explain what you are trying to do. There should be a better way. ``` from selenium import webdriver driver = webdriver.Firefox() driver.get("http://www.stackoverflow.com") header = driver.find_element_by_id("header") # start from your target element, here for example, "header" all_children_by_css = header.find_elements_by_css_selector("*") all_children_by_xpath = header.find_elements_by_xpath(".//*") print 'len(all_children_by_css): ' + str(len(all_children_by_css)) print 'len(all_children_by_xpath): ' + str(len(all_children_by_xpath)) ```
You can use `get_attribute` and `BeautifulSoup` ``` html_str = el.get_attribute('innerHTML') bs = BeautifulSoup(html_str, 'lxml') ```
24,795,198
In Selenium with Python is it possible to get all the children of a WebElement as a list?
2014/07/17
[ "https://Stackoverflow.com/questions/24795198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1672428/" ]
Another variation of `find_elements_by_xpath(".//*")` is: ``` from selenium.webdriver.common.by import By find_elements(By.XPATH, ".//*") ```
You can use `get_attribute` and `BeautifulSoup` ``` html_str = el.get_attribute('innerHTML') bs = BeautifulSoup(html_str, 'lxml') ```
8,586,225
I am using same php page for different operation. So condition wise I am doing some actions Which one showing good perfomance? ``` This one if($catid){ .. some action } if($sub_catid){ .. some action } if($sub_sub_catid){ .. some action } ``` OR This one ``` if($catid){ .. some action }else{ if($sub_catid){ .. some action }else{ if($sub_sub_catid){ .. some action } } } ```
2011/12/21
[ "https://Stackoverflow.com/questions/8586225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669388/" ]
First off, those two have very different meanings. The first one could allow every single statement to execute if all those variables were TRUE. The second one will "short-circuit" the first time it finds something TRUE. What I think you're looking for is: ``` if($catid) { .. some action } else if($sub_catid) { .. some action } else if($sub_sub_catid) { .. some action } ``` Bonus points: more readable!
Both have a good performance. An if check on a simple variable is very fast. Theoretically the second is faster, but you will hardly be able to measure the difference. Semantically however, they are not the same. If both $catid and $subcatid are set, in the first situation, both the first and the second action are executed, while in the second situation, only the first action is executed. So always be careful with 'optimizations' like this. You may make your code a nanosecond faster, but it may be less readable and it may even break!
8,586,225
I am using same php page for different operation. So condition wise I am doing some actions Which one showing good perfomance? ``` This one if($catid){ .. some action } if($sub_catid){ .. some action } if($sub_sub_catid){ .. some action } ``` OR This one ``` if($catid){ .. some action }else{ if($sub_catid){ .. some action }else{ if($sub_sub_catid){ .. some action } } } ```
2011/12/21
[ "https://Stackoverflow.com/questions/8586225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669388/" ]
First off, those two have very different meanings. The first one could allow every single statement to execute if all those variables were TRUE. The second one will "short-circuit" the first time it finds something TRUE. What I think you're looking for is: ``` if($catid) { .. some action } else if($sub_catid) { .. some action } else if($sub_sub_catid) { .. some action } ``` Bonus points: more readable!
if your conditions cannot be true at the same time the best way is to use the switch statement ``` switch($mycondition){ case 'category': //Category statement here break; case 'sub_category': //Another Statement here break; default: //Other cases } ```
8,586,225
I am using same php page for different operation. So condition wise I am doing some actions Which one showing good perfomance? ``` This one if($catid){ .. some action } if($sub_catid){ .. some action } if($sub_sub_catid){ .. some action } ``` OR This one ``` if($catid){ .. some action }else{ if($sub_catid){ .. some action }else{ if($sub_sub_catid){ .. some action } } } ```
2011/12/21
[ "https://Stackoverflow.com/questions/8586225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669388/" ]
Both have a good performance. An if check on a simple variable is very fast. Theoretically the second is faster, but you will hardly be able to measure the difference. Semantically however, they are not the same. If both $catid and $subcatid are set, in the first situation, both the first and the second action are executed, while in the second situation, only the first action is executed. So always be careful with 'optimizations' like this. You may make your code a nanosecond faster, but it may be less readable and it may even break!
if your conditions cannot be true at the same time the best way is to use the switch statement ``` switch($mycondition){ case 'category': //Category statement here break; case 'sub_category': //Another Statement here break; default: //Other cases } ```
12,453,794
I was trying to send email through Appcelerator Cloud Service, in my Titanium app. The code I'm using is the standart one, given at the documentation site. But the email is not being sent. ``` Cloud.Emails.send({ template: 'welcome', recipients: '*******@gmail.com' }, function (e) { if (e.success) { Titanium.API.info('Email sent successfully.'); } else { Titanium.API.info('Error:\\n' + ((e.error && e.message) || JSON.stringify(e))); } }); ``` It give the this error, 'Email template welcome is not found'. I was thinking that template is the message to be sent in email. There is no help on API about this attribute , template. Can anybody explain it to me? I'll be thankful. Thanx
2012/09/17
[ "https://Stackoverflow.com/questions/12453794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1124928/" ]
The error shows that you haven't created an email template on the ACS website yet. The following steps will help you to create email template 1. Log in to your Appcelerator App Console 2. click "Manage ACS" under the app you're working on 3. click the "Email Templates" tab 4. "Create an Email Template". also you can setup your SMTP settings as follows which worked for me. **Username: *\_*\_\_*\_*\_\_\_\_@gmail.com Password: gmail account password TLS: true/ false (both will work) SMTP Address: smtp.gmail.com Port: *587* Domain : www.gmail.com**
That error means you haven't created an email template on the ACS website yet. Log in to your [Appcelerator App Console](https://my.appcelerator.com/apps/titanium), click "Manage ACS" under the app you're working on, then click the "Email Templates" tab, and "Create an Email Template".
41,795,668
So a list from 0 to 100 is created and I apply the formula in line two to make list B. The issue is that it's rounded to an int and I have been trying how to get it out to 3 decimals. ``` A = range(0,101) B = [(x-10)/3 for x in A] ``` Ex: If A = 11 (11-10)/3 = 0.333 instead of (11-10)/3 = 0. Thanks!
2017/01/22
[ "https://Stackoverflow.com/questions/41795668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The problem is with the design of the class. The default copy constructor will create a new instance of `Foo` when passed by **value** into the free standing function named `func`. When the instance of `Foo` named `f` exits scope then the code invokes the user-provided destructor that deletes the array of doubles. This opens the code to the unfortunate situation of deleting the same array twice when the original instance of `Foo` named `f` exits scope at the end of the program. When run on my machine, the code does not produce the same output. Instead I see two output lines of `0 3 6` followed by fault indicating the double free operation. The solution is to avoid the copy by passing by reference (or by const reference): `void func(Foo const &f) { }` or to supply a valid copy constructor that makes a deep copy of the underlying array. Passing by reference is just a bandaid that avoids exercising the bug. Using `std::vector<double>` fixes the problem because the default copy constructor will perform a deep copy and avoid double deallocation. This is absolutely the best approach in this small example, but it avoids having to understand the root of the problem. Most C++ developers will learn these techniques then promptly do what they can to avoid having to write code that manually allocates and deallocates memory.
One problem is that calling func creates a bitwise copy. When that copy goes out of scope the destructor is called which deletes your array. You should change void func(Foo f){} to void func(Foo& f){}. But better yet you add a create copy constructor or add a private declaration to stop it being called unexpectedly.
41,795,668
So a list from 0 to 100 is created and I apply the formula in line two to make list B. The issue is that it's rounded to an int and I have been trying how to get it out to 3 decimals. ``` A = range(0,101) B = [(x-10)/3 for x in A] ``` Ex: If A = 11 (11-10)/3 = 0.333 instead of (11-10)/3 = 0. Thanks!
2017/01/22
[ "https://Stackoverflow.com/questions/41795668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You should probably pass the object as a reference `func(Foo& f)` or - if you do not want to modify it at all - as a constant reference `func(const Foo& f)`. This will not create or delete any objects during the function call. Aside from that, as others have already mentioned, your class should better implement the Rule of Three.
One problem is that calling func creates a bitwise copy. When that copy goes out of scope the destructor is called which deletes your array. You should change void func(Foo f){} to void func(Foo& f){}. But better yet you add a create copy constructor or add a private declaration to stop it being called unexpectedly.
41,795,668
So a list from 0 to 100 is created and I apply the formula in line two to make list B. The issue is that it's rounded to an int and I have been trying how to get it out to 3 decimals. ``` A = range(0,101) B = [(x-10)/3 for x in A] ``` Ex: If A = 11 (11-10)/3 = 0.333 instead of (11-10)/3 = 0. Thanks!
2017/01/22
[ "https://Stackoverflow.com/questions/41795668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When you pass a value to a function, it is supposed to be copied. The destructor is run on the copy and should no effect on the original object. `Foo` fails to implement a copy constructor, so compiler provides the default one which simply performs a member-wise copy of the struct. As a result, the "copy" of `Foo` inside `Func` contains the same pointer as the original, and its destructor frees the data pointed to by both. In order to be usable by idiomatic C++ code, `Foo` **must** implement at least a copy constructor and an assignment operator in addition to the destructor. The rule that these three come together is sometimes referred to as "the rule of three", and is mentioned in other answers. Here is an (untested) example of what the constructors could look like: ``` Foo::Foo(const Foo& other) { // copy constructor: construct Foo given another Foo size = other->size; d = new double[size]; std::copy(other->d, other->d + size, d); } Foo& Foo::operator=(const Foo& other) { // assignment: reinitialize Foo with another Foo if (this != &other) { delete d; size = other->size; d = new double[size]; std::copy(other->d, other->d + size, d); } return *this; } ``` Additionally, you can also modify functions like `func` to accept a reference to `Foo` or a constant reference to `Foo` to avoid unnecessary copying. Doing this alone would also happen fix the immediate problem you are having, but it would not help other issues, so you should definitely implement a proper copy constructor before doing anything else. It's a good idea to get a good book on C++ where the rule of three and other C++ pitfalls are explained. Also, look into using STL containers such as `std::vector` as members. Since they implement the rule of three themselves, your class wouldn't need to.
One problem is that calling func creates a bitwise copy. When that copy goes out of scope the destructor is called which deletes your array. You should change void func(Foo f){} to void func(Foo& f){}. But better yet you add a create copy constructor or add a private declaration to stop it being called unexpectedly.
9,460,435
Can anybody tell me how to select data from two tables, without having to use join? Something like this: ``` SELECT t1.*, t2.* FROM table1 t1, table2 t2 ``` ###Clarification I have these two tables, that have the same fields. IE: `table1` contains data from 2011 and `table2` contains data in 2012. I want to get them all. ###Further clarification: The result set desired can be produced by: ``` (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '') UNION (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions_bk_2012 tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '' ``` and the OP wishes to see if there are alternative ways to speed this up ("I tried to use `UNION` in between those queries. but query speed took 0.1887 secs. it's kinda slow.") (@Jetoox: if this is not your intent, please edit your question and clarify).
2012/02/27
[ "https://Stackoverflow.com/questions/9460435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175915/" ]
Just put the join condition in the WHERE clause: ``` SELECT t1.*, t2.* FROM table1 t1, table2 t2 WHERE t1.id = t2.t1_id ``` That is an inner join, though. UPDATE ====== Upon looking at your queries: In this particular case, there is no relation between `tbl_transactions` and `tbl_transactions_bk_2012` (i.e. joining these on person\_key is meaningless because there is no relationship between the two tables in the way that (say) tbl\_transactions and persons are related). Then, you should use the `UNION` approach. Trying to join the first query to the second using either `JOIN` or `FROM xx, yy WHERE xx.id=yy.id` is meaningless and won't give you the results you need. By the way, in the future, put your current query/attempt in your post - as you can see it will prevent you from getting answers that aren't appropriate for your question (as my first attempt was).
``` select t1.*, t2.* from table1 t1, table2 t2 where t1.fkey = t2.pkey ```
9,460,435
Can anybody tell me how to select data from two tables, without having to use join? Something like this: ``` SELECT t1.*, t2.* FROM table1 t1, table2 t2 ``` ###Clarification I have these two tables, that have the same fields. IE: `table1` contains data from 2011 and `table2` contains data in 2012. I want to get them all. ###Further clarification: The result set desired can be produced by: ``` (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '') UNION (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions_bk_2012 tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '' ``` and the OP wishes to see if there are alternative ways to speed this up ("I tried to use `UNION` in between those queries. but query speed took 0.1887 secs. it's kinda slow.") (@Jetoox: if this is not your intent, please edit your question and clarify).
2012/02/27
[ "https://Stackoverflow.com/questions/9460435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175915/" ]
Just put the join condition in the WHERE clause: ``` SELECT t1.*, t2.* FROM table1 t1, table2 t2 WHERE t1.id = t2.t1_id ``` That is an inner join, though. UPDATE ====== Upon looking at your queries: In this particular case, there is no relation between `tbl_transactions` and `tbl_transactions_bk_2012` (i.e. joining these on person\_key is meaningless because there is no relationship between the two tables in the way that (say) tbl\_transactions and persons are related). Then, you should use the `UNION` approach. Trying to join the first query to the second using either `JOIN` or `FROM xx, yy WHERE xx.id=yy.id` is meaningless and won't give you the results you need. By the way, in the future, put your current query/attempt in your post - as you can see it will prevent you from getting answers that aren't appropriate for your question (as my first attempt was).
``` select t1.* , t2.* from t1, t2 where t1.id=t2.id; ```
9,460,435
Can anybody tell me how to select data from two tables, without having to use join? Something like this: ``` SELECT t1.*, t2.* FROM table1 t1, table2 t2 ``` ###Clarification I have these two tables, that have the same fields. IE: `table1` contains data from 2011 and `table2` contains data in 2012. I want to get them all. ###Further clarification: The result set desired can be produced by: ``` (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '') UNION (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions_bk_2012 tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '' ``` and the OP wishes to see if there are alternative ways to speed this up ("I tried to use `UNION` in between those queries. but query speed took 0.1887 secs. it's kinda slow.") (@Jetoox: if this is not your intent, please edit your question and clarify).
2012/02/27
[ "https://Stackoverflow.com/questions/9460435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175915/" ]
Just put the join condition in the WHERE clause: ``` SELECT t1.*, t2.* FROM table1 t1, table2 t2 WHERE t1.id = t2.t1_id ``` That is an inner join, though. UPDATE ====== Upon looking at your queries: In this particular case, there is no relation between `tbl_transactions` and `tbl_transactions_bk_2012` (i.e. joining these on person\_key is meaningless because there is no relationship between the two tables in the way that (say) tbl\_transactions and persons are related). Then, you should use the `UNION` approach. Trying to join the first query to the second using either `JOIN` or `FROM xx, yy WHERE xx.id=yy.id` is meaningless and won't give you the results you need. By the way, in the future, put your current query/attempt in your post - as you can see it will prevent you from getting answers that aren't appropriate for your question (as my first attempt was).
You want [`UNION`](http://dev.mysql.com/doc/refman/5.0/en/union.html). ``` (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '') UNION (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions_bk_2012 tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '' ```
9,460,435
Can anybody tell me how to select data from two tables, without having to use join? Something like this: ``` SELECT t1.*, t2.* FROM table1 t1, table2 t2 ``` ###Clarification I have these two tables, that have the same fields. IE: `table1` contains data from 2011 and `table2` contains data in 2012. I want to get them all. ###Further clarification: The result set desired can be produced by: ``` (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '') UNION (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions_bk_2012 tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '' ``` and the OP wishes to see if there are alternative ways to speed this up ("I tried to use `UNION` in between those queries. but query speed took 0.1887 secs. it's kinda slow.") (@Jetoox: if this is not your intent, please edit your question and clarify).
2012/02/27
[ "https://Stackoverflow.com/questions/9460435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175915/" ]
Just put the join condition in the WHERE clause: ``` SELECT t1.*, t2.* FROM table1 t1, table2 t2 WHERE t1.id = t2.t1_id ``` That is an inner join, though. UPDATE ====== Upon looking at your queries: In this particular case, there is no relation between `tbl_transactions` and `tbl_transactions_bk_2012` (i.e. joining these on person\_key is meaningless because there is no relationship between the two tables in the way that (say) tbl\_transactions and persons are related). Then, you should use the `UNION` approach. Trying to join the first query to the second using either `JOIN` or `FROM xx, yy WHERE xx.id=yy.id` is meaningless and won't give you the results you need. By the way, in the future, put your current query/attempt in your post - as you can see it will prevent you from getting answers that aren't appropriate for your question (as my first attempt was).
While using the UNION query, you may also want to add indexes to any columns that you are using to join and filter which will improve performance
9,460,435
Can anybody tell me how to select data from two tables, without having to use join? Something like this: ``` SELECT t1.*, t2.* FROM table1 t1, table2 t2 ``` ###Clarification I have these two tables, that have the same fields. IE: `table1` contains data from 2011 and `table2` contains data in 2012. I want to get them all. ###Further clarification: The result set desired can be produced by: ``` (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '') UNION (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions_bk_2012 tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '' ``` and the OP wishes to see if there are alternative ways to speed this up ("I tried to use `UNION` in between those queries. but query speed took 0.1887 secs. it's kinda slow.") (@Jetoox: if this is not your intent, please edit your question and clarify).
2012/02/27
[ "https://Stackoverflow.com/questions/9460435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175915/" ]
You want [`UNION`](http://dev.mysql.com/doc/refman/5.0/en/union.html). ``` (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '') UNION (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions_bk_2012 tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '' ```
``` select t1.*, t2.* from table1 t1, table2 t2 where t1.fkey = t2.pkey ```
9,460,435
Can anybody tell me how to select data from two tables, without having to use join? Something like this: ``` SELECT t1.*, t2.* FROM table1 t1, table2 t2 ``` ###Clarification I have these two tables, that have the same fields. IE: `table1` contains data from 2011 and `table2` contains data in 2012. I want to get them all. ###Further clarification: The result set desired can be produced by: ``` (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '') UNION (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions_bk_2012 tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '' ``` and the OP wishes to see if there are alternative ways to speed this up ("I tried to use `UNION` in between those queries. but query speed took 0.1887 secs. it's kinda slow.") (@Jetoox: if this is not your intent, please edit your question and clarify).
2012/02/27
[ "https://Stackoverflow.com/questions/9460435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175915/" ]
``` select t1.*, t2.* from table1 t1, table2 t2 where t1.fkey = t2.pkey ```
While using the UNION query, you may also want to add indexes to any columns that you are using to join and filter which will improve performance
9,460,435
Can anybody tell me how to select data from two tables, without having to use join? Something like this: ``` SELECT t1.*, t2.* FROM table1 t1, table2 t2 ``` ###Clarification I have these two tables, that have the same fields. IE: `table1` contains data from 2011 and `table2` contains data in 2012. I want to get them all. ###Further clarification: The result set desired can be produced by: ``` (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '') UNION (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions_bk_2012 tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '' ``` and the OP wishes to see if there are alternative ways to speed this up ("I tried to use `UNION` in between those queries. but query speed took 0.1887 secs. it's kinda slow.") (@Jetoox: if this is not your intent, please edit your question and clarify).
2012/02/27
[ "https://Stackoverflow.com/questions/9460435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175915/" ]
You want [`UNION`](http://dev.mysql.com/doc/refman/5.0/en/union.html). ``` (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '') UNION (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions_bk_2012 tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '' ```
``` select t1.* , t2.* from t1, t2 where t1.id=t2.id; ```
9,460,435
Can anybody tell me how to select data from two tables, without having to use join? Something like this: ``` SELECT t1.*, t2.* FROM table1 t1, table2 t2 ``` ###Clarification I have these two tables, that have the same fields. IE: `table1` contains data from 2011 and `table2` contains data in 2012. I want to get them all. ###Further clarification: The result set desired can be produced by: ``` (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '') UNION (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions_bk_2012 tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '' ``` and the OP wishes to see if there are alternative ways to speed this up ("I tried to use `UNION` in between those queries. but query speed took 0.1887 secs. it's kinda slow.") (@Jetoox: if this is not your intent, please edit your question and clarify).
2012/02/27
[ "https://Stackoverflow.com/questions/9460435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175915/" ]
``` select t1.* , t2.* from t1, t2 where t1.id=t2.id; ```
While using the UNION query, you may also want to add indexes to any columns that you are using to join and filter which will improve performance
9,460,435
Can anybody tell me how to select data from two tables, without having to use join? Something like this: ``` SELECT t1.*, t2.* FROM table1 t1, table2 t2 ``` ###Clarification I have these two tables, that have the same fields. IE: `table1` contains data from 2011 and `table2` contains data in 2012. I want to get them all. ###Further clarification: The result set desired can be produced by: ``` (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '') UNION (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions_bk_2012 tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '' ``` and the OP wishes to see if there are alternative ways to speed this up ("I tried to use `UNION` in between those queries. but query speed took 0.1887 secs. it's kinda slow.") (@Jetoox: if this is not your intent, please edit your question and clarify).
2012/02/27
[ "https://Stackoverflow.com/questions/9460435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175915/" ]
You want [`UNION`](http://dev.mysql.com/doc/refman/5.0/en/union.html). ``` (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '') UNION (SELECT tr.full_name, tr.headlines, tr.content, tr.stamp, tr.person_key FROM tbl_transactions_bk_2012 tr JOIN persons p ON p.person_key = tr.person_key JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams') WHERE t.team_key = '' ```
While using the UNION query, you may also want to add indexes to any columns that you are using to join and filter which will improve performance
8,947,582
I'm trying to enumerate all hosts in an XML document, create a db entry for each host, then add each host's users (also from the XML document) to the db that are tied to that foreign key. The message box in the code below displays each user more times than there are `<user>` elements. I expected to see "a", "b" and "c" just twice each, but the code doesn't seem to stop displaying them. ``` private void simple_test() { var xml = "<root> <main> <host> <sub> <user> <name> a </name> </user> <user> <name> b </name> </user> <user> <name> c </name> </user> </sub> </host> <host> <sub> <user> <name> a </name> </user> <user> <name> b </name> </user> <user> <name> c </name> </user> </sub> </host> </main> </root>"; var xml_reader = XmlReader.Create(new StringReader(xml)); var xpath_doc = new XPathDocument(xml_reader); var xpath_nav = xpath_doc.CreateNavigator(); XPathExpression expr; expr = xpath_nav.Compile("//host/*"); var xpni = xpath_nav.Select(expr); while(xpni.MoveNext()) { if (xpni.Current == null) continue; var nav = xpni.Current.Clone(); expr = nav.Compile("//user/*"); var xpni2 = nav.Select(expr); while (xpni2.MoveNext()) { if (xpni2.Current == null) continue; var nav2 = xpni2.Current.Clone(); nav2.SelectSingleNode("//name"); MessageBox.Show(nav2.Value); } } } ```
2012/01/20
[ "https://Stackoverflow.com/questions/8947582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/511273/" ]
How about this: ``` private void simple_test() { var xml = "<root><main><host><sub><user><name>a</name></user><user><name>b</name></user><user><name>c</name></user></sub></host><host><sub><user><name>a</name></user><user><name>b</name></user><user><name>c</name></user></sub></host></main></root>"; var doc = XDocument.Parse(xml); foreach(var name in doc.descendants("name")){ MessageBox.Show(name.Value); } } ``` I didn't test but it should work. Good Luck!
``` var xml = "<root> <main> <host> <sub> <user> <name>a</name> </user> <user> <name>b</name> </user> <user> <name>c</name> </user> </sub> </host> <host> <sub> <user> <name>a</name> </user> <user> <name>b</name> </user> <user> <name>c</name> </user> </sub> </host> </main> </root>"; var doc = XDocument.Parse(xml); foreach(string name in doc.Descendants("name")) { MessageBox.Show(name); } ``` outputs: a b c a b c
8,947,582
I'm trying to enumerate all hosts in an XML document, create a db entry for each host, then add each host's users (also from the XML document) to the db that are tied to that foreign key. The message box in the code below displays each user more times than there are `<user>` elements. I expected to see "a", "b" and "c" just twice each, but the code doesn't seem to stop displaying them. ``` private void simple_test() { var xml = "<root> <main> <host> <sub> <user> <name> a </name> </user> <user> <name> b </name> </user> <user> <name> c </name> </user> </sub> </host> <host> <sub> <user> <name> a </name> </user> <user> <name> b </name> </user> <user> <name> c </name> </user> </sub> </host> </main> </root>"; var xml_reader = XmlReader.Create(new StringReader(xml)); var xpath_doc = new XPathDocument(xml_reader); var xpath_nav = xpath_doc.CreateNavigator(); XPathExpression expr; expr = xpath_nav.Compile("//host/*"); var xpni = xpath_nav.Select(expr); while(xpni.MoveNext()) { if (xpni.Current == null) continue; var nav = xpni.Current.Clone(); expr = nav.Compile("//user/*"); var xpni2 = nav.Select(expr); while (xpni2.MoveNext()) { if (xpni2.Current == null) continue; var nav2 = xpni2.Current.Clone(); nav2.SelectSingleNode("//name"); MessageBox.Show(nav2.Value); } } } ```
2012/01/20
[ "https://Stackoverflow.com/questions/8947582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/511273/" ]
As the others have demonstrated, there are more elegant ways to achieve what you need; however, if you’re looking for bugs in your code, here are two. First: ``` var nav2 = xpni.Current.Clone(); ``` should presumably be ``` var nav2 = xpni2.Current.Clone(); ``` Second: ``` expr = nav.Compile("//user/*"); ``` This would match *any* `user` elements in your document, and not just descendants of the current `sub`. Per the [XPath Examples](http://msdn.microsoft.com/en-us/library/ms256086.aspx) on MSDN: * `//author` matches all `<author>` elements in the document. * `.//title` matches all `<title>` elements one or more levels deep in the current context. Thus, if you want to match all `user` elements that are descendants of the current `sub` *at any level*, you may use: ``` expr = nav.Compile(".//user/*"); ``` In your case, since all `user` elements are direct children, it would be more efficient to use the following snippet: ``` expr = nav.Compile("./user/*"); ``` which is equivalent to: ``` expr = nav.Compile("user/*"); ``` This avoids unnecessarily traversing the hierarchy looking for deeper-nested elements which don’t exist. **Edit**: Removed some incorrect remarks pointed out in the comments.
How about this: ``` private void simple_test() { var xml = "<root><main><host><sub><user><name>a</name></user><user><name>b</name></user><user><name>c</name></user></sub></host><host><sub><user><name>a</name></user><user><name>b</name></user><user><name>c</name></user></sub></host></main></root>"; var doc = XDocument.Parse(xml); foreach(var name in doc.descendants("name")){ MessageBox.Show(name.Value); } } ``` I didn't test but it should work. Good Luck!
8,947,582
I'm trying to enumerate all hosts in an XML document, create a db entry for each host, then add each host's users (also from the XML document) to the db that are tied to that foreign key. The message box in the code below displays each user more times than there are `<user>` elements. I expected to see "a", "b" and "c" just twice each, but the code doesn't seem to stop displaying them. ``` private void simple_test() { var xml = "<root> <main> <host> <sub> <user> <name> a </name> </user> <user> <name> b </name> </user> <user> <name> c </name> </user> </sub> </host> <host> <sub> <user> <name> a </name> </user> <user> <name> b </name> </user> <user> <name> c </name> </user> </sub> </host> </main> </root>"; var xml_reader = XmlReader.Create(new StringReader(xml)); var xpath_doc = new XPathDocument(xml_reader); var xpath_nav = xpath_doc.CreateNavigator(); XPathExpression expr; expr = xpath_nav.Compile("//host/*"); var xpni = xpath_nav.Select(expr); while(xpni.MoveNext()) { if (xpni.Current == null) continue; var nav = xpni.Current.Clone(); expr = nav.Compile("//user/*"); var xpni2 = nav.Select(expr); while (xpni2.MoveNext()) { if (xpni2.Current == null) continue; var nav2 = xpni2.Current.Clone(); nav2.SelectSingleNode("//name"); MessageBox.Show(nav2.Value); } } } ```
2012/01/20
[ "https://Stackoverflow.com/questions/8947582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/511273/" ]
How about this: ``` private void simple_test() { var xml = "<root><main><host><sub><user><name>a</name></user><user><name>b</name></user><user><name>c</name></user></sub></host><host><sub><user><name>a</name></user><user><name>b</name></user><user><name>c</name></user></sub></host></main></root>"; var doc = XDocument.Parse(xml); foreach(var name in doc.descendants("name")){ MessageBox.Show(name.Value); } } ``` I didn't test but it should work. Good Luck!
**Use**: ``` /*/*/host[$k]/sub/user/name ``` where `$k` can take a value from 1 to `count(/*/*/host)`. **XSLT - based verification**: ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/"> <xsl:for-each select="/*/*/host"> <xsl:variable name="vPos" select="position()"/> <xsl:copy-of select="/*/*/host[$vPos]/sub/user/name"/> ============ </xsl:for-each> </xsl:template> </xsl:stylesheet> ``` **When this transformation is applied on the following XML document** (the provided one, slightly modified so that the names under different slots are different): ``` <root> <main> <host> <sub> <user> <name>a</name> </user> <user> <name>b</name> </user> <user> <name>c</name> </user> </sub> </host> <host> <sub> <user> <name>a2</name> </user> <user> <name>b2</name> </user> <user> <name>c2</name> </user> </sub> </host> </main> </root> ``` **the wanted elements are selected and copied to the output**. In the output between two selection results there is a string delimiter ("========") to make the individual selection results easily identifiable: ``` <name>a</name> <name>b</name> <name>c</name> ============ <name>a2</name> <name>b2</name> <name>c2</name> ============ ```
8,947,582
I'm trying to enumerate all hosts in an XML document, create a db entry for each host, then add each host's users (also from the XML document) to the db that are tied to that foreign key. The message box in the code below displays each user more times than there are `<user>` elements. I expected to see "a", "b" and "c" just twice each, but the code doesn't seem to stop displaying them. ``` private void simple_test() { var xml = "<root> <main> <host> <sub> <user> <name> a </name> </user> <user> <name> b </name> </user> <user> <name> c </name> </user> </sub> </host> <host> <sub> <user> <name> a </name> </user> <user> <name> b </name> </user> <user> <name> c </name> </user> </sub> </host> </main> </root>"; var xml_reader = XmlReader.Create(new StringReader(xml)); var xpath_doc = new XPathDocument(xml_reader); var xpath_nav = xpath_doc.CreateNavigator(); XPathExpression expr; expr = xpath_nav.Compile("//host/*"); var xpni = xpath_nav.Select(expr); while(xpni.MoveNext()) { if (xpni.Current == null) continue; var nav = xpni.Current.Clone(); expr = nav.Compile("//user/*"); var xpni2 = nav.Select(expr); while (xpni2.MoveNext()) { if (xpni2.Current == null) continue; var nav2 = xpni2.Current.Clone(); nav2.SelectSingleNode("//name"); MessageBox.Show(nav2.Value); } } } ```
2012/01/20
[ "https://Stackoverflow.com/questions/8947582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/511273/" ]
As the others have demonstrated, there are more elegant ways to achieve what you need; however, if you’re looking for bugs in your code, here are two. First: ``` var nav2 = xpni.Current.Clone(); ``` should presumably be ``` var nav2 = xpni2.Current.Clone(); ``` Second: ``` expr = nav.Compile("//user/*"); ``` This would match *any* `user` elements in your document, and not just descendants of the current `sub`. Per the [XPath Examples](http://msdn.microsoft.com/en-us/library/ms256086.aspx) on MSDN: * `//author` matches all `<author>` elements in the document. * `.//title` matches all `<title>` elements one or more levels deep in the current context. Thus, if you want to match all `user` elements that are descendants of the current `sub` *at any level*, you may use: ``` expr = nav.Compile(".//user/*"); ``` In your case, since all `user` elements are direct children, it would be more efficient to use the following snippet: ``` expr = nav.Compile("./user/*"); ``` which is equivalent to: ``` expr = nav.Compile("user/*"); ``` This avoids unnecessarily traversing the hierarchy looking for deeper-nested elements which don’t exist. **Edit**: Removed some incorrect remarks pointed out in the comments.
``` var xml = "<root> <main> <host> <sub> <user> <name>a</name> </user> <user> <name>b</name> </user> <user> <name>c</name> </user> </sub> </host> <host> <sub> <user> <name>a</name> </user> <user> <name>b</name> </user> <user> <name>c</name> </user> </sub> </host> </main> </root>"; var doc = XDocument.Parse(xml); foreach(string name in doc.Descendants("name")) { MessageBox.Show(name); } ``` outputs: a b c a b c
8,947,582
I'm trying to enumerate all hosts in an XML document, create a db entry for each host, then add each host's users (also from the XML document) to the db that are tied to that foreign key. The message box in the code below displays each user more times than there are `<user>` elements. I expected to see "a", "b" and "c" just twice each, but the code doesn't seem to stop displaying them. ``` private void simple_test() { var xml = "<root> <main> <host> <sub> <user> <name> a </name> </user> <user> <name> b </name> </user> <user> <name> c </name> </user> </sub> </host> <host> <sub> <user> <name> a </name> </user> <user> <name> b </name> </user> <user> <name> c </name> </user> </sub> </host> </main> </root>"; var xml_reader = XmlReader.Create(new StringReader(xml)); var xpath_doc = new XPathDocument(xml_reader); var xpath_nav = xpath_doc.CreateNavigator(); XPathExpression expr; expr = xpath_nav.Compile("//host/*"); var xpni = xpath_nav.Select(expr); while(xpni.MoveNext()) { if (xpni.Current == null) continue; var nav = xpni.Current.Clone(); expr = nav.Compile("//user/*"); var xpni2 = nav.Select(expr); while (xpni2.MoveNext()) { if (xpni2.Current == null) continue; var nav2 = xpni2.Current.Clone(); nav2.SelectSingleNode("//name"); MessageBox.Show(nav2.Value); } } } ```
2012/01/20
[ "https://Stackoverflow.com/questions/8947582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/511273/" ]
As the others have demonstrated, there are more elegant ways to achieve what you need; however, if you’re looking for bugs in your code, here are two. First: ``` var nav2 = xpni.Current.Clone(); ``` should presumably be ``` var nav2 = xpni2.Current.Clone(); ``` Second: ``` expr = nav.Compile("//user/*"); ``` This would match *any* `user` elements in your document, and not just descendants of the current `sub`. Per the [XPath Examples](http://msdn.microsoft.com/en-us/library/ms256086.aspx) on MSDN: * `//author` matches all `<author>` elements in the document. * `.//title` matches all `<title>` elements one or more levels deep in the current context. Thus, if you want to match all `user` elements that are descendants of the current `sub` *at any level*, you may use: ``` expr = nav.Compile(".//user/*"); ``` In your case, since all `user` elements are direct children, it would be more efficient to use the following snippet: ``` expr = nav.Compile("./user/*"); ``` which is equivalent to: ``` expr = nav.Compile("user/*"); ``` This avoids unnecessarily traversing the hierarchy looking for deeper-nested elements which don’t exist. **Edit**: Removed some incorrect remarks pointed out in the comments.
**Use**: ``` /*/*/host[$k]/sub/user/name ``` where `$k` can take a value from 1 to `count(/*/*/host)`. **XSLT - based verification**: ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/"> <xsl:for-each select="/*/*/host"> <xsl:variable name="vPos" select="position()"/> <xsl:copy-of select="/*/*/host[$vPos]/sub/user/name"/> ============ </xsl:for-each> </xsl:template> </xsl:stylesheet> ``` **When this transformation is applied on the following XML document** (the provided one, slightly modified so that the names under different slots are different): ``` <root> <main> <host> <sub> <user> <name>a</name> </user> <user> <name>b</name> </user> <user> <name>c</name> </user> </sub> </host> <host> <sub> <user> <name>a2</name> </user> <user> <name>b2</name> </user> <user> <name>c2</name> </user> </sub> </host> </main> </root> ``` **the wanted elements are selected and copied to the output**. In the output between two selection results there is a string delimiter ("========") to make the individual selection results easily identifiable: ``` <name>a</name> <name>b</name> <name>c</name> ============ <name>a2</name> <name>b2</name> <name>c2</name> ============ ```
30,533,568
Is there any way prevent angular from auto trim for fields in the whole application? I know that I can prevent it for specified field using ngTrim directive, but it doesn't look good add this directive to all text fields in the application, is there any way do it for all fields in the angular module? Here is code, if you add add spaces in the begin of input they will not appear in label: ``` <div ng-app> <div ng-controller="TodoCtrl"> {{field}} <input type="text" ng-model="field"> </div> </div> ```
2015/05/29
[ "https://Stackoverflow.com/questions/30533568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2992825/" ]
You can extend [input[text]](https://docs.angularjs.org/api/ng/input/input%5Btext%5D) directive, the code below will automatically change the value of the attribute `ngTrim` to `false`: ``` .directive('input', function($compile){ // Runs during compile return { link(scope, iElement, iAttrs) { if (iElement.attr('type') === 'text') { iAttrs.$set('ngTrim', "false"); } } }; }); ``` Reference: <https://docs.angularjs.org/api/ng/type/>$compile.directive.Attributes ```html <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example - example-text-input-directive</title> <script src="https://docs.angularjs.org/angular.min.js"></script> </head> <body ng-app="textInputExample"> <script> angular.module('textInputExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.example = { text: 'guest' }; }]) .directive('input', function($compile){ // Runs during compile return { link(scope, iElement, iAttrs) { if (iElement.attr('type') === 'text') { iAttrs.$set('ngTrim', "false"); } } }; }); </script> <form name="myForm" ng-controller="ExampleController"> <label>Single word: <input type="text" name="input" ng-model="example.text" required> </label> <div role="alert"> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.pattern"> Single word only!</span> </div> <tt>text = {{example.text}} - 3</tt><br/> <tt>text = {{example.text.length}} - 3</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </body> </html> ``` **EDIT:** **How it works** 1) You can bind multiple directives to the same html element and they can share the same `$scope` and `$attributes`. 2) `iAttrs.$set('ngTrim', "false");` is updating the attribute `ng-trim`. You can't do this using normal dom manipulation because the dom is already compiled (<https://docs.angularjs.org/api/ng/service/>$compile) 3) Calling `iAttrs.$set` will trigger updates on all directives, so it will override the original `ng-trim` attribute value.
Another way to extend the `input` directive (or any directive/service, for that matter) is by using a [decorator](https://docs.angularjs.org/api/auto/service/$provide#decorator): ``` app.config(function($provide) { $provide.decorator('inputDirective', function($delegate) { var directive = $delegate[0], link = directive.link; link.post = function(scope, element, attrs) { attrs.$set('ngTrim', 'false'); }; return $delegate; }); }); ``` [Working Plunker](http://plnkr.co/edit/RqMEu46pihb2UCXUpSRt?p=preview) I personally prefer this approach because it allows me to execute the directive's original code, if needed. In this particular case that isn't necessary because the `input` directive has no link function, so you can simply provide your own without worrying about breaking anything.
1,414,358
I want to set the control binding property "updatesource=Explicit" in cs file (dynamically) not in UI end. Please help me how can i do this?
2009/09/12
[ "https://Stackoverflow.com/questions/1414358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
it works :) ``` this.GetBindingExpression(SomeProperty).ParentBinding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit; ```
Are you creating the binding in code manually? If so you can just set it like any other property: ``` var binding = new Binding("BindingPath") { Source = myDataObject, UpdateSourceTrigger = UpdateSourceTrigger.Explicit } textBlock.SetBinding(TextBlock.TextProperty, binding); ``` [More information here](http://msdn.microsoft.com/en-us/library/ms742863.aspx).
1,414,358
I want to set the control binding property "updatesource=Explicit" in cs file (dynamically) not in UI end. Please help me how can i do this?
2009/09/12
[ "https://Stackoverflow.com/questions/1414358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
it works :) ``` this.GetBindingExpression(SomeProperty).ParentBinding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit; ```
I tested it and it works. :-) The code remains the same as Gimalay's. ``` BindingExpression bindingExpr = this.textBox1.GetBindingExpression(TextBox.TextProperty); bindingExpr.ParentBinding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit; ```
46,728,366
I have some code that I found online that fits my project perfectly. The issue is that I don't use storyboards at all. Instead of using a storyboard file to create the UIView **`(CustomCallOutView)`**, I just create a class with a subclass of UIView. Here's the code that requires a nib file but I don't want to use them. How do I achieve this? The code is below. Thank you! ``` func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { // 1 if view.annotation is MKUserLocation { // Don't proceed with custom callout return } // 2 let starbucksAnnotation = view.annotation as! StarbucksAnnotation let views = Bundle.main.loadNibNamed("CustomCalloutView", owner: nil, options: nil) let calloutView = views?[0] as! CustomCalloutView calloutView.starbucksName.text = starbucksAnnotation.name calloutView.starbucksAddress.text = starbucksAnnotation.address calloutView.starbucksPhone.text = starbucksAnnotation.phone calloutView.starbucksImage.image = starbucksAnnotation.image let button = UIButton(frame: calloutView.starbucksPhone.frame) button.addTarget(self, action: #selector(ViewController.callPhoneNumber(sender:)), for: .touchUpInside) calloutView.addSubview(button) // 3 calloutView.center = CGPoint(x: view.bounds.size.width / 2, y: -calloutView.bounds.size.height*0.52) view.addSubview(calloutView) mapView.setCenter((view.annotation?.coordinate)!, animated: true) } ```
2017/10/13
[ "https://Stackoverflow.com/questions/46728366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6406541/" ]
I am not aware whether this is possible with a Wikipedia API function. However, it can be done using quite ordinary Python code. ``` >>> from lxml import html >>> import requests ``` Fetch the page that lists all of the featured articles. ``` >>> page = requests.get('https://en.wikipedia.org/wiki/Wikipedia:Featured_articles').content ``` Parse it suitably for search purposes. ``` >>> tree = html.fromstring(page) ``` Assume that we're searching for the wikipedia article entitled 'Melbourne Castle'. ``` >>> wiki_title = 'Melbourne Castle' ``` Find any links with this title. ``` >>> links = tree.xpath('.//a[@href="/wiki/%s"]'%wiki_title.replace(' ', '_')) ``` If `links` is a non-empty list, meaning that a link to an article with the title 'Melbourne Castle' has been found, then print a suitable result, or otherwise. ``` >>> if links: ... links[0].text + ' is a featured article' ... else: ... links[0].text + ' is NOT a featured article' ... 'Melbourne Castle is a featured article' ```
I just found a way to do that.I could get all the pages in a Category using `Categorymembers` <https://www.mediawiki.org/wiki/API:Categorymembers>
46,728,366
I have some code that I found online that fits my project perfectly. The issue is that I don't use storyboards at all. Instead of using a storyboard file to create the UIView **`(CustomCallOutView)`**, I just create a class with a subclass of UIView. Here's the code that requires a nib file but I don't want to use them. How do I achieve this? The code is below. Thank you! ``` func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { // 1 if view.annotation is MKUserLocation { // Don't proceed with custom callout return } // 2 let starbucksAnnotation = view.annotation as! StarbucksAnnotation let views = Bundle.main.loadNibNamed("CustomCalloutView", owner: nil, options: nil) let calloutView = views?[0] as! CustomCalloutView calloutView.starbucksName.text = starbucksAnnotation.name calloutView.starbucksAddress.text = starbucksAnnotation.address calloutView.starbucksPhone.text = starbucksAnnotation.phone calloutView.starbucksImage.image = starbucksAnnotation.image let button = UIButton(frame: calloutView.starbucksPhone.frame) button.addTarget(self, action: #selector(ViewController.callPhoneNumber(sender:)), for: .touchUpInside) calloutView.addSubview(button) // 3 calloutView.center = CGPoint(x: view.bounds.size.width / 2, y: -calloutView.bounds.size.height*0.52) view.addSubview(calloutView) mapView.setCenter((view.annotation?.coordinate)!, animated: true) } ```
2017/10/13
[ "https://Stackoverflow.com/questions/46728366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6406541/" ]
Probably the most semantic and portable approach is checking for [Wikidata badges](https://www.wikidata.org/wiki/Help:Badges) ([example](https://www.wikidata.org/wiki/Special:ApiSandbox#action=wbgetentities&format=json&sites=enwiki&titles=Melbourne%20Castle&props=sitelinks&sitefilter=enwiki&formatversion=2)) although the repsonse format is a bit obscure. Alternatively, you can check for the featured article category via the `list=categorymembers` API module or for the featured article template via the `prop=transcludedin` module.
I just found a way to do that.I could get all the pages in a Category using `Categorymembers` <https://www.mediawiki.org/wiki/API:Categorymembers>
90,984
I'm about to start a campaign using MgT 2e and I have tons of GT material but I've read over and over again how **Behind the Claw** (for GT) differs from **OTU**. I'm not interested on moving rules from GURPS to MgT 2e, but information, so I just want to know which are the points where **GT** background is different from **OTU** (beyond the Dulinor issues). Bear in mind that I intend to play the *Golden Age* (1105-) or just after the *Fifth Frontier War*.
2016/11/29
[ "https://rpg.stackexchange.com/questions/90984", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/7885/" ]
Take an leaf from (historical) fiction ====================================== [Das Boat's convoy attack](https://www.youtube.com/watch?v=_jP-eOrv2Ok) is a good example of a submarine fight. The book is very good too. You could easily adapt this to a space opera setting. The [Master and Commander](http://www.imdb.com/title/tt0311113/) film (and book) are another good example where ship-to-ship combat. Finally, [Midway](http://www.imdb.com/title/tt0074899/) is a great film focusing on both the air and naval sides of the battle. Space opera generally tend to see space as either submarine warfare ([The Expanse](http://www.imdb.com/title/tt3230854/?ref_=fn_al_tt_1)) or glorified air plane combat ([Cowboy Bebop](http://www.imdb.com/title/tt0213338/?ref_=fn_al_tt_1), Star Wars). Of course, all of them take their inspiration for real life™. You could do that too: [Raid on the Medway](https://en.wikipedia.org/wiki/Raid_on_the_Medway) for example. So, do what these guys do: use limited information to build tension, raise the stakes, and then explode in a fast ball of fire! Repeat. Why the battle matters? ======================= The game should be about the player characters, so that is where your focus should go. Ships blowing up are good special effects that can be seen but rarely interacted with. Why are the players there? What are they trying to achieve? Once you have an answer to that, you can make combat more interesting by focusing on what the players do, not the ships. It is the hundred of small decisions in the middle of the battle that matters: Do we support ship X or attack ship Z? Do we keep firing on ship A to sink it, or do we allow it to flee? Do we move to intercept T or just fire some torpedoes? Do we try to disengage or keep close to their capital ship? How are we dealing with damage to the ship? Finally, combat takes a long time (hours/days), which is generally not modelled well by RPG systems: so use more descriptions rather than tactical info dumps. You can, of course, focus the action from time to time where critical events happen.
A quick solution can be to force a **choice from the players**. Basically it means that on the standard turn they won't be able to perfectly fill all the roles so they will have to choose which ones are filled and which ones are not. For example in your ship you can have the following roles: commander (who give bonuses to morale tests), seeker (who make the ship able to react in case of imminent danger), gunner (who attack the enemy), pilot (who makes the ship dodge), shipwright (who repairs the damages)... You can imagine the unfilled roles as under the responsibility of a random NPC who will do the job but without giving bonuses. Each turn, make your player decide which roles they want to do. The role can be more or less useful depending on the situation (in close-quarter combat the seeker becomes less useful for example), and PCs will be more or less good at each role. For some roles you may discourage, or even forbid, that two PCs fill it (by making the bonuses from the second PC less important for example). Add to that some events that will accentuate the need for all the roles, and your players will really have to choose. For example: * the rudder is damaged by a previous salve, piloting becomes very difficult (malus), but a quick repair would fix that. * fog raises, and without a seeker it becomes very difficult to aim these fires. * some members of the crew fell from the ship, without a rescuer they are in big trouble * there is a weird sound coming from the south, what is it ? Maybe it would worth that someone prepares for a counter-measure. Maybe not. * the enemy have started firing gold coins. Your pirate crew is trying to gather them and don't answer your orders anymore, unless a talented commander give them an earbashing. This solution is inspired by a homemade space-op system I played with (not as the GM).
90,984
I'm about to start a campaign using MgT 2e and I have tons of GT material but I've read over and over again how **Behind the Claw** (for GT) differs from **OTU**. I'm not interested on moving rules from GURPS to MgT 2e, but information, so I just want to know which are the points where **GT** background is different from **OTU** (beyond the Dulinor issues). Bear in mind that I intend to play the *Golden Age* (1105-) or just after the *Fifth Frontier War*.
2016/11/29
[ "https://rpg.stackexchange.com/questions/90984", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/7885/" ]
Take an leaf from (historical) fiction ====================================== [Das Boat's convoy attack](https://www.youtube.com/watch?v=_jP-eOrv2Ok) is a good example of a submarine fight. The book is very good too. You could easily adapt this to a space opera setting. The [Master and Commander](http://www.imdb.com/title/tt0311113/) film (and book) are another good example where ship-to-ship combat. Finally, [Midway](http://www.imdb.com/title/tt0074899/) is a great film focusing on both the air and naval sides of the battle. Space opera generally tend to see space as either submarine warfare ([The Expanse](http://www.imdb.com/title/tt3230854/?ref_=fn_al_tt_1)) or glorified air plane combat ([Cowboy Bebop](http://www.imdb.com/title/tt0213338/?ref_=fn_al_tt_1), Star Wars). Of course, all of them take their inspiration for real life™. You could do that too: [Raid on the Medway](https://en.wikipedia.org/wiki/Raid_on_the_Medway) for example. So, do what these guys do: use limited information to build tension, raise the stakes, and then explode in a fast ball of fire! Repeat. Why the battle matters? ======================= The game should be about the player characters, so that is where your focus should go. Ships blowing up are good special effects that can be seen but rarely interacted with. Why are the players there? What are they trying to achieve? Once you have an answer to that, you can make combat more interesting by focusing on what the players do, not the ships. It is the hundred of small decisions in the middle of the battle that matters: Do we support ship X or attack ship Z? Do we keep firing on ship A to sink it, or do we allow it to flee? Do we move to intercept T or just fire some torpedoes? Do we try to disengage or keep close to their capital ship? How are we dealing with damage to the ship? Finally, combat takes a long time (hours/days), which is generally not modelled well by RPG systems: so use more descriptions rather than tactical info dumps. You can, of course, focus the action from time to time where critical events happen.
My answer is for my experience with space battles not sea. Space battles in most games I have run tend to have terrible rules that bear little relation to how things move in space or the vast distances and ridiculous speeds. Space battles seem to me to be games of chess, with ships dancing around each other trying to get a line of fire on the enemy while avoiding having the same occur to them. As the point that a large lance weapon or broadside can be brought to bear the game is often over. Boarding in space is more fun as you have to match velocity to dock/storm the vessel or have some kind of teleporter or boarding shuttles. To keep this fluid I tend to bin most movement rules(most of the rules) in the system. And take speed as the change in velocity a ship can affect. Also rotating on the spot in space takes virtually no effort, but changing direction should be difficult. I take acceleration/speed to be in mm so a speed of 6 is 6mm/turn/turn on the table, as after a few turns of combat you can be covering large distances. So if travelling in a straight line you cover 6mm in first turn 12mm in second, 18 in third etc. So you can go very "fast" but stopping or turning becomes more difficult the faster you go. I clear as large a table as possible. Battle start far apart, space is big and I like this to be represented. I also give players 60 seconds to plan their next move; so if flows quickly. If they don't give me written instructions at the 60s mark then they continue to do what they did last turn. Think of it like a bridge on a ship where the command staff discuss tactics and plan and then pass notes to the helmsman and gunnery staff. I also have to have written down what I am going to do with the NPC ships before I look at their notes. Often for enemy ships I have a plan and contingencies and follow them so I as GM can't be accused of cheating. I find the dancing is the fun, there are very few dice roles unless you want to overdirve the engines or jury rig your ship in some silly way. The game flows as the ships close or circle each other. The roles are only needed for targeting, firing and damage. I don't know if this is what you were looking for but my players really enjoyed their space battles when run this way. Try it, see what works and what doesn't for you and tweak as needed.
90,984
I'm about to start a campaign using MgT 2e and I have tons of GT material but I've read over and over again how **Behind the Claw** (for GT) differs from **OTU**. I'm not interested on moving rules from GURPS to MgT 2e, but information, so I just want to know which are the points where **GT** background is different from **OTU** (beyond the Dulinor issues). Bear in mind that I intend to play the *Golden Age* (1105-) or just after the *Fifth Frontier War*.
2016/11/29
[ "https://rpg.stackexchange.com/questions/90984", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/7885/" ]
Take an leaf from (historical) fiction ====================================== [Das Boat's convoy attack](https://www.youtube.com/watch?v=_jP-eOrv2Ok) is a good example of a submarine fight. The book is very good too. You could easily adapt this to a space opera setting. The [Master and Commander](http://www.imdb.com/title/tt0311113/) film (and book) are another good example where ship-to-ship combat. Finally, [Midway](http://www.imdb.com/title/tt0074899/) is a great film focusing on both the air and naval sides of the battle. Space opera generally tend to see space as either submarine warfare ([The Expanse](http://www.imdb.com/title/tt3230854/?ref_=fn_al_tt_1)) or glorified air plane combat ([Cowboy Bebop](http://www.imdb.com/title/tt0213338/?ref_=fn_al_tt_1), Star Wars). Of course, all of them take their inspiration for real life™. You could do that too: [Raid on the Medway](https://en.wikipedia.org/wiki/Raid_on_the_Medway) for example. So, do what these guys do: use limited information to build tension, raise the stakes, and then explode in a fast ball of fire! Repeat. Why the battle matters? ======================= The game should be about the player characters, so that is where your focus should go. Ships blowing up are good special effects that can be seen but rarely interacted with. Why are the players there? What are they trying to achieve? Once you have an answer to that, you can make combat more interesting by focusing on what the players do, not the ships. It is the hundred of small decisions in the middle of the battle that matters: Do we support ship X or attack ship Z? Do we keep firing on ship A to sink it, or do we allow it to flee? Do we move to intercept T or just fire some torpedoes? Do we try to disengage or keep close to their capital ship? How are we dealing with damage to the ship? Finally, combat takes a long time (hours/days), which is generally not modelled well by RPG systems: so use more descriptions rather than tactical info dumps. You can, of course, focus the action from time to time where critical events happen.
What I found in sea or space battles is that players have no clue what ships look like. No matter how popular you think the ships are, some of your players will not be able to visualize them in the detail you expect. Take for example a [three master](https://www.google.de/search?q=three+master&tbm=isch&tbo=u&source=univ&sa=X&ved=0ahUKEwi4o6uVoM7QAhXkDZoKHWPRCZ8QsAQILA&biw=1433&bih=760). If the DM says something like "after the smoke of your broadside clears, you see the enemy ship has sustained heavy damage, it's foremast broken and hanging over the side", expect players to not be able to accurately describe the scene, no matter how many popular movies you have seen and you *think* they have seen. And it gets even worse with space battles, with all kind of popular fiction depicting ships differently. Make sure you have pictures or props of the ships or ideally, both. Being able to picture the scene, even if the pictures are given, is a huge boost in playability. Prepare in advance as a DM, so you have pictures of possible encounters, possible damage and other outcomes (beaches, asteroids, whatever). Rogue Trader and 40K for example has a very distinct style and that style is a big part of how it *feels*. Fighting an Ork dreadnought or a sleek Eldar frigate *feels* completely different even if you are rolling the same dice. There's pictures of both all over the net. And if you want to have a great evening, maybe you can find some Battlefleet Gothic miniatures to put in the middle of the table. Now if you and your players are unhappy with the *system* I guess you need to find a better system. Personally, I was happy with Rogue Trader, but if you are not, maybe it's just not the right system for you.
90,984
I'm about to start a campaign using MgT 2e and I have tons of GT material but I've read over and over again how **Behind the Claw** (for GT) differs from **OTU**. I'm not interested on moving rules from GURPS to MgT 2e, but information, so I just want to know which are the points where **GT** background is different from **OTU** (beyond the Dulinor issues). Bear in mind that I intend to play the *Golden Age* (1105-) or just after the *Fifth Frontier War*.
2016/11/29
[ "https://rpg.stackexchange.com/questions/90984", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/7885/" ]
Take an leaf from (historical) fiction ====================================== [Das Boat's convoy attack](https://www.youtube.com/watch?v=_jP-eOrv2Ok) is a good example of a submarine fight. The book is very good too. You could easily adapt this to a space opera setting. The [Master and Commander](http://www.imdb.com/title/tt0311113/) film (and book) are another good example where ship-to-ship combat. Finally, [Midway](http://www.imdb.com/title/tt0074899/) is a great film focusing on both the air and naval sides of the battle. Space opera generally tend to see space as either submarine warfare ([The Expanse](http://www.imdb.com/title/tt3230854/?ref_=fn_al_tt_1)) or glorified air plane combat ([Cowboy Bebop](http://www.imdb.com/title/tt0213338/?ref_=fn_al_tt_1), Star Wars). Of course, all of them take their inspiration for real life™. You could do that too: [Raid on the Medway](https://en.wikipedia.org/wiki/Raid_on_the_Medway) for example. So, do what these guys do: use limited information to build tension, raise the stakes, and then explode in a fast ball of fire! Repeat. Why the battle matters? ======================= The game should be about the player characters, so that is where your focus should go. Ships blowing up are good special effects that can be seen but rarely interacted with. Why are the players there? What are they trying to achieve? Once you have an answer to that, you can make combat more interesting by focusing on what the players do, not the ships. It is the hundred of small decisions in the middle of the battle that matters: Do we support ship X or attack ship Z? Do we keep firing on ship A to sink it, or do we allow it to flee? Do we move to intercept T or just fire some torpedoes? Do we try to disengage or keep close to their capital ship? How are we dealing with damage to the ship? Finally, combat takes a long time (hours/days), which is generally not modelled well by RPG systems: so use more descriptions rather than tactical info dumps. You can, of course, focus the action from time to time where critical events happen.
As a Rogue Trader RPG veteran, I understand your problem. RT is trying to combine two distinct gaming experiences; RPG’s and wargaming. In wargaming, the pleasure is derived from fighting the battles according to the rules with the players commanding either units or parts of the battlefield. In RPG’s, the players play their characters. It’s the combination that fails IMO. Our solution was to throw away the minutiae of ship fighting and make it a more of a RPG session. So instead of mapping out the manoeuvres, broadsides etc., change it into a story in which the players have certain parts to play. And use the crew’s rating, not the players for the ship’s rolls. Players can give a bonus but it makes no sense that for example a single player’s gunnery rating works for a ship of 100,000 crew…. So describe noticing the enemy ship on the scanners (perhaps insert a scene where the scanners go on the fritz and the tech-priest has to fix it), manoeuvring the ship into an advantageous combat position (insert scene where a rudder fails, the engines go off-line, zombies come crawling out of the ventilation ducts, the crew needs a hearty speech etc.), then describe the first salvoes and roll for damage. Describe the effect of damage on your ship and then let the players effect repairs or work around the issues. In short, eliminate tactical rounds, just play the enemy ship intelligently, and throw in scenes/challenges for the players aboard their own ship. Space combat takes forever so there is enough time to solve (small) issues before the next broadside arrives. The entire encounter should be tense and nerve-wracking and things are always breaking down at the worst moment. The players should be running around fixing things or getting the crew to work at maximum efficiency. That also offers them the chance to use their skills instead of just moving the ship and firing every round.
90,984
I'm about to start a campaign using MgT 2e and I have tons of GT material but I've read over and over again how **Behind the Claw** (for GT) differs from **OTU**. I'm not interested on moving rules from GURPS to MgT 2e, but information, so I just want to know which are the points where **GT** background is different from **OTU** (beyond the Dulinor issues). Bear in mind that I intend to play the *Golden Age* (1105-) or just after the *Fifth Frontier War*.
2016/11/29
[ "https://rpg.stackexchange.com/questions/90984", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/7885/" ]
What I found in sea or space battles is that players have no clue what ships look like. No matter how popular you think the ships are, some of your players will not be able to visualize them in the detail you expect. Take for example a [three master](https://www.google.de/search?q=three+master&tbm=isch&tbo=u&source=univ&sa=X&ved=0ahUKEwi4o6uVoM7QAhXkDZoKHWPRCZ8QsAQILA&biw=1433&bih=760). If the DM says something like "after the smoke of your broadside clears, you see the enemy ship has sustained heavy damage, it's foremast broken and hanging over the side", expect players to not be able to accurately describe the scene, no matter how many popular movies you have seen and you *think* they have seen. And it gets even worse with space battles, with all kind of popular fiction depicting ships differently. Make sure you have pictures or props of the ships or ideally, both. Being able to picture the scene, even if the pictures are given, is a huge boost in playability. Prepare in advance as a DM, so you have pictures of possible encounters, possible damage and other outcomes (beaches, asteroids, whatever). Rogue Trader and 40K for example has a very distinct style and that style is a big part of how it *feels*. Fighting an Ork dreadnought or a sleek Eldar frigate *feels* completely different even if you are rolling the same dice. There's pictures of both all over the net. And if you want to have a great evening, maybe you can find some Battlefleet Gothic miniatures to put in the middle of the table. Now if you and your players are unhappy with the *system* I guess you need to find a better system. Personally, I was happy with Rogue Trader, but if you are not, maybe it's just not the right system for you.
A quick solution can be to force a **choice from the players**. Basically it means that on the standard turn they won't be able to perfectly fill all the roles so they will have to choose which ones are filled and which ones are not. For example in your ship you can have the following roles: commander (who give bonuses to morale tests), seeker (who make the ship able to react in case of imminent danger), gunner (who attack the enemy), pilot (who makes the ship dodge), shipwright (who repairs the damages)... You can imagine the unfilled roles as under the responsibility of a random NPC who will do the job but without giving bonuses. Each turn, make your player decide which roles they want to do. The role can be more or less useful depending on the situation (in close-quarter combat the seeker becomes less useful for example), and PCs will be more or less good at each role. For some roles you may discourage, or even forbid, that two PCs fill it (by making the bonuses from the second PC less important for example). Add to that some events that will accentuate the need for all the roles, and your players will really have to choose. For example: * the rudder is damaged by a previous salve, piloting becomes very difficult (malus), but a quick repair would fix that. * fog raises, and without a seeker it becomes very difficult to aim these fires. * some members of the crew fell from the ship, without a rescuer they are in big trouble * there is a weird sound coming from the south, what is it ? Maybe it would worth that someone prepares for a counter-measure. Maybe not. * the enemy have started firing gold coins. Your pirate crew is trying to gather them and don't answer your orders anymore, unless a talented commander give them an earbashing. This solution is inspired by a homemade space-op system I played with (not as the GM).
90,984
I'm about to start a campaign using MgT 2e and I have tons of GT material but I've read over and over again how **Behind the Claw** (for GT) differs from **OTU**. I'm not interested on moving rules from GURPS to MgT 2e, but information, so I just want to know which are the points where **GT** background is different from **OTU** (beyond the Dulinor issues). Bear in mind that I intend to play the *Golden Age* (1105-) or just after the *Fifth Frontier War*.
2016/11/29
[ "https://rpg.stackexchange.com/questions/90984", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/7885/" ]
As a Rogue Trader RPG veteran, I understand your problem. RT is trying to combine two distinct gaming experiences; RPG’s and wargaming. In wargaming, the pleasure is derived from fighting the battles according to the rules with the players commanding either units or parts of the battlefield. In RPG’s, the players play their characters. It’s the combination that fails IMO. Our solution was to throw away the minutiae of ship fighting and make it a more of a RPG session. So instead of mapping out the manoeuvres, broadsides etc., change it into a story in which the players have certain parts to play. And use the crew’s rating, not the players for the ship’s rolls. Players can give a bonus but it makes no sense that for example a single player’s gunnery rating works for a ship of 100,000 crew…. So describe noticing the enemy ship on the scanners (perhaps insert a scene where the scanners go on the fritz and the tech-priest has to fix it), manoeuvring the ship into an advantageous combat position (insert scene where a rudder fails, the engines go off-line, zombies come crawling out of the ventilation ducts, the crew needs a hearty speech etc.), then describe the first salvoes and roll for damage. Describe the effect of damage on your ship and then let the players effect repairs or work around the issues. In short, eliminate tactical rounds, just play the enemy ship intelligently, and throw in scenes/challenges for the players aboard their own ship. Space combat takes forever so there is enough time to solve (small) issues before the next broadside arrives. The entire encounter should be tense and nerve-wracking and things are always breaking down at the worst moment. The players should be running around fixing things or getting the crew to work at maximum efficiency. That also offers them the chance to use their skills instead of just moving the ship and firing every round.
A quick solution can be to force a **choice from the players**. Basically it means that on the standard turn they won't be able to perfectly fill all the roles so they will have to choose which ones are filled and which ones are not. For example in your ship you can have the following roles: commander (who give bonuses to morale tests), seeker (who make the ship able to react in case of imminent danger), gunner (who attack the enemy), pilot (who makes the ship dodge), shipwright (who repairs the damages)... You can imagine the unfilled roles as under the responsibility of a random NPC who will do the job but without giving bonuses. Each turn, make your player decide which roles they want to do. The role can be more or less useful depending on the situation (in close-quarter combat the seeker becomes less useful for example), and PCs will be more or less good at each role. For some roles you may discourage, or even forbid, that two PCs fill it (by making the bonuses from the second PC less important for example). Add to that some events that will accentuate the need for all the roles, and your players will really have to choose. For example: * the rudder is damaged by a previous salve, piloting becomes very difficult (malus), but a quick repair would fix that. * fog raises, and without a seeker it becomes very difficult to aim these fires. * some members of the crew fell from the ship, without a rescuer they are in big trouble * there is a weird sound coming from the south, what is it ? Maybe it would worth that someone prepares for a counter-measure. Maybe not. * the enemy have started firing gold coins. Your pirate crew is trying to gather them and don't answer your orders anymore, unless a talented commander give them an earbashing. This solution is inspired by a homemade space-op system I played with (not as the GM).
90,984
I'm about to start a campaign using MgT 2e and I have tons of GT material but I've read over and over again how **Behind the Claw** (for GT) differs from **OTU**. I'm not interested on moving rules from GURPS to MgT 2e, but information, so I just want to know which are the points where **GT** background is different from **OTU** (beyond the Dulinor issues). Bear in mind that I intend to play the *Golden Age* (1105-) or just after the *Fifth Frontier War*.
2016/11/29
[ "https://rpg.stackexchange.com/questions/90984", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/7885/" ]
What I found in sea or space battles is that players have no clue what ships look like. No matter how popular you think the ships are, some of your players will not be able to visualize them in the detail you expect. Take for example a [three master](https://www.google.de/search?q=three+master&tbm=isch&tbo=u&source=univ&sa=X&ved=0ahUKEwi4o6uVoM7QAhXkDZoKHWPRCZ8QsAQILA&biw=1433&bih=760). If the DM says something like "after the smoke of your broadside clears, you see the enemy ship has sustained heavy damage, it's foremast broken and hanging over the side", expect players to not be able to accurately describe the scene, no matter how many popular movies you have seen and you *think* they have seen. And it gets even worse with space battles, with all kind of popular fiction depicting ships differently. Make sure you have pictures or props of the ships or ideally, both. Being able to picture the scene, even if the pictures are given, is a huge boost in playability. Prepare in advance as a DM, so you have pictures of possible encounters, possible damage and other outcomes (beaches, asteroids, whatever). Rogue Trader and 40K for example has a very distinct style and that style is a big part of how it *feels*. Fighting an Ork dreadnought or a sleek Eldar frigate *feels* completely different even if you are rolling the same dice. There's pictures of both all over the net. And if you want to have a great evening, maybe you can find some Battlefleet Gothic miniatures to put in the middle of the table. Now if you and your players are unhappy with the *system* I guess you need to find a better system. Personally, I was happy with Rogue Trader, but if you are not, maybe it's just not the right system for you.
My answer is for my experience with space battles not sea. Space battles in most games I have run tend to have terrible rules that bear little relation to how things move in space or the vast distances and ridiculous speeds. Space battles seem to me to be games of chess, with ships dancing around each other trying to get a line of fire on the enemy while avoiding having the same occur to them. As the point that a large lance weapon or broadside can be brought to bear the game is often over. Boarding in space is more fun as you have to match velocity to dock/storm the vessel or have some kind of teleporter or boarding shuttles. To keep this fluid I tend to bin most movement rules(most of the rules) in the system. And take speed as the change in velocity a ship can affect. Also rotating on the spot in space takes virtually no effort, but changing direction should be difficult. I take acceleration/speed to be in mm so a speed of 6 is 6mm/turn/turn on the table, as after a few turns of combat you can be covering large distances. So if travelling in a straight line you cover 6mm in first turn 12mm in second, 18 in third etc. So you can go very "fast" but stopping or turning becomes more difficult the faster you go. I clear as large a table as possible. Battle start far apart, space is big and I like this to be represented. I also give players 60 seconds to plan their next move; so if flows quickly. If they don't give me written instructions at the 60s mark then they continue to do what they did last turn. Think of it like a bridge on a ship where the command staff discuss tactics and plan and then pass notes to the helmsman and gunnery staff. I also have to have written down what I am going to do with the NPC ships before I look at their notes. Often for enemy ships I have a plan and contingencies and follow them so I as GM can't be accused of cheating. I find the dancing is the fun, there are very few dice roles unless you want to overdirve the engines or jury rig your ship in some silly way. The game flows as the ships close or circle each other. The roles are only needed for targeting, firing and damage. I don't know if this is what you were looking for but my players really enjoyed their space battles when run this way. Try it, see what works and what doesn't for you and tweak as needed.
90,984
I'm about to start a campaign using MgT 2e and I have tons of GT material but I've read over and over again how **Behind the Claw** (for GT) differs from **OTU**. I'm not interested on moving rules from GURPS to MgT 2e, but information, so I just want to know which are the points where **GT** background is different from **OTU** (beyond the Dulinor issues). Bear in mind that I intend to play the *Golden Age* (1105-) or just after the *Fifth Frontier War*.
2016/11/29
[ "https://rpg.stackexchange.com/questions/90984", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/7885/" ]
As a Rogue Trader RPG veteran, I understand your problem. RT is trying to combine two distinct gaming experiences; RPG’s and wargaming. In wargaming, the pleasure is derived from fighting the battles according to the rules with the players commanding either units or parts of the battlefield. In RPG’s, the players play their characters. It’s the combination that fails IMO. Our solution was to throw away the minutiae of ship fighting and make it a more of a RPG session. So instead of mapping out the manoeuvres, broadsides etc., change it into a story in which the players have certain parts to play. And use the crew’s rating, not the players for the ship’s rolls. Players can give a bonus but it makes no sense that for example a single player’s gunnery rating works for a ship of 100,000 crew…. So describe noticing the enemy ship on the scanners (perhaps insert a scene where the scanners go on the fritz and the tech-priest has to fix it), manoeuvring the ship into an advantageous combat position (insert scene where a rudder fails, the engines go off-line, zombies come crawling out of the ventilation ducts, the crew needs a hearty speech etc.), then describe the first salvoes and roll for damage. Describe the effect of damage on your ship and then let the players effect repairs or work around the issues. In short, eliminate tactical rounds, just play the enemy ship intelligently, and throw in scenes/challenges for the players aboard their own ship. Space combat takes forever so there is enough time to solve (small) issues before the next broadside arrives. The entire encounter should be tense and nerve-wracking and things are always breaking down at the worst moment. The players should be running around fixing things or getting the crew to work at maximum efficiency. That also offers them the chance to use their skills instead of just moving the ship and firing every round.
My answer is for my experience with space battles not sea. Space battles in most games I have run tend to have terrible rules that bear little relation to how things move in space or the vast distances and ridiculous speeds. Space battles seem to me to be games of chess, with ships dancing around each other trying to get a line of fire on the enemy while avoiding having the same occur to them. As the point that a large lance weapon or broadside can be brought to bear the game is often over. Boarding in space is more fun as you have to match velocity to dock/storm the vessel or have some kind of teleporter or boarding shuttles. To keep this fluid I tend to bin most movement rules(most of the rules) in the system. And take speed as the change in velocity a ship can affect. Also rotating on the spot in space takes virtually no effort, but changing direction should be difficult. I take acceleration/speed to be in mm so a speed of 6 is 6mm/turn/turn on the table, as after a few turns of combat you can be covering large distances. So if travelling in a straight line you cover 6mm in first turn 12mm in second, 18 in third etc. So you can go very "fast" but stopping or turning becomes more difficult the faster you go. I clear as large a table as possible. Battle start far apart, space is big and I like this to be represented. I also give players 60 seconds to plan their next move; so if flows quickly. If they don't give me written instructions at the 60s mark then they continue to do what they did last turn. Think of it like a bridge on a ship where the command staff discuss tactics and plan and then pass notes to the helmsman and gunnery staff. I also have to have written down what I am going to do with the NPC ships before I look at their notes. Often for enemy ships I have a plan and contingencies and follow them so I as GM can't be accused of cheating. I find the dancing is the fun, there are very few dice roles unless you want to overdirve the engines or jury rig your ship in some silly way. The game flows as the ships close or circle each other. The roles are only needed for targeting, firing and damage. I don't know if this is what you were looking for but my players really enjoyed their space battles when run this way. Try it, see what works and what doesn't for you and tweak as needed.
90,984
I'm about to start a campaign using MgT 2e and I have tons of GT material but I've read over and over again how **Behind the Claw** (for GT) differs from **OTU**. I'm not interested on moving rules from GURPS to MgT 2e, but information, so I just want to know which are the points where **GT** background is different from **OTU** (beyond the Dulinor issues). Bear in mind that I intend to play the *Golden Age* (1105-) or just after the *Fifth Frontier War*.
2016/11/29
[ "https://rpg.stackexchange.com/questions/90984", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/7885/" ]
As a Rogue Trader RPG veteran, I understand your problem. RT is trying to combine two distinct gaming experiences; RPG’s and wargaming. In wargaming, the pleasure is derived from fighting the battles according to the rules with the players commanding either units or parts of the battlefield. In RPG’s, the players play their characters. It’s the combination that fails IMO. Our solution was to throw away the minutiae of ship fighting and make it a more of a RPG session. So instead of mapping out the manoeuvres, broadsides etc., change it into a story in which the players have certain parts to play. And use the crew’s rating, not the players for the ship’s rolls. Players can give a bonus but it makes no sense that for example a single player’s gunnery rating works for a ship of 100,000 crew…. So describe noticing the enemy ship on the scanners (perhaps insert a scene where the scanners go on the fritz and the tech-priest has to fix it), manoeuvring the ship into an advantageous combat position (insert scene where a rudder fails, the engines go off-line, zombies come crawling out of the ventilation ducts, the crew needs a hearty speech etc.), then describe the first salvoes and roll for damage. Describe the effect of damage on your ship and then let the players effect repairs or work around the issues. In short, eliminate tactical rounds, just play the enemy ship intelligently, and throw in scenes/challenges for the players aboard their own ship. Space combat takes forever so there is enough time to solve (small) issues before the next broadside arrives. The entire encounter should be tense and nerve-wracking and things are always breaking down at the worst moment. The players should be running around fixing things or getting the crew to work at maximum efficiency. That also offers them the chance to use their skills instead of just moving the ship and firing every round.
What I found in sea or space battles is that players have no clue what ships look like. No matter how popular you think the ships are, some of your players will not be able to visualize them in the detail you expect. Take for example a [three master](https://www.google.de/search?q=three+master&tbm=isch&tbo=u&source=univ&sa=X&ved=0ahUKEwi4o6uVoM7QAhXkDZoKHWPRCZ8QsAQILA&biw=1433&bih=760). If the DM says something like "after the smoke of your broadside clears, you see the enemy ship has sustained heavy damage, it's foremast broken and hanging over the side", expect players to not be able to accurately describe the scene, no matter how many popular movies you have seen and you *think* they have seen. And it gets even worse with space battles, with all kind of popular fiction depicting ships differently. Make sure you have pictures or props of the ships or ideally, both. Being able to picture the scene, even if the pictures are given, is a huge boost in playability. Prepare in advance as a DM, so you have pictures of possible encounters, possible damage and other outcomes (beaches, asteroids, whatever). Rogue Trader and 40K for example has a very distinct style and that style is a big part of how it *feels*. Fighting an Ork dreadnought or a sleek Eldar frigate *feels* completely different even if you are rolling the same dice. There's pictures of both all over the net. And if you want to have a great evening, maybe you can find some Battlefleet Gothic miniatures to put in the middle of the table. Now if you and your players are unhappy with the *system* I guess you need to find a better system. Personally, I was happy with Rogue Trader, but if you are not, maybe it's just not the right system for you.
7,260,278
Good day, i was having a little trouble with the following code below and i got a solution from a ticked answer in this link. I would like to know why. Note: i had a similar type of layout as in the question, but with one TextView only. [solution link here](https://stackoverflow.com/questions/6054773/classcastexception-in-my-application) my code below: ``` public void onItemClick(AdapterView<?> av, View v, int position, long id) { blueadapter.cancelDiscovery(); String info = ((TextView) v).getText().toString(); //classcastException here String Bluetooth_address = info.substring(info.length()-17); } ``` so from his solution, if i change this to this ``` String info = ((TextView) v.findViewById(R.id.search_device_id)).getText().toString(); ``` it solves my ClassCastException problem. Now please can someone kindly explain to me or point me to the right direction, what he meant by in the answer **"You receive the whole LinearLayout as the parameter v. You should try v.findViewById() and then use this textview."** its nice it solves my problem, but i would like to understand why i had to do that?.. i have dealt with ListViews before, but i have not come across this, so its kind of strange for me. Thank you.
2011/08/31
[ "https://Stackoverflow.com/questions/7260278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/316843/" ]
According to the exception, you're calling this on a string, which doesn't know that method. You need to call it on wherever your Barby::Barcode instance is. According to the documentation "Bookland" is a special case of "pure" EAN-13 data. So, maybe doing something like ``` bc = Barby::EAN13.new(productidentifier_idvalue) bc.valid? ``` Should get you closer to your aim
The valid? method exists only on objects which are instances of the [Barcode class](http://barby.rubyforge.org/rdoc/classes/Barby/Barcode.html) You're calling this method on a String.
7,260,278
Good day, i was having a little trouble with the following code below and i got a solution from a ticked answer in this link. I would like to know why. Note: i had a similar type of layout as in the question, but with one TextView only. [solution link here](https://stackoverflow.com/questions/6054773/classcastexception-in-my-application) my code below: ``` public void onItemClick(AdapterView<?> av, View v, int position, long id) { blueadapter.cancelDiscovery(); String info = ((TextView) v).getText().toString(); //classcastException here String Bluetooth_address = info.substring(info.length()-17); } ``` so from his solution, if i change this to this ``` String info = ((TextView) v.findViewById(R.id.search_device_id)).getText().toString(); ``` it solves my ClassCastException problem. Now please can someone kindly explain to me or point me to the right direction, what he meant by in the answer **"You receive the whole LinearLayout as the parameter v. You should try v.findViewById() and then use this textview."** its nice it solves my problem, but i would like to understand why i had to do that?.. i have dealt with ListViews before, but i have not come across this, so its kind of strange for me. Thank you.
2011/08/31
[ "https://Stackoverflow.com/questions/7260278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/316843/" ]
If you're giving an invalid ISBN here ``` barcode = Barby::Bookland.new("'#{self.productidentifier_idvalue}'") ``` it's no wonder it gives you the `data not valid` error. Check the value of `self.productidentifier_idvalue` and make sure it's 12 digits (the regexp to validate the code can be seen [here](https://github.com/toretore/barby/blob/master/lib/barby/barcode/ean_13.rb#L53)). **Update** Replace `"'#{self.productidentifier_idvalue}'"` with `self.productidentifier_idvalue`. The way you're doing it, the result of your expression is `'123456789012'`, which is two quotes too many. Besides, you don't really need to call `valid?`, it's done in the initializer as you can see [here](https://github.com/toretore/barby/blob/master/lib/barby/barcode/bookland.rb#L15).
According to the exception, you're calling this on a string, which doesn't know that method. You need to call it on wherever your Barby::Barcode instance is. According to the documentation "Bookland" is a special case of "pure" EAN-13 data. So, maybe doing something like ``` bc = Barby::EAN13.new(productidentifier_idvalue) bc.valid? ``` Should get you closer to your aim
7,260,278
Good day, i was having a little trouble with the following code below and i got a solution from a ticked answer in this link. I would like to know why. Note: i had a similar type of layout as in the question, but with one TextView only. [solution link here](https://stackoverflow.com/questions/6054773/classcastexception-in-my-application) my code below: ``` public void onItemClick(AdapterView<?> av, View v, int position, long id) { blueadapter.cancelDiscovery(); String info = ((TextView) v).getText().toString(); //classcastException here String Bluetooth_address = info.substring(info.length()-17); } ``` so from his solution, if i change this to this ``` String info = ((TextView) v.findViewById(R.id.search_device_id)).getText().toString(); ``` it solves my ClassCastException problem. Now please can someone kindly explain to me or point me to the right direction, what he meant by in the answer **"You receive the whole LinearLayout as the parameter v. You should try v.findViewById() and then use this textview."** its nice it solves my problem, but i would like to understand why i had to do that?.. i have dealt with ListViews before, but i have not come across this, so its kind of strange for me. Thank you.
2011/08/31
[ "https://Stackoverflow.com/questions/7260278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/316843/" ]
If you're giving an invalid ISBN here ``` barcode = Barby::Bookland.new("'#{self.productidentifier_idvalue}'") ``` it's no wonder it gives you the `data not valid` error. Check the value of `self.productidentifier_idvalue` and make sure it's 12 digits (the regexp to validate the code can be seen [here](https://github.com/toretore/barby/blob/master/lib/barby/barcode/ean_13.rb#L53)). **Update** Replace `"'#{self.productidentifier_idvalue}'"` with `self.productidentifier_idvalue`. The way you're doing it, the result of your expression is `'123456789012'`, which is two quotes too many. Besides, you don't really need to call `valid?`, it's done in the initializer as you can see [here](https://github.com/toretore/barby/blob/master/lib/barby/barcode/bookland.rb#L15).
The valid? method exists only on objects which are instances of the [Barcode class](http://barby.rubyforge.org/rdoc/classes/Barby/Barcode.html) You're calling this method on a String.
67,657,481
I have a sheet called [Calendar] with a calendar for each month of the year, this sheet has conditional formatting to colour each date depending on holidays/capacity for that month. These dates are also set in the [Calendar] sheet. I have a second sheet for each month (eg. [Jan 2022], this sheet has lots of information about what's happening that month. I'd like to have that months calendar from [Calendar] show up on [Jan 2022] keeping all of the conditional formatting. Is this possible? (I realise that I could re-do all of the conditional formatting on the Monthly sheets based on the info in [Calendar] using `Calendar!Range` in the conditions but there are 45 different sets of conditional formatting as well as a script which changes the border colour of certain cells if they match other conditions on the sheet. I was wondering if there was an easier way)
2021/05/23
[ "https://Stackoverflow.com/questions/67657481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15753969/" ]
There is current a feature request to set a ranges border color and style. If you want that sort of feature you may wish to go to this issue and star the request. [36756953](https://issuetracker.google.com/issues/36756953)
Ok, After a LOT of messing about, I've found a few possible solutions that worked. Firstly, you can copy/paste the area you'd like to 'show' which will also copy the formatting over, sadly this formatting doesn't link to the correct page anymore (if, as in my case, you're not also copying the information that the conditions rely on). The easiest way I found was to copy the fields that the conditions rely on into the same fields on the sheet you're copying to (eg. in the cell Jan!X10 put the code `=Calendar!X10` and do the same for X10:Z20 for example). This means that when [Calendar] is updated, the conditional formatting on [Jan] changes to represent this. [one last tip, after putting the code in the matching cells, you can then either hide these cells OR copy/paste these cells to somewhere that works better in your sheet and the references in the conditional formatting will update] The other way I found to do it is to change the [Jan] conditional formatting to reference the [Calendar] page, sadly, you cant simply change `=A1>X10` to `=A1>Calendar!X10`, you need to change it to `=A1>INDIRECT("'Calendar'!X10")` as you cant directly use a cross-sheet reference in Conditional Formatting (for some reason). I hope this helps anyone who is having the same problems I was having. Happy coding :)
6,660,172
I need to specify a Index hint for my HQL ``` Query.setComment() ``` method is of no use as it is appending the hint before the select clause, though this can be achieved by NativeSQL but I just wanted to check is there a way we can achieve this in HQL rather then SQL
2011/07/12
[ "https://Stackoverflow.com/questions/6660172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/537445/" ]
Well, skype uses propriatery protocols, and there are some efforts of reversing them: <http://en.wikipedia.org/wiki/Skype_protocol>
**Update** It is now possible to connect through “Skype for Web”, allowing you to just use your browser to connect to the (clunky) web client. Way better: [a recent plugin for Pidgin](https://github.com/EionRobb/skype4pidgin/tree/master/skypeweb) lets you use it directly through Pidgin, effectively adding true support for Skype in Pidgin.
16,590,765
I am looking to create a **mardown directive** (restrict A) which would make me able to use same recipient for **ng-view**. So I would basically load only .md files in views and apply my function on its content each time ng-view change. So : **index.html** ``` <div markdown ng-view></div> ``` with two views containing, let say, **view1.md** ``` #That should be h1 ``` and **view2.md** ``` ##That should be h2, no ? ``` My actual code is ``` 'use strict'; angular.module('btford.markdown', []). directive('markdown', function () { var converter = new Showdown.converter(); return { restrict: 'A', link: function (scope, element, attrs) { scope.$watch(element.html(), function(value) { var htmlText = converter.makeHtml(element.html()); element.html(htmlText); }); var htmlText = converter.makeHtml(element.text()); element.html(htmlText); } } }); ```
2013/05/16
[ "https://Stackoverflow.com/questions/16590765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2390493/" ]
The first param of watch can be a function, return any value you want including your $element.html(). You can even do a combination of data ``` $scope.$watch( function() { return $element.attr("abc") + $scope.variable + someinternalvar; }, function(newVal, oldVal) { doTheStuff(); } ); ``` Obviously the more intense the data you put in here the slower your watches will be. Use caution. -- FYI You should clean up your watchers, create an array and push the results of $scope.$watch into that array. Then on the $destroy message remove them. Also remember to unbind events as they will cause eventual performance issues as scopes are created & destroyed. ``` $document.bind('click', clickMe); $(window).on("resize", winResize); var watches = [] watches.push($scope.$watch("thing", function() { Thing(); })); $scope.$on("$destroy", function () { for (var i in watches) watches[i](); $document.unbind('click', clickMe); $(window).off("resize", winResize); }); ``` -- EDIT 2016-07-14 Just to add, cleaning up scope watchers is not needed as they are already processed internally, however rootScope, parent, etc. you should absolutely cleanup.
You can only watch variables on your scope. ``` scope.foo = 'bar'; scope.$watch('foo', function(newValue) { // Code to execute here }); ``` If you want to monitor the changes of DOM elements you need to do this on your own.
16,590,765
I am looking to create a **mardown directive** (restrict A) which would make me able to use same recipient for **ng-view**. So I would basically load only .md files in views and apply my function on its content each time ng-view change. So : **index.html** ``` <div markdown ng-view></div> ``` with two views containing, let say, **view1.md** ``` #That should be h1 ``` and **view2.md** ``` ##That should be h2, no ? ``` My actual code is ``` 'use strict'; angular.module('btford.markdown', []). directive('markdown', function () { var converter = new Showdown.converter(); return { restrict: 'A', link: function (scope, element, attrs) { scope.$watch(element.html(), function(value) { var htmlText = converter.makeHtml(element.html()); element.html(htmlText); }); var htmlText = converter.makeHtml(element.text()); element.html(htmlText); } } }); ```
2013/05/16
[ "https://Stackoverflow.com/questions/16590765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2390493/" ]
It may be cleaner for you to use the `$stateChangeSuccess` event inside your directive rather than setting your own $watch. Try adding a callback function to the `$stateChangeSuccess` event, this should trickle down to the scope of your directive. ``` 'use strict'; angular.module('btford.markdown', []). directive('markdown', function () { var converter = new Showdown.converter(); return { restrict: 'A', link: function (scope, element, attrs) { // When the state is change to, or reloaded... scope.$on('$stateChangeSuccess', function () { var htmlText = converter.makeHtml(element.text()); element.html(htmlText); }); } } }); ```
You can only watch variables on your scope. ``` scope.foo = 'bar'; scope.$watch('foo', function(newValue) { // Code to execute here }); ``` If you want to monitor the changes of DOM elements you need to do this on your own.
16,590,765
I am looking to create a **mardown directive** (restrict A) which would make me able to use same recipient for **ng-view**. So I would basically load only .md files in views and apply my function on its content each time ng-view change. So : **index.html** ``` <div markdown ng-view></div> ``` with two views containing, let say, **view1.md** ``` #That should be h1 ``` and **view2.md** ``` ##That should be h2, no ? ``` My actual code is ``` 'use strict'; angular.module('btford.markdown', []). directive('markdown', function () { var converter = new Showdown.converter(); return { restrict: 'A', link: function (scope, element, attrs) { scope.$watch(element.html(), function(value) { var htmlText = converter.makeHtml(element.html()); element.html(htmlText); }); var htmlText = converter.makeHtml(element.text()); element.html(htmlText); } } }); ```
2013/05/16
[ "https://Stackoverflow.com/questions/16590765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2390493/" ]
The first param of watch can be a function, return any value you want including your $element.html(). You can even do a combination of data ``` $scope.$watch( function() { return $element.attr("abc") + $scope.variable + someinternalvar; }, function(newVal, oldVal) { doTheStuff(); } ); ``` Obviously the more intense the data you put in here the slower your watches will be. Use caution. -- FYI You should clean up your watchers, create an array and push the results of $scope.$watch into that array. Then on the $destroy message remove them. Also remember to unbind events as they will cause eventual performance issues as scopes are created & destroyed. ``` $document.bind('click', clickMe); $(window).on("resize", winResize); var watches = [] watches.push($scope.$watch("thing", function() { Thing(); })); $scope.$on("$destroy", function () { for (var i in watches) watches[i](); $document.unbind('click', clickMe); $(window).off("resize", winResize); }); ``` -- EDIT 2016-07-14 Just to add, cleaning up scope watchers is not needed as they are already processed internally, however rootScope, parent, etc. you should absolutely cleanup.
It may be cleaner for you to use the `$stateChangeSuccess` event inside your directive rather than setting your own $watch. Try adding a callback function to the `$stateChangeSuccess` event, this should trickle down to the scope of your directive. ``` 'use strict'; angular.module('btford.markdown', []). directive('markdown', function () { var converter = new Showdown.converter(); return { restrict: 'A', link: function (scope, element, attrs) { // When the state is change to, or reloaded... scope.$on('$stateChangeSuccess', function () { var htmlText = converter.makeHtml(element.text()); element.html(htmlText); }); } } }); ```
64,590
This question makes absolutely no sense to me and it is driving me crazy that I cannot find a solution. [![enter image description here](https://i.stack.imgur.com/iZSzh.png)](https://i.stack.imgur.com/iZSzh.png)
2018/04/22
[ "https://puzzling.stackexchange.com/questions/64590", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/48438/" ]
it's > > green, blank, blank. > > > because... calling the cells A,B,C,D,E,F and examples 1,2,3,4,5 1-2 deonstrates that B is the opposite of D It can also be deduced by looking at 1,2,3,4,5 that A,B,C are not correlated with each other then it can be seen that A always matches F and C always matces E leaving only one of the patterns offered as the answer. 3 and 4 identical hints that there is no vertical sequence 5 being half filled suggests that the D,E,F are can be determined by A,B,C it took me a lot longer to deduce this than the time I allow to answer most IQ test questions.
Extracting a pattern from so little data will always be ambiguous. My guess would be > > Green, blank, blank > > > because if we assume there is an independent operation for deducing the fifth element in a column from the other four, we have existing samples for the fifth and sixth column, and only one answer choice that fits both.
64,590
This question makes absolutely no sense to me and it is driving me crazy that I cannot find a solution. [![enter image description here](https://i.stack.imgur.com/iZSzh.png)](https://i.stack.imgur.com/iZSzh.png)
2018/04/22
[ "https://puzzling.stackexchange.com/questions/64590", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/48438/" ]
it's > > green, blank, blank. > > > because... calling the cells A,B,C,D,E,F and examples 1,2,3,4,5 1-2 deonstrates that B is the opposite of D It can also be deduced by looking at 1,2,3,4,5 that A,B,C are not correlated with each other then it can be seen that A always matches F and C always matces E leaving only one of the patterns offered as the answer. 3 and 4 identical hints that there is no vertical sequence 5 being half filled suggests that the D,E,F are can be determined by A,B,C it took me a lot longer to deduce this than the time I allow to answer most IQ test questions.
> > I notice that there are 3 shaded (blue) blocks and 3 non-shaded blocks per row. > > From this alone, I can tell that the likely solution is(final row): > > u = un-shaded, s = shaded > > **Given**: u, u, u; > > **Solved**: s, s, s; > > **Final**: u, u, u, s, s, s > > > **[INCORRECT]**
64,590
This question makes absolutely no sense to me and it is driving me crazy that I cannot find a solution. [![enter image description here](https://i.stack.imgur.com/iZSzh.png)](https://i.stack.imgur.com/iZSzh.png)
2018/04/22
[ "https://puzzling.stackexchange.com/questions/64590", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/48438/" ]
it's > > green, blank, blank. > > > because... calling the cells A,B,C,D,E,F and examples 1,2,3,4,5 1-2 deonstrates that B is the opposite of D It can also be deduced by looking at 1,2,3,4,5 that A,B,C are not correlated with each other then it can be seen that A always matches F and C always matces E leaving only one of the patterns offered as the answer. 3 and 4 identical hints that there is no vertical sequence 5 being half filled suggests that the D,E,F are can be determined by A,B,C it took me a lot longer to deduce this than the time I allow to answer most IQ test questions.
If we treat the blocks as pixels which move on a small screen, and roll over from one side to the other, as they go off the edge of the screen, then we get the answer: > > blank,green,green > > > as we can see fairly quickly that the two pixels on the left each move left one space to the left, and then wrap around to the right, and the pixel on the left moves 0, then 1, then 2, then 3 spaces. Not sure if this is how to interpret this question (I have noticed some IQ questions are just poorly designed), but This is at least a logically consistant answer
64,590
This question makes absolutely no sense to me and it is driving me crazy that I cannot find a solution. [![enter image description here](https://i.stack.imgur.com/iZSzh.png)](https://i.stack.imgur.com/iZSzh.png)
2018/04/22
[ "https://puzzling.stackexchange.com/questions/64590", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/48438/" ]
Extracting a pattern from so little data will always be ambiguous. My guess would be > > Green, blank, blank > > > because if we assume there is an independent operation for deducing the fifth element in a column from the other four, we have existing samples for the fifth and sixth column, and only one answer choice that fits both.
> > I notice that there are 3 shaded (blue) blocks and 3 non-shaded blocks per row. > > From this alone, I can tell that the likely solution is(final row): > > u = un-shaded, s = shaded > > **Given**: u, u, u; > > **Solved**: s, s, s; > > **Final**: u, u, u, s, s, s > > > **[INCORRECT]**
64,590
This question makes absolutely no sense to me and it is driving me crazy that I cannot find a solution. [![enter image description here](https://i.stack.imgur.com/iZSzh.png)](https://i.stack.imgur.com/iZSzh.png)
2018/04/22
[ "https://puzzling.stackexchange.com/questions/64590", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/48438/" ]
Extracting a pattern from so little data will always be ambiguous. My guess would be > > Green, blank, blank > > > because if we assume there is an independent operation for deducing the fifth element in a column from the other four, we have existing samples for the fifth and sixth column, and only one answer choice that fits both.
If we treat the blocks as pixels which move on a small screen, and roll over from one side to the other, as they go off the edge of the screen, then we get the answer: > > blank,green,green > > > as we can see fairly quickly that the two pixels on the left each move left one space to the left, and then wrap around to the right, and the pixel on the left moves 0, then 1, then 2, then 3 spaces. Not sure if this is how to interpret this question (I have noticed some IQ questions are just poorly designed), but This is at least a logically consistant answer
593,110
So "half" belongs to a special class of words known as "predeterminers", those that can occur before determiners: > > Half a century > > > > > Half the people in this company can't speak a word of English > > > In English though, there are no indefinite (article-type) determiners in the plural: there are no plural equivalents to "a/an". This means that "half", as a predeterminer, does not have any determiner to "pre". > > Half Americans disapprove of the President (?) > > > > > Half Japanese women prefer men who can cook (?) > > > Are these two last sentences incorrect in any way? Or could they sound awkward or unnatural? Should I use "half of" instead?
2022/08/06
[ "https://english.stackexchange.com/questions/593110", "https://english.stackexchange.com", "https://english.stackexchange.com/users/120439/" ]
I had to go to the third page of my search results but [ELT Concourse](https://www.eltconcourse.com/training/inservice/lexicogrammar/pre-_post-determiners.html) claims precisely that: the contextual range for *half* is more restricted than *all* and *both*, both of which are also predeterminers. In short, unlike *all* and *both*, there **must** be a determiner after *half*. Therefore, such phrase as "half Americans" is incorrect, and must be changed to "half of Americans", for example. Here's an excerpt from the source: > > With plural count nouns we can use all three pre-determiners but *half* cannot be used with the zero article > > > For example: > > > * half those oranges are rotten > * both the children came > * all the men went home and stayed there > * all lions are unpredictable > * both (the) dogs are friendly > > > but not with the zero article: > > > * \*half people arrived > * \*half trains are always late in my country > > >
Just confirming a comment. Both of the sentences are acceptable, but *mean* different things. > > Half of Japanese women prefer men who can cook. > > > This means that in a given population, we are speaking of 50% or so. > > Half Japanese women prefer men who can cook. > > > This would imply the women in question are half Japanese. See [a CNN article on Japan's hafu](https://www.cnn.com/2020/09/22/asia/japan-mixed-roots-hafu-dst-hnk-intl/index.html): > > The Japanese word "hafu" -- or "half" in English -- refers to people who are ethnically half Japanese, and is now used more for multiethnic people in general in Japan. > > >
593,110
So "half" belongs to a special class of words known as "predeterminers", those that can occur before determiners: > > Half a century > > > > > Half the people in this company can't speak a word of English > > > In English though, there are no indefinite (article-type) determiners in the plural: there are no plural equivalents to "a/an". This means that "half", as a predeterminer, does not have any determiner to "pre". > > Half Americans disapprove of the President (?) > > > > > Half Japanese women prefer men who can cook (?) > > > Are these two last sentences incorrect in any way? Or could they sound awkward or unnatural? Should I use "half of" instead?
2022/08/06
[ "https://english.stackexchange.com/questions/593110", "https://english.stackexchange.com", "https://english.stackexchange.com/users/120439/" ]
After reading your question, I didn't quite understand what you're asking. Only after reading your own answer did I understand what you're asking and, more importantly, why you're asking what you're asking. To quote your own answer: > > the contextual range for *half* is more restricted than *all* and *both*, both of which are also predeterminers. In short, unlike *all* and *both*, there **must** be a determiner after *half*. > > > So, you're comparing *half* with *all* and *both*, which is simply comparing apples with oranges. Firstly, *half* is a fraction, just as *quarter*, *third*, and *fifth* are. Secondly, fractions can only function as predeterminers and cannot function as determiners, which means that they can come only before a determiner. So it's only natural that you can't say things like: > > \**Half Americans disapprove of the President.* > > > Because you don't have any determiner right after the predeterminer! In contrast, *both* and *all* can function as determiners as well as predeterminers. To quote the examples of your own answer: > > * half those oranges are rotten [predeterminer] > * *both* the children came [predeterminer] > * *all* the men went home and stayed there [predeterminer] > * *all* lions are unpredictable [determiner] > * *both* the dogs are friendly [predeterminer] > * *both* dogs are friendly [determiner] > * \**half* people arrived [predeterminer] > * \**half* trains are always late in my country [predeterminer] > > > So you just have to know that *half* is a fraction whereas *all* and *both* are not, and therefore that *half* functions differently from *all* and *both*.
Just confirming a comment. Both of the sentences are acceptable, but *mean* different things. > > Half of Japanese women prefer men who can cook. > > > This means that in a given population, we are speaking of 50% or so. > > Half Japanese women prefer men who can cook. > > > This would imply the women in question are half Japanese. See [a CNN article on Japan's hafu](https://www.cnn.com/2020/09/22/asia/japan-mixed-roots-hafu-dst-hnk-intl/index.html): > > The Japanese word "hafu" -- or "half" in English -- refers to people who are ethnically half Japanese, and is now used more for multiethnic people in general in Japan. > > >
593,110
So "half" belongs to a special class of words known as "predeterminers", those that can occur before determiners: > > Half a century > > > > > Half the people in this company can't speak a word of English > > > In English though, there are no indefinite (article-type) determiners in the plural: there are no plural equivalents to "a/an". This means that "half", as a predeterminer, does not have any determiner to "pre". > > Half Americans disapprove of the President (?) > > > > > Half Japanese women prefer men who can cook (?) > > > Are these two last sentences incorrect in any way? Or could they sound awkward or unnatural? Should I use "half of" instead?
2022/08/06
[ "https://english.stackexchange.com/questions/593110", "https://english.stackexchange.com", "https://english.stackexchange.com/users/120439/" ]
After reading your question, I didn't quite understand what you're asking. Only after reading your own answer did I understand what you're asking and, more importantly, why you're asking what you're asking. To quote your own answer: > > the contextual range for *half* is more restricted than *all* and *both*, both of which are also predeterminers. In short, unlike *all* and *both*, there **must** be a determiner after *half*. > > > So, you're comparing *half* with *all* and *both*, which is simply comparing apples with oranges. Firstly, *half* is a fraction, just as *quarter*, *third*, and *fifth* are. Secondly, fractions can only function as predeterminers and cannot function as determiners, which means that they can come only before a determiner. So it's only natural that you can't say things like: > > \**Half Americans disapprove of the President.* > > > Because you don't have any determiner right after the predeterminer! In contrast, *both* and *all* can function as determiners as well as predeterminers. To quote the examples of your own answer: > > * half those oranges are rotten [predeterminer] > * *both* the children came [predeterminer] > * *all* the men went home and stayed there [predeterminer] > * *all* lions are unpredictable [determiner] > * *both* the dogs are friendly [predeterminer] > * *both* dogs are friendly [determiner] > * \**half* people arrived [predeterminer] > * \**half* trains are always late in my country [predeterminer] > > > So you just have to know that *half* is a fraction whereas *all* and *both* are not, and therefore that *half* functions differently from *all* and *both*.
I had to go to the third page of my search results but [ELT Concourse](https://www.eltconcourse.com/training/inservice/lexicogrammar/pre-_post-determiners.html) claims precisely that: the contextual range for *half* is more restricted than *all* and *both*, both of which are also predeterminers. In short, unlike *all* and *both*, there **must** be a determiner after *half*. Therefore, such phrase as "half Americans" is incorrect, and must be changed to "half of Americans", for example. Here's an excerpt from the source: > > With plural count nouns we can use all three pre-determiners but *half* cannot be used with the zero article > > > For example: > > > * half those oranges are rotten > * both the children came > * all the men went home and stayed there > * all lions are unpredictable > * both (the) dogs are friendly > > > but not with the zero article: > > > * \*half people arrived > * \*half trains are always late in my country > > >
7,321,698
I have used DATEDIFF function but since it requires yyyy/mm/dd this code is giving wrong value ,because i have stored date from date time picker in this formate day,month,dd,yyyy ``` private void button3_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); DataSet ds1 = new DataSet(); DataSet ds2 = new DataSet(); DBHandling db = new DBHandling(); db.GetDataset(" select JoiningDate from Emp where name = '" + textBox2.Text + "'", ref ds); db.GetDataset(" select LeavingDate from AddDate where name = '" + textBox2.Text + "'", ref ds1); string date1, date2; date1 = ds.Tables[0].Rows[0][0].ToString(); date2 = ds1.Tables[0].Rows[0][0].ToString(); db.GetDataset("select DATEDIFF(day,2008/1/15,2008/1/12) ", ref ds2); textBox5.Text = ds2.Tables[0].Rows[0][0].ToString(); } ``` so how should i do this so that i will gate right Difference between 2 dates i.e number of days between 2 dates,thanks in advance
2011/09/06
[ "https://Stackoverflow.com/questions/7321698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/895965/" ]
Some time ago I was also studying SHA-256 and created pure-python class that implements this hash. If I remember correctly, mostly I've taken algorithm from Wikipedia [SHA-256 Pseudocode](https://en.wikipedia.org/wiki/SHA-2#Pseudocode) and partially from some open-source projects. Algorithm doesn't import any (even standard) modules. Of cause it is much slower than `hashlib`'s variant and only meant for studying. If you just run the script it executes 1000 tests comparing `hashlib`'s and my variants. Only testing function imports some modules, algorithm's class itself doesn't need any modules. Interface is same as in hashlib's sha256 class. See `test()` function for examples of usage. [Try it online!](https://tio.run/##lVZNc9s2EL37V6CHVmRtKwAIgKQnyfTk6aW9pDdV1QAgYDEWJY9IT2VPp3/dXSwoiZRlN@FF0AL7dvftB/Dw1C036@zlxa5025IvS82lurkg8N235BOZ4TJ8dCd4obkviytY5yzLhShZWBtpqTfWh7UrjayMllcDvayUynJpwr4sPWPMo17JM19wLcJaG2alq0Z6VUFzraM9xotMGop6XGSskMYhnqQ2r2w21Mu5cbLKEbeglTPM49nSVJYqnYe1ZaXxDM4M9JwojSot2nDeOJEXKqyph9OVVdE2tZpZO9TjlSu5VRi/0LkohNbomzVUgyLypYC4otJDvbLInGSSY/xFxqxSFfJJacZzi3EbL8vc23yoZ5Wj1Pgs7FdS5yUTGBNVVqtMov9M8JKXaqTHc5NTXUiMwzHDWYY2RAXeVx79lFkGlLERn0pSnWdSxDiUptpgLgtmuS155JbnnNtilD/NjXeFZjE@ppUSqGe5MAW4gutcWcn0yF7FALRgJcanypIqjra9oC6T0X8GidQUMAZ6rNTCMoZ5Yi4DZIrxcUhJnguMLxOGGmtO6pNZag3yKVxVaC1i/kxprRaYV1Vwp7wf15kooH4dxp8XWqos1kAhbJEXLNaftTnl4Mcw79Q47z3a0EJC2hzyAtJSZz7Wp8pZXnge9eYX@LM87UjIRemUQg1jVK5dZCeDEvFZHitLCu9lNqo8yaiTPPexK6hURYHsMF9kValjpxpHLaRi5MFvGQcX6O62/6K0cp4sFvW67haLpHUrwG3g2O@btUtvDmbDxrRZuXVAGEvNowehmUzG4nsQxkU7u5mP95b7veXrPV8HG7d61brDRu3Bp7ol602Hjh39Oqg9PlS6c0mTxqh@aTvd1bZxMCGrQ5wPukpCEIPAmqoGcxjZT4H828MOiO664CmqkI8fSZZOu83CPHWuTaA4J6a@m6SH8wAe@ZGSXCNucBt@PhKpiIN4CGNl3DoobV33uF0De3/CtJuQS1xRWP28x7vsHXkvru1mm@yuyNMgrh44SXbk82fYIf8QWEIQCVTBNQjSFAKOV8YUKuM9@EZ/Rfgr8nzGwg5wAP@vuHrG1ROu3sO0y2@CTP7dpQMs1Nw0D1vXtn2x2oH@36HF6BzIU@IonFFyQ5iah8163U39dtP0WbSzGvZqIFnM9wklfrMFEZThVq/vXAKjDjKQ2PSKiLRvpfCdHAujS4n0pDTpvtJDiv4Ga9eESTBF8hDeuR1WYOAHSUgfVN4Ylr2GJTwon4ONO@UAFiQBltExLGwGkva2gbHLEMEliYIc/7OQD7RwqJrwwUCEyQODCG5BGKqQmLsrcuzzN2n7H8oAlo9CAgHLTiWcjwPpwqBDz@Pcgvrt/XuPR3BbjZBBwNiphMsTWwFjiczs7UFt9xSke9F9oBaJHFQQXgugfTeS3IHEjyRhvrqRxIU0VQDYjdMxPFPBGTuS2DCnRxIDEj2S6IDchVA6fj7TmMArEgdOSKRbPzZuG6bvc/2QxHxfkdn5ipin6Znpvewrbwd2n16bDW3fD/j@hhqA7C@HcDEQ8C00a5OST3BRjS3F6TIo2bZ12w4vlf3NAzPgV90uiV5tna6eCIj0qn52FdHrili9xtPG9d5UP0wuzlyRl596J463zL7OwmV5SZo326EfNuD/hw9nxglW137@NTMlYNSFCYaLJMwxls7Ti3MXdDPrga9J0q9@RAvzI8dVfefaDjkeEzzk6O3LF9fhjj1QkaavD0cj8ckw/bqp18nueK2K0RTeBWL6Arkp5mfA4mvhj@2jO71EBraOAS7d7nyMnQ6tMKGMZ0KqvIB3lAWFySnq3mU4PzNhhorQ1vFfeD/cztFxc3C8NwdEXAQHOvwT7dbNw2YbeLUA3kJvQOWtaugZKIVq01wcyiMoHUtEUjpwHIjXWFwIAkTeu3XPZYSZhp@oyWU@SEjozzC6otVpi0@BJOCl0yNPcOt9eWPntJF06DlwH2dt@m3un3fiaDQdNcrXI8yr4OAyO@mW76GG8fKkVvW@qjHu8dQ8v9XHosfsme@k7GELb5RkEuPHeoHp0z5aCy3vH1erpym8OS/q8Ghf68YtFgFislg0ul4vFpNIQSyzi5eX/wA "Python 3 – Try It Online") ``` class Sha256: ks = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, ] hs = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, ] M32 = 0xFFFFFFFF def __init__(self, m = None): self.mlen = 0 self.buf = b'' self.k = self.ks[:] self.h = self.hs[:] self.fin = False if m is not None: self.update(m) @staticmethod def pad(mlen): mdi = mlen & 0x3F length = (mlen << 3).to_bytes(8, 'big') padlen = 55 - mdi if mdi < 56 else 119 - mdi return b'\x80' + b'\x00' * padlen + length @staticmethod def ror(x, y): return ((x >> y) | (x << (32 - y))) & Sha256.M32 @staticmethod def maj(x, y, z): return (x & y) ^ (x & z) ^ (y & z) @staticmethod def ch(x, y, z): return (x & y) ^ ((~x) & z) def compress(self, c): w = [0] * 64 w[0 : 16] = [int.from_bytes(c[i : i + 4], 'big') for i in range(0, len(c), 4)] for i in range(16, 64): s0 = self.ror(w[i - 15], 7) ^ self.ror(w[i - 15], 18) ^ (w[i - 15] >> 3) s1 = self.ror(w[i - 2], 17) ^ self.ror(w[i - 2], 19) ^ (w[i - 2] >> 10) w[i] = (w[i - 16] + s0 + w[i - 7] + s1) & self.M32 a, b, c, d, e, f, g, h = self.h for i in range(64): s0 = self.ror(a, 2) ^ self.ror(a, 13) ^ self.ror(a, 22) t2 = s0 + self.maj(a, b, c) s1 = self.ror(e, 6) ^ self.ror(e, 11) ^ self.ror(e, 25) t1 = h + s1 + self.ch(e, f, g) + self.k[i] + w[i] h = g g = f f = e e = (d + t1) & self.M32 d = c c = b b = a a = (t1 + t2) & self.M32 for i, (x, y) in enumerate(zip(self.h, [a, b, c, d, e, f, g, h])): self.h[i] = (x + y) & self.M32 def update(self, m): if m is None or len(m) == 0: return assert not self.fin, 'Hash already finalized and can not be updated!' self.mlen += len(m) m = self.buf + m for i in range(0, len(m) // 64): self.compress(m[64 * i : 64 * (i + 1)]) self.buf = m[len(m) - (len(m) % 64):] def digest(self): if not self.fin: self.update(self.pad(self.mlen)) self.digest = b''.join(x.to_bytes(4, 'big') for x in self.h[:8]) self.fin = True return self.digest def hexdigest(self): tab = '0123456789abcdef' return ''.join(tab[b >> 4] + tab[b & 0xF] for b in self.digest()) def test(): import secrets, hashlib, random for itest in range(500): data = secrets.token_bytes(random.randrange(257)) a, b = hashlib.sha256(data).hexdigest(), Sha256(data).hexdigest() assert a == b, (a, b) for itest in range(500): a, b = hashlib.sha256(), Sha256() for j in range(random.randrange(10)): data = secrets.token_bytes(random.randrange(129)) a.update(data) b.update(data) a, b = a.hexdigest(), b.hexdigest() assert a == b, (a, b) print('Sha256 tested successfully.') if __name__ == '__main__': test() ```
Translating <http://en.wikipedia.org/wiki/SHA-2#SHA-256_.28a_SHA-2_variant.29_pseudocode> to Python should be straight forward.
7,321,698
I have used DATEDIFF function but since it requires yyyy/mm/dd this code is giving wrong value ,because i have stored date from date time picker in this formate day,month,dd,yyyy ``` private void button3_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); DataSet ds1 = new DataSet(); DataSet ds2 = new DataSet(); DBHandling db = new DBHandling(); db.GetDataset(" select JoiningDate from Emp where name = '" + textBox2.Text + "'", ref ds); db.GetDataset(" select LeavingDate from AddDate where name = '" + textBox2.Text + "'", ref ds1); string date1, date2; date1 = ds.Tables[0].Rows[0][0].ToString(); date2 = ds1.Tables[0].Rows[0][0].ToString(); db.GetDataset("select DATEDIFF(day,2008/1/15,2008/1/12) ", ref ds2); textBox5.Text = ds2.Tables[0].Rows[0][0].ToString(); } ``` so how should i do this so that i will gate right Difference between 2 dates i.e number of days between 2 dates,thanks in advance
2011/09/06
[ "https://Stackoverflow.com/questions/7321698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/895965/" ]
PyPy's source contains a pure-python implementation of SHA-256 [here](https://foss.heptapod.net/pypy/pypy/-/blob/branch/default/lib_pypy/_sha256.py). Poking around in that directory, you'll probably also find pure-python implementations of other standard hashes.
Translating <http://en.wikipedia.org/wiki/SHA-2#SHA-256_.28a_SHA-2_variant.29_pseudocode> to Python should be straight forward.
7,321,698
I have used DATEDIFF function but since it requires yyyy/mm/dd this code is giving wrong value ,because i have stored date from date time picker in this formate day,month,dd,yyyy ``` private void button3_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); DataSet ds1 = new DataSet(); DataSet ds2 = new DataSet(); DBHandling db = new DBHandling(); db.GetDataset(" select JoiningDate from Emp where name = '" + textBox2.Text + "'", ref ds); db.GetDataset(" select LeavingDate from AddDate where name = '" + textBox2.Text + "'", ref ds1); string date1, date2; date1 = ds.Tables[0].Rows[0][0].ToString(); date2 = ds1.Tables[0].Rows[0][0].ToString(); db.GetDataset("select DATEDIFF(day,2008/1/15,2008/1/12) ", ref ds2); textBox5.Text = ds2.Tables[0].Rows[0][0].ToString(); } ``` so how should i do this so that i will gate right Difference between 2 dates i.e number of days between 2 dates,thanks in advance
2011/09/06
[ "https://Stackoverflow.com/questions/7321698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/895965/" ]
Some time ago I was also studying SHA-256 and created pure-python class that implements this hash. If I remember correctly, mostly I've taken algorithm from Wikipedia [SHA-256 Pseudocode](https://en.wikipedia.org/wiki/SHA-2#Pseudocode) and partially from some open-source projects. Algorithm doesn't import any (even standard) modules. Of cause it is much slower than `hashlib`'s variant and only meant for studying. If you just run the script it executes 1000 tests comparing `hashlib`'s and my variants. Only testing function imports some modules, algorithm's class itself doesn't need any modules. Interface is same as in hashlib's sha256 class. See `test()` function for examples of usage. [Try it online!](https://tio.run/##lVZNc9s2EL37V6CHVmRtKwAIgKQnyfTk6aW9pDdV1QAgYDEWJY9IT2VPp3/dXSwoiZRlN@FF0AL7dvftB/Dw1C036@zlxa5025IvS82lurkg8N235BOZ4TJ8dCd4obkviytY5yzLhShZWBtpqTfWh7UrjayMllcDvayUynJpwr4sPWPMo17JM19wLcJaG2alq0Z6VUFzraM9xotMGop6XGSskMYhnqQ2r2w21Mu5cbLKEbeglTPM49nSVJYqnYe1ZaXxDM4M9JwojSot2nDeOJEXKqyph9OVVdE2tZpZO9TjlSu5VRi/0LkohNbomzVUgyLypYC4otJDvbLInGSSY/xFxqxSFfJJacZzi3EbL8vc23yoZ5Wj1Pgs7FdS5yUTGBNVVqtMov9M8JKXaqTHc5NTXUiMwzHDWYY2RAXeVx79lFkGlLERn0pSnWdSxDiUptpgLgtmuS155JbnnNtilD/NjXeFZjE@ppUSqGe5MAW4gutcWcn0yF7FALRgJcanypIqjra9oC6T0X8GidQUMAZ6rNTCMoZ5Yi4DZIrxcUhJnguMLxOGGmtO6pNZag3yKVxVaC1i/kxprRaYV1Vwp7wf15kooH4dxp8XWqos1kAhbJEXLNaftTnl4Mcw79Q47z3a0EJC2hzyAtJSZz7Wp8pZXnge9eYX@LM87UjIRemUQg1jVK5dZCeDEvFZHitLCu9lNqo8yaiTPPexK6hURYHsMF9kValjpxpHLaRi5MFvGQcX6O62/6K0cp4sFvW67haLpHUrwG3g2O@btUtvDmbDxrRZuXVAGEvNowehmUzG4nsQxkU7u5mP95b7veXrPV8HG7d61brDRu3Bp7ol602Hjh39Oqg9PlS6c0mTxqh@aTvd1bZxMCGrQ5wPukpCEIPAmqoGcxjZT4H828MOiO664CmqkI8fSZZOu83CPHWuTaA4J6a@m6SH8wAe@ZGSXCNucBt@PhKpiIN4CGNl3DoobV33uF0De3/CtJuQS1xRWP28x7vsHXkvru1mm@yuyNMgrh44SXbk82fYIf8QWEIQCVTBNQjSFAKOV8YUKuM9@EZ/Rfgr8nzGwg5wAP@vuHrG1ROu3sO0y2@CTP7dpQMs1Nw0D1vXtn2x2oH@36HF6BzIU@IonFFyQ5iah8163U39dtP0WbSzGvZqIFnM9wklfrMFEZThVq/vXAKjDjKQ2PSKiLRvpfCdHAujS4n0pDTpvtJDiv4Ga9eESTBF8hDeuR1WYOAHSUgfVN4Ylr2GJTwon4ONO@UAFiQBltExLGwGkva2gbHLEMEliYIc/7OQD7RwqJrwwUCEyQODCG5BGKqQmLsrcuzzN2n7H8oAlo9CAgHLTiWcjwPpwqBDz@Pcgvrt/XuPR3BbjZBBwNiphMsTWwFjiczs7UFt9xSke9F9oBaJHFQQXgugfTeS3IHEjyRhvrqRxIU0VQDYjdMxPFPBGTuS2DCnRxIDEj2S6IDchVA6fj7TmMArEgdOSKRbPzZuG6bvc/2QxHxfkdn5ipin6Znpvewrbwd2n16bDW3fD/j@hhqA7C@HcDEQ8C00a5OST3BRjS3F6TIo2bZ12w4vlf3NAzPgV90uiV5tna6eCIj0qn52FdHrili9xtPG9d5UP0wuzlyRl596J463zL7OwmV5SZo326EfNuD/hw9nxglW137@NTMlYNSFCYaLJMwxls7Ti3MXdDPrga9J0q9@RAvzI8dVfefaDjkeEzzk6O3LF9fhjj1QkaavD0cj8ckw/bqp18nueK2K0RTeBWL6Arkp5mfA4mvhj@2jO71EBraOAS7d7nyMnQ6tMKGMZ0KqvIB3lAWFySnq3mU4PzNhhorQ1vFfeD/cztFxc3C8NwdEXAQHOvwT7dbNw2YbeLUA3kJvQOWtaugZKIVq01wcyiMoHUtEUjpwHIjXWFwIAkTeu3XPZYSZhp@oyWU@SEjozzC6otVpi0@BJOCl0yNPcOt9eWPntJF06DlwH2dt@m3un3fiaDQdNcrXI8yr4OAyO@mW76GG8fKkVvW@qjHu8dQ8v9XHosfsme@k7GELb5RkEuPHeoHp0z5aCy3vH1erpym8OS/q8Ghf68YtFgFislg0ul4vFpNIQSyzi5eX/wA "Python 3 – Try It Online") ``` class Sha256: ks = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, ] hs = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, ] M32 = 0xFFFFFFFF def __init__(self, m = None): self.mlen = 0 self.buf = b'' self.k = self.ks[:] self.h = self.hs[:] self.fin = False if m is not None: self.update(m) @staticmethod def pad(mlen): mdi = mlen & 0x3F length = (mlen << 3).to_bytes(8, 'big') padlen = 55 - mdi if mdi < 56 else 119 - mdi return b'\x80' + b'\x00' * padlen + length @staticmethod def ror(x, y): return ((x >> y) | (x << (32 - y))) & Sha256.M32 @staticmethod def maj(x, y, z): return (x & y) ^ (x & z) ^ (y & z) @staticmethod def ch(x, y, z): return (x & y) ^ ((~x) & z) def compress(self, c): w = [0] * 64 w[0 : 16] = [int.from_bytes(c[i : i + 4], 'big') for i in range(0, len(c), 4)] for i in range(16, 64): s0 = self.ror(w[i - 15], 7) ^ self.ror(w[i - 15], 18) ^ (w[i - 15] >> 3) s1 = self.ror(w[i - 2], 17) ^ self.ror(w[i - 2], 19) ^ (w[i - 2] >> 10) w[i] = (w[i - 16] + s0 + w[i - 7] + s1) & self.M32 a, b, c, d, e, f, g, h = self.h for i in range(64): s0 = self.ror(a, 2) ^ self.ror(a, 13) ^ self.ror(a, 22) t2 = s0 + self.maj(a, b, c) s1 = self.ror(e, 6) ^ self.ror(e, 11) ^ self.ror(e, 25) t1 = h + s1 + self.ch(e, f, g) + self.k[i] + w[i] h = g g = f f = e e = (d + t1) & self.M32 d = c c = b b = a a = (t1 + t2) & self.M32 for i, (x, y) in enumerate(zip(self.h, [a, b, c, d, e, f, g, h])): self.h[i] = (x + y) & self.M32 def update(self, m): if m is None or len(m) == 0: return assert not self.fin, 'Hash already finalized and can not be updated!' self.mlen += len(m) m = self.buf + m for i in range(0, len(m) // 64): self.compress(m[64 * i : 64 * (i + 1)]) self.buf = m[len(m) - (len(m) % 64):] def digest(self): if not self.fin: self.update(self.pad(self.mlen)) self.digest = b''.join(x.to_bytes(4, 'big') for x in self.h[:8]) self.fin = True return self.digest def hexdigest(self): tab = '0123456789abcdef' return ''.join(tab[b >> 4] + tab[b & 0xF] for b in self.digest()) def test(): import secrets, hashlib, random for itest in range(500): data = secrets.token_bytes(random.randrange(257)) a, b = hashlib.sha256(data).hexdigest(), Sha256(data).hexdigest() assert a == b, (a, b) for itest in range(500): a, b = hashlib.sha256(), Sha256() for j in range(random.randrange(10)): data = secrets.token_bytes(random.randrange(129)) a.update(data) b.update(data) a, b = a.hexdigest(), b.hexdigest() assert a == b, (a, b) print('Sha256 tested successfully.') if __name__ == '__main__': test() ```
If you only want the hash value: ``` from hashlib import sha256 data = input('Enter plaintext data: ') output = sha256(data.encode('utf-8')) print(output) ``` Python's hashlib also has SHA-1, SHA-384, SHA-512, and MD5 hash functions.
7,321,698
I have used DATEDIFF function but since it requires yyyy/mm/dd this code is giving wrong value ,because i have stored date from date time picker in this formate day,month,dd,yyyy ``` private void button3_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); DataSet ds1 = new DataSet(); DataSet ds2 = new DataSet(); DBHandling db = new DBHandling(); db.GetDataset(" select JoiningDate from Emp where name = '" + textBox2.Text + "'", ref ds); db.GetDataset(" select LeavingDate from AddDate where name = '" + textBox2.Text + "'", ref ds1); string date1, date2; date1 = ds.Tables[0].Rows[0][0].ToString(); date2 = ds1.Tables[0].Rows[0][0].ToString(); db.GetDataset("select DATEDIFF(day,2008/1/15,2008/1/12) ", ref ds2); textBox5.Text = ds2.Tables[0].Rows[0][0].ToString(); } ``` so how should i do this so that i will gate right Difference between 2 dates i.e number of days between 2 dates,thanks in advance
2011/09/06
[ "https://Stackoverflow.com/questions/7321698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/895965/" ]
PyPy's source contains a pure-python implementation of SHA-256 [here](https://foss.heptapod.net/pypy/pypy/-/blob/branch/default/lib_pypy/_sha256.py). Poking around in that directory, you'll probably also find pure-python implementations of other standard hashes.
Some time ago I was also studying SHA-256 and created pure-python class that implements this hash. If I remember correctly, mostly I've taken algorithm from Wikipedia [SHA-256 Pseudocode](https://en.wikipedia.org/wiki/SHA-2#Pseudocode) and partially from some open-source projects. Algorithm doesn't import any (even standard) modules. Of cause it is much slower than `hashlib`'s variant and only meant for studying. If you just run the script it executes 1000 tests comparing `hashlib`'s and my variants. Only testing function imports some modules, algorithm's class itself doesn't need any modules. Interface is same as in hashlib's sha256 class. See `test()` function for examples of usage. [Try it online!](https://tio.run/##lVZNc9s2EL37V6CHVmRtKwAIgKQnyfTk6aW9pDdV1QAgYDEWJY9IT2VPp3/dXSwoiZRlN@FF0AL7dvftB/Dw1C036@zlxa5025IvS82lurkg8N235BOZ4TJ8dCd4obkviytY5yzLhShZWBtpqTfWh7UrjayMllcDvayUynJpwr4sPWPMo17JM19wLcJaG2alq0Z6VUFzraM9xotMGop6XGSskMYhnqQ2r2w21Mu5cbLKEbeglTPM49nSVJYqnYe1ZaXxDM4M9JwojSot2nDeOJEXKqyph9OVVdE2tZpZO9TjlSu5VRi/0LkohNbomzVUgyLypYC4otJDvbLInGSSY/xFxqxSFfJJacZzi3EbL8vc23yoZ5Wj1Pgs7FdS5yUTGBNVVqtMov9M8JKXaqTHc5NTXUiMwzHDWYY2RAXeVx79lFkGlLERn0pSnWdSxDiUptpgLgtmuS155JbnnNtilD/NjXeFZjE@ppUSqGe5MAW4gutcWcn0yF7FALRgJcanypIqjra9oC6T0X8GidQUMAZ6rNTCMoZ5Yi4DZIrxcUhJnguMLxOGGmtO6pNZag3yKVxVaC1i/kxprRaYV1Vwp7wf15kooH4dxp8XWqos1kAhbJEXLNaftTnl4Mcw79Q47z3a0EJC2hzyAtJSZz7Wp8pZXnge9eYX@LM87UjIRemUQg1jVK5dZCeDEvFZHitLCu9lNqo8yaiTPPexK6hURYHsMF9kValjpxpHLaRi5MFvGQcX6O62/6K0cp4sFvW67haLpHUrwG3g2O@btUtvDmbDxrRZuXVAGEvNowehmUzG4nsQxkU7u5mP95b7veXrPV8HG7d61brDRu3Bp7ol602Hjh39Oqg9PlS6c0mTxqh@aTvd1bZxMCGrQ5wPukpCEIPAmqoGcxjZT4H828MOiO664CmqkI8fSZZOu83CPHWuTaA4J6a@m6SH8wAe@ZGSXCNucBt@PhKpiIN4CGNl3DoobV33uF0De3/CtJuQS1xRWP28x7vsHXkvru1mm@yuyNMgrh44SXbk82fYIf8QWEIQCVTBNQjSFAKOV8YUKuM9@EZ/Rfgr8nzGwg5wAP@vuHrG1ROu3sO0y2@CTP7dpQMs1Nw0D1vXtn2x2oH@36HF6BzIU@IonFFyQ5iah8163U39dtP0WbSzGvZqIFnM9wklfrMFEZThVq/vXAKjDjKQ2PSKiLRvpfCdHAujS4n0pDTpvtJDiv4Ga9eESTBF8hDeuR1WYOAHSUgfVN4Ylr2GJTwon4ONO@UAFiQBltExLGwGkva2gbHLEMEliYIc/7OQD7RwqJrwwUCEyQODCG5BGKqQmLsrcuzzN2n7H8oAlo9CAgHLTiWcjwPpwqBDz@Pcgvrt/XuPR3BbjZBBwNiphMsTWwFjiczs7UFt9xSke9F9oBaJHFQQXgugfTeS3IHEjyRhvrqRxIU0VQDYjdMxPFPBGTuS2DCnRxIDEj2S6IDchVA6fj7TmMArEgdOSKRbPzZuG6bvc/2QxHxfkdn5ipin6Znpvewrbwd2n16bDW3fD/j@hhqA7C@HcDEQ8C00a5OST3BRjS3F6TIo2bZ12w4vlf3NAzPgV90uiV5tna6eCIj0qn52FdHrili9xtPG9d5UP0wuzlyRl596J463zL7OwmV5SZo326EfNuD/hw9nxglW137@NTMlYNSFCYaLJMwxls7Ti3MXdDPrga9J0q9@RAvzI8dVfefaDjkeEzzk6O3LF9fhjj1QkaavD0cj8ckw/bqp18nueK2K0RTeBWL6Arkp5mfA4mvhj@2jO71EBraOAS7d7nyMnQ6tMKGMZ0KqvIB3lAWFySnq3mU4PzNhhorQ1vFfeD/cztFxc3C8NwdEXAQHOvwT7dbNw2YbeLUA3kJvQOWtaugZKIVq01wcyiMoHUtEUjpwHIjXWFwIAkTeu3XPZYSZhp@oyWU@SEjozzC6otVpi0@BJOCl0yNPcOt9eWPntJF06DlwH2dt@m3un3fiaDQdNcrXI8yr4OAyO@mW76GG8fKkVvW@qjHu8dQ8v9XHosfsme@k7GELb5RkEuPHeoHp0z5aCy3vH1erpym8OS/q8Ghf68YtFgFislg0ul4vFpNIQSyzi5eX/wA "Python 3 – Try It Online") ``` class Sha256: ks = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, ] hs = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, ] M32 = 0xFFFFFFFF def __init__(self, m = None): self.mlen = 0 self.buf = b'' self.k = self.ks[:] self.h = self.hs[:] self.fin = False if m is not None: self.update(m) @staticmethod def pad(mlen): mdi = mlen & 0x3F length = (mlen << 3).to_bytes(8, 'big') padlen = 55 - mdi if mdi < 56 else 119 - mdi return b'\x80' + b'\x00' * padlen + length @staticmethod def ror(x, y): return ((x >> y) | (x << (32 - y))) & Sha256.M32 @staticmethod def maj(x, y, z): return (x & y) ^ (x & z) ^ (y & z) @staticmethod def ch(x, y, z): return (x & y) ^ ((~x) & z) def compress(self, c): w = [0] * 64 w[0 : 16] = [int.from_bytes(c[i : i + 4], 'big') for i in range(0, len(c), 4)] for i in range(16, 64): s0 = self.ror(w[i - 15], 7) ^ self.ror(w[i - 15], 18) ^ (w[i - 15] >> 3) s1 = self.ror(w[i - 2], 17) ^ self.ror(w[i - 2], 19) ^ (w[i - 2] >> 10) w[i] = (w[i - 16] + s0 + w[i - 7] + s1) & self.M32 a, b, c, d, e, f, g, h = self.h for i in range(64): s0 = self.ror(a, 2) ^ self.ror(a, 13) ^ self.ror(a, 22) t2 = s0 + self.maj(a, b, c) s1 = self.ror(e, 6) ^ self.ror(e, 11) ^ self.ror(e, 25) t1 = h + s1 + self.ch(e, f, g) + self.k[i] + w[i] h = g g = f f = e e = (d + t1) & self.M32 d = c c = b b = a a = (t1 + t2) & self.M32 for i, (x, y) in enumerate(zip(self.h, [a, b, c, d, e, f, g, h])): self.h[i] = (x + y) & self.M32 def update(self, m): if m is None or len(m) == 0: return assert not self.fin, 'Hash already finalized and can not be updated!' self.mlen += len(m) m = self.buf + m for i in range(0, len(m) // 64): self.compress(m[64 * i : 64 * (i + 1)]) self.buf = m[len(m) - (len(m) % 64):] def digest(self): if not self.fin: self.update(self.pad(self.mlen)) self.digest = b''.join(x.to_bytes(4, 'big') for x in self.h[:8]) self.fin = True return self.digest def hexdigest(self): tab = '0123456789abcdef' return ''.join(tab[b >> 4] + tab[b & 0xF] for b in self.digest()) def test(): import secrets, hashlib, random for itest in range(500): data = secrets.token_bytes(random.randrange(257)) a, b = hashlib.sha256(data).hexdigest(), Sha256(data).hexdigest() assert a == b, (a, b) for itest in range(500): a, b = hashlib.sha256(), Sha256() for j in range(random.randrange(10)): data = secrets.token_bytes(random.randrange(129)) a.update(data) b.update(data) a, b = a.hexdigest(), b.hexdigest() assert a == b, (a, b) print('Sha256 tested successfully.') if __name__ == '__main__': test() ```
7,321,698
I have used DATEDIFF function but since it requires yyyy/mm/dd this code is giving wrong value ,because i have stored date from date time picker in this formate day,month,dd,yyyy ``` private void button3_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); DataSet ds1 = new DataSet(); DataSet ds2 = new DataSet(); DBHandling db = new DBHandling(); db.GetDataset(" select JoiningDate from Emp where name = '" + textBox2.Text + "'", ref ds); db.GetDataset(" select LeavingDate from AddDate where name = '" + textBox2.Text + "'", ref ds1); string date1, date2; date1 = ds.Tables[0].Rows[0][0].ToString(); date2 = ds1.Tables[0].Rows[0][0].ToString(); db.GetDataset("select DATEDIFF(day,2008/1/15,2008/1/12) ", ref ds2); textBox5.Text = ds2.Tables[0].Rows[0][0].ToString(); } ``` so how should i do this so that i will gate right Difference between 2 dates i.e number of days between 2 dates,thanks in advance
2011/09/06
[ "https://Stackoverflow.com/questions/7321698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/895965/" ]
Some time ago I was also studying SHA-256 and created pure-python class that implements this hash. If I remember correctly, mostly I've taken algorithm from Wikipedia [SHA-256 Pseudocode](https://en.wikipedia.org/wiki/SHA-2#Pseudocode) and partially from some open-source projects. Algorithm doesn't import any (even standard) modules. Of cause it is much slower than `hashlib`'s variant and only meant for studying. If you just run the script it executes 1000 tests comparing `hashlib`'s and my variants. Only testing function imports some modules, algorithm's class itself doesn't need any modules. Interface is same as in hashlib's sha256 class. See `test()` function for examples of usage. [Try it online!](https://tio.run/##lVZNc9s2EL37V6CHVmRtKwAIgKQnyfTk6aW9pDdV1QAgYDEWJY9IT2VPp3/dXSwoiZRlN@FF0AL7dvftB/Dw1C036@zlxa5025IvS82lurkg8N235BOZ4TJ8dCd4obkviytY5yzLhShZWBtpqTfWh7UrjayMllcDvayUynJpwr4sPWPMo17JM19wLcJaG2alq0Z6VUFzraM9xotMGop6XGSskMYhnqQ2r2w21Mu5cbLKEbeglTPM49nSVJYqnYe1ZaXxDM4M9JwojSot2nDeOJEXKqyph9OVVdE2tZpZO9TjlSu5VRi/0LkohNbomzVUgyLypYC4otJDvbLInGSSY/xFxqxSFfJJacZzi3EbL8vc23yoZ5Wj1Pgs7FdS5yUTGBNVVqtMov9M8JKXaqTHc5NTXUiMwzHDWYY2RAXeVx79lFkGlLERn0pSnWdSxDiUptpgLgtmuS155JbnnNtilD/NjXeFZjE@ppUSqGe5MAW4gutcWcn0yF7FALRgJcanypIqjra9oC6T0X8GidQUMAZ6rNTCMoZ5Yi4DZIrxcUhJnguMLxOGGmtO6pNZag3yKVxVaC1i/kxprRaYV1Vwp7wf15kooH4dxp8XWqos1kAhbJEXLNaftTnl4Mcw79Q47z3a0EJC2hzyAtJSZz7Wp8pZXnge9eYX@LM87UjIRemUQg1jVK5dZCeDEvFZHitLCu9lNqo8yaiTPPexK6hURYHsMF9kValjpxpHLaRi5MFvGQcX6O62/6K0cp4sFvW67haLpHUrwG3g2O@btUtvDmbDxrRZuXVAGEvNowehmUzG4nsQxkU7u5mP95b7veXrPV8HG7d61brDRu3Bp7ol602Hjh39Oqg9PlS6c0mTxqh@aTvd1bZxMCGrQ5wPukpCEIPAmqoGcxjZT4H828MOiO664CmqkI8fSZZOu83CPHWuTaA4J6a@m6SH8wAe@ZGSXCNucBt@PhKpiIN4CGNl3DoobV33uF0De3/CtJuQS1xRWP28x7vsHXkvru1mm@yuyNMgrh44SXbk82fYIf8QWEIQCVTBNQjSFAKOV8YUKuM9@EZ/Rfgr8nzGwg5wAP@vuHrG1ROu3sO0y2@CTP7dpQMs1Nw0D1vXtn2x2oH@36HF6BzIU@IonFFyQ5iah8163U39dtP0WbSzGvZqIFnM9wklfrMFEZThVq/vXAKjDjKQ2PSKiLRvpfCdHAujS4n0pDTpvtJDiv4Ga9eESTBF8hDeuR1WYOAHSUgfVN4Ylr2GJTwon4ONO@UAFiQBltExLGwGkva2gbHLEMEliYIc/7OQD7RwqJrwwUCEyQODCG5BGKqQmLsrcuzzN2n7H8oAlo9CAgHLTiWcjwPpwqBDz@Pcgvrt/XuPR3BbjZBBwNiphMsTWwFjiczs7UFt9xSke9F9oBaJHFQQXgugfTeS3IHEjyRhvrqRxIU0VQDYjdMxPFPBGTuS2DCnRxIDEj2S6IDchVA6fj7TmMArEgdOSKRbPzZuG6bvc/2QxHxfkdn5ipin6Znpvewrbwd2n16bDW3fD/j@hhqA7C@HcDEQ8C00a5OST3BRjS3F6TIo2bZ12w4vlf3NAzPgV90uiV5tna6eCIj0qn52FdHrili9xtPG9d5UP0wuzlyRl596J463zL7OwmV5SZo326EfNuD/hw9nxglW137@NTMlYNSFCYaLJMwxls7Ti3MXdDPrga9J0q9@RAvzI8dVfefaDjkeEzzk6O3LF9fhjj1QkaavD0cj8ckw/bqp18nueK2K0RTeBWL6Arkp5mfA4mvhj@2jO71EBraOAS7d7nyMnQ6tMKGMZ0KqvIB3lAWFySnq3mU4PzNhhorQ1vFfeD/cztFxc3C8NwdEXAQHOvwT7dbNw2YbeLUA3kJvQOWtaugZKIVq01wcyiMoHUtEUjpwHIjXWFwIAkTeu3XPZYSZhp@oyWU@SEjozzC6otVpi0@BJOCl0yNPcOt9eWPntJF06DlwH2dt@m3un3fiaDQdNcrXI8yr4OAyO@mW76GG8fKkVvW@qjHu8dQ8v9XHosfsme@k7GELb5RkEuPHeoHp0z5aCy3vH1erpym8OS/q8Ghf68YtFgFislg0ul4vFpNIQSyzi5eX/wA "Python 3 – Try It Online") ``` class Sha256: ks = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, ] hs = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, ] M32 = 0xFFFFFFFF def __init__(self, m = None): self.mlen = 0 self.buf = b'' self.k = self.ks[:] self.h = self.hs[:] self.fin = False if m is not None: self.update(m) @staticmethod def pad(mlen): mdi = mlen & 0x3F length = (mlen << 3).to_bytes(8, 'big') padlen = 55 - mdi if mdi < 56 else 119 - mdi return b'\x80' + b'\x00' * padlen + length @staticmethod def ror(x, y): return ((x >> y) | (x << (32 - y))) & Sha256.M32 @staticmethod def maj(x, y, z): return (x & y) ^ (x & z) ^ (y & z) @staticmethod def ch(x, y, z): return (x & y) ^ ((~x) & z) def compress(self, c): w = [0] * 64 w[0 : 16] = [int.from_bytes(c[i : i + 4], 'big') for i in range(0, len(c), 4)] for i in range(16, 64): s0 = self.ror(w[i - 15], 7) ^ self.ror(w[i - 15], 18) ^ (w[i - 15] >> 3) s1 = self.ror(w[i - 2], 17) ^ self.ror(w[i - 2], 19) ^ (w[i - 2] >> 10) w[i] = (w[i - 16] + s0 + w[i - 7] + s1) & self.M32 a, b, c, d, e, f, g, h = self.h for i in range(64): s0 = self.ror(a, 2) ^ self.ror(a, 13) ^ self.ror(a, 22) t2 = s0 + self.maj(a, b, c) s1 = self.ror(e, 6) ^ self.ror(e, 11) ^ self.ror(e, 25) t1 = h + s1 + self.ch(e, f, g) + self.k[i] + w[i] h = g g = f f = e e = (d + t1) & self.M32 d = c c = b b = a a = (t1 + t2) & self.M32 for i, (x, y) in enumerate(zip(self.h, [a, b, c, d, e, f, g, h])): self.h[i] = (x + y) & self.M32 def update(self, m): if m is None or len(m) == 0: return assert not self.fin, 'Hash already finalized and can not be updated!' self.mlen += len(m) m = self.buf + m for i in range(0, len(m) // 64): self.compress(m[64 * i : 64 * (i + 1)]) self.buf = m[len(m) - (len(m) % 64):] def digest(self): if not self.fin: self.update(self.pad(self.mlen)) self.digest = b''.join(x.to_bytes(4, 'big') for x in self.h[:8]) self.fin = True return self.digest def hexdigest(self): tab = '0123456789abcdef' return ''.join(tab[b >> 4] + tab[b & 0xF] for b in self.digest()) def test(): import secrets, hashlib, random for itest in range(500): data = secrets.token_bytes(random.randrange(257)) a, b = hashlib.sha256(data).hexdigest(), Sha256(data).hexdigest() assert a == b, (a, b) for itest in range(500): a, b = hashlib.sha256(), Sha256() for j in range(random.randrange(10)): data = secrets.token_bytes(random.randrange(129)) a.update(data) b.update(data) a, b = a.hexdigest(), b.hexdigest() assert a == b, (a, b) print('Sha256 tested successfully.') if __name__ == '__main__': test() ```
Here is my proposition with redis: ``` for i in range(len(rserver.keys())): mdp_hash = rserver.get(rserver.keys()[i]) rserver.set(rserver.keys()[i], hashlib.sha256(mdp_hash.encode()).hexdigest()) ```
7,321,698
I have used DATEDIFF function but since it requires yyyy/mm/dd this code is giving wrong value ,because i have stored date from date time picker in this formate day,month,dd,yyyy ``` private void button3_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); DataSet ds1 = new DataSet(); DataSet ds2 = new DataSet(); DBHandling db = new DBHandling(); db.GetDataset(" select JoiningDate from Emp where name = '" + textBox2.Text + "'", ref ds); db.GetDataset(" select LeavingDate from AddDate where name = '" + textBox2.Text + "'", ref ds1); string date1, date2; date1 = ds.Tables[0].Rows[0][0].ToString(); date2 = ds1.Tables[0].Rows[0][0].ToString(); db.GetDataset("select DATEDIFF(day,2008/1/15,2008/1/12) ", ref ds2); textBox5.Text = ds2.Tables[0].Rows[0][0].ToString(); } ``` so how should i do this so that i will gate right Difference between 2 dates i.e number of days between 2 dates,thanks in advance
2011/09/06
[ "https://Stackoverflow.com/questions/7321698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/895965/" ]
``` initial_hash_values=[ '6a09e667','bb67ae85','3c6ef372','a54ff53a', '510e527f','9b05688c','1f83d9ab','5be0cd19' ] sha_256_constants=[ '428a2f98','71374491','b5c0fbcf','e9b5dba5', '3956c25b','59f111f1','923f82a4','ab1c5ed5', 'd807aa98','12835b01','243185be','550c7dc3', '72be5d74','80deb1fe','9bdc06a7','c19bf174', 'e49b69c1','efbe4786','0fc19dc6','240ca1cc', '2de92c6f','4a7484aa','5cb0a9dc','76f988da', '983e5152','a831c66d','b00327c8','bf597fc7', 'c6e00bf3','d5a79147','06ca6351','14292967', '27b70a85','2e1b2138','4d2c6dfc','53380d13', '650a7354','766a0abb','81c2c92e','92722c85', 'a2bfe8a1','a81a664b','c24b8b70','c76c51a3', 'd192e819','d6990624','f40e3585','106aa070', '19a4c116','1e376c08','2748774c','34b0bcb5', '391c0cb3','4ed8aa4a','5b9cca4f','682e6ff3', '748f82ee','78a5636f','84c87814','8cc70208', '90befffa','a4506ceb','bef9a3f7','c67178f2' ] def bin_return(dec): return(str(format(dec,'b'))) def bin_8bit(dec): return(str(format(dec,'08b'))) def bin_32bit(dec): return(str(format(dec,'032b'))) def bin_64bit(dec): return(str(format(dec,'064b'))) def hex_return(dec): return(str(format(dec,'x'))) def dec_return_bin(bin_string): return(int(bin_string,2)) def dec_return_hex(hex_string): return(int(hex_string,16)) def L_P(SET,n): to_return=[] j=0 k=n while k<len(SET)+1: to_return.append(SET[j:k]) j=k k+=n return(to_return) def s_l(bit_string): bit_list=[] for i in range(len(bit_string)): bit_list.append(bit_string[i]) return(bit_list) def l_s(bit_list): bit_string='' for i in range(len(bit_list)): bit_string+=bit_list[i] return(bit_string) def rotate_right(bit_string,n): bit_list = s_l(bit_string) count=0 while count <= n-1: list_main=list(bit_list) var_0=list_main.pop(-1) list_main=list([var_0]+list_main) bit_list=list(list_main) count+=1 return(l_s(list_main)) def shift_right(bit_string,n): bit_list=s_l(bit_string) count=0 while count <= n-1: bit_list.pop(-1) count+=1 front_append=['0']*n return(l_s(front_append+bit_list)) def mod_32_addition(input_set): value=0 for i in range(len(input_set)): value+=input_set[i] mod_32 = 4294967296 return(value%mod_32) def xor_2str(bit_string_1,bit_string_2): xor_list=[] for i in range(len(bit_string_1)): if bit_string_1[i]=='0' and bit_string_2[i]=='0': xor_list.append('0') if bit_string_1[i]=='1' and bit_string_2[i]=='1': xor_list.append('0') if bit_string_1[i]=='0' and bit_string_2[i]=='1': xor_list.append('1') if bit_string_1[i]=='1' and bit_string_2[i]=='0': xor_list.append('1') return(l_s(xor_list)) def and_2str(bit_string_1,bit_string_2): and_list=[] for i in range(len(bit_string_1)): if bit_string_1[i]=='1' and bit_string_2[i]=='1': and_list.append('1') else: and_list.append('0') return(l_s(and_list)) def or_2str(bit_string_1,bit_string_2): or_list=[] for i in range(len(bit_string_1)): if bit_string_1[i]=='0' and bit_string_2[i]=='0': or_list.append('0') else: or_list.append('1') return(l_s(or_list)) def not_str(bit_string): not_list=[] for i in range(len(bit_string)): if bit_string[i]=='0': not_list.append('1') else: not_list.append('0') return(l_s(not_list)) ''' SHA-256 Specific Functions: ''' def Ch(x,y,z): return(xor_2str(and_2str(x,y),and_2str(not_str(x),z))) def Maj(x,y,z): return(xor_2str(xor_2str(and_2str(x,y),and_2str(x,z)),and_2str(y,z))) def e_0(x): return(xor_2str(xor_2str(rotate_right(x,2),rotate_right(x,13)),rotate_right(x,22))) def e_1(x): return(xor_2str(xor_2str(rotate_right(x,6),rotate_right(x,11)),rotate_right(x,25))) def s_0(x): return(xor_2str(xor_2str(rotate_right(x,7),rotate_right(x,18)),shift_right(x,3))) def s_1(x): return(xor_2str(xor_2str(rotate_right(x,17),rotate_right(x,19)),shift_right(x,10))) def message_pad(bit_list): pad_one = bit_list + '1' pad_len = len(pad_one) k=0 while ((pad_len+k)-448)%512 != 0: k+=1 back_append_0 = '0'*k back_append_1 = bin_64bit(len(bit_list)) return(pad_one+back_append_0+back_append_1) def message_bit_return(string_input): bit_list=[] for i in range(len(string_input)): bit_list.append(bin_8bit(ord(string_input[i]))) return(l_s(bit_list)) def message_pre_pro(input_string): bit_main = message_bit_return(input_string) return(message_pad(bit_main)) def message_parsing(input_string): return(L_P(message_pre_pro(input_string),32)) def message_schedule(index,w_t): new_word = bin_32bit(mod_32_addition([int(s_1(w_t[index-2]),2),int(w_t[index-7],2),int(s_0(w_t[index-15]),2),int(w_t[index-16],2)])) return(new_word) ''' This example of SHA_256 works for an input string <56 characters. ''' def sha_256(input_string): assert len(input_string) < 56, "This example of SHA_256 works for an input string <56 characters." w_t=message_parsing(input_string) a=bin_32bit(dec_return_hex(initial_hash_values[0])) b=bin_32bit(dec_return_hex(initial_hash_values[1])) c=bin_32bit(dec_return_hex(initial_hash_values[2])) d=bin_32bit(dec_return_hex(initial_hash_values[3])) e=bin_32bit(dec_return_hex(initial_hash_values[4])) f=bin_32bit(dec_return_hex(initial_hash_values[5])) g=bin_32bit(dec_return_hex(initial_hash_values[6])) h=bin_32bit(dec_return_hex(initial_hash_values[7])) for i in range(0,64): if i <= 15: t_1=mod_32_addition([int(h,2),int(e_1(e),2),int(Ch(e,f,g),2),int(sha_256_constants[i],16),int(w_t[i],2)]) t_2=mod_32_addition([int(e_0(a),2),int(Maj(a,b,c),2)]) h=g g=f f=e e=mod_32_addition([int(d,2),t_1]) d=c c=b b=a a=mod_32_addition([t_1,t_2]) a=bin_32bit(a) e=bin_32bit(e) if i > 15: w_t.append(message_schedule(i,w_t)) t_1=mod_32_addition([int(h,2),int(e_1(e),2),int(Ch(e,f,g),2),int(sha_256_constants[i],16),int(w_t[i],2)]) t_2=mod_32_addition([int(e_0(a),2),int(Maj(a,b,c),2)]) h=g g=f f=e e=mod_32_addition([int(d,2),t_1]) d=c c=b b=a a=mod_32_addition([t_1,t_2]) a=bin_32bit(a) e=bin_32bit(e) hash_0 = mod_32_addition([dec_return_hex(initial_hash_values[0]),int(a,2)]) hash_1 = mod_32_addition([dec_return_hex(initial_hash_values[1]),int(b,2)]) hash_2 = mod_32_addition([dec_return_hex(initial_hash_values[2]),int(c,2)]) hash_3 = mod_32_addition([dec_return_hex(initial_hash_values[3]),int(d,2)]) hash_4 = mod_32_addition([dec_return_hex(initial_hash_values[4]),int(e,2)]) hash_5 = mod_32_addition([dec_return_hex(initial_hash_values[5]),int(f,2)]) hash_6 = mod_32_addition([dec_return_hex(initial_hash_values[6]),int(g,2)]) hash_7 = mod_32_addition([dec_return_hex(initial_hash_values[7]),int(h,2)]) final_hash = (hex_return(hash_0), hex_return(hash_1), hex_return(hash_2), hex_return(hash_3), hex_return(hash_4), hex_return(hash_5), hex_return(hash_6), hex_return(hash_7)) return(final_hash) ```
Translating <http://en.wikipedia.org/wiki/SHA-2#SHA-256_.28a_SHA-2_variant.29_pseudocode> to Python should be straight forward.
7,321,698
I have used DATEDIFF function but since it requires yyyy/mm/dd this code is giving wrong value ,because i have stored date from date time picker in this formate day,month,dd,yyyy ``` private void button3_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); DataSet ds1 = new DataSet(); DataSet ds2 = new DataSet(); DBHandling db = new DBHandling(); db.GetDataset(" select JoiningDate from Emp where name = '" + textBox2.Text + "'", ref ds); db.GetDataset(" select LeavingDate from AddDate where name = '" + textBox2.Text + "'", ref ds1); string date1, date2; date1 = ds.Tables[0].Rows[0][0].ToString(); date2 = ds1.Tables[0].Rows[0][0].ToString(); db.GetDataset("select DATEDIFF(day,2008/1/15,2008/1/12) ", ref ds2); textBox5.Text = ds2.Tables[0].Rows[0][0].ToString(); } ``` so how should i do this so that i will gate right Difference between 2 dates i.e number of days between 2 dates,thanks in advance
2011/09/06
[ "https://Stackoverflow.com/questions/7321698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/895965/" ]
``` initial_hash_values=[ '6a09e667','bb67ae85','3c6ef372','a54ff53a', '510e527f','9b05688c','1f83d9ab','5be0cd19' ] sha_256_constants=[ '428a2f98','71374491','b5c0fbcf','e9b5dba5', '3956c25b','59f111f1','923f82a4','ab1c5ed5', 'd807aa98','12835b01','243185be','550c7dc3', '72be5d74','80deb1fe','9bdc06a7','c19bf174', 'e49b69c1','efbe4786','0fc19dc6','240ca1cc', '2de92c6f','4a7484aa','5cb0a9dc','76f988da', '983e5152','a831c66d','b00327c8','bf597fc7', 'c6e00bf3','d5a79147','06ca6351','14292967', '27b70a85','2e1b2138','4d2c6dfc','53380d13', '650a7354','766a0abb','81c2c92e','92722c85', 'a2bfe8a1','a81a664b','c24b8b70','c76c51a3', 'd192e819','d6990624','f40e3585','106aa070', '19a4c116','1e376c08','2748774c','34b0bcb5', '391c0cb3','4ed8aa4a','5b9cca4f','682e6ff3', '748f82ee','78a5636f','84c87814','8cc70208', '90befffa','a4506ceb','bef9a3f7','c67178f2' ] def bin_return(dec): return(str(format(dec,'b'))) def bin_8bit(dec): return(str(format(dec,'08b'))) def bin_32bit(dec): return(str(format(dec,'032b'))) def bin_64bit(dec): return(str(format(dec,'064b'))) def hex_return(dec): return(str(format(dec,'x'))) def dec_return_bin(bin_string): return(int(bin_string,2)) def dec_return_hex(hex_string): return(int(hex_string,16)) def L_P(SET,n): to_return=[] j=0 k=n while k<len(SET)+1: to_return.append(SET[j:k]) j=k k+=n return(to_return) def s_l(bit_string): bit_list=[] for i in range(len(bit_string)): bit_list.append(bit_string[i]) return(bit_list) def l_s(bit_list): bit_string='' for i in range(len(bit_list)): bit_string+=bit_list[i] return(bit_string) def rotate_right(bit_string,n): bit_list = s_l(bit_string) count=0 while count <= n-1: list_main=list(bit_list) var_0=list_main.pop(-1) list_main=list([var_0]+list_main) bit_list=list(list_main) count+=1 return(l_s(list_main)) def shift_right(bit_string,n): bit_list=s_l(bit_string) count=0 while count <= n-1: bit_list.pop(-1) count+=1 front_append=['0']*n return(l_s(front_append+bit_list)) def mod_32_addition(input_set): value=0 for i in range(len(input_set)): value+=input_set[i] mod_32 = 4294967296 return(value%mod_32) def xor_2str(bit_string_1,bit_string_2): xor_list=[] for i in range(len(bit_string_1)): if bit_string_1[i]=='0' and bit_string_2[i]=='0': xor_list.append('0') if bit_string_1[i]=='1' and bit_string_2[i]=='1': xor_list.append('0') if bit_string_1[i]=='0' and bit_string_2[i]=='1': xor_list.append('1') if bit_string_1[i]=='1' and bit_string_2[i]=='0': xor_list.append('1') return(l_s(xor_list)) def and_2str(bit_string_1,bit_string_2): and_list=[] for i in range(len(bit_string_1)): if bit_string_1[i]=='1' and bit_string_2[i]=='1': and_list.append('1') else: and_list.append('0') return(l_s(and_list)) def or_2str(bit_string_1,bit_string_2): or_list=[] for i in range(len(bit_string_1)): if bit_string_1[i]=='0' and bit_string_2[i]=='0': or_list.append('0') else: or_list.append('1') return(l_s(or_list)) def not_str(bit_string): not_list=[] for i in range(len(bit_string)): if bit_string[i]=='0': not_list.append('1') else: not_list.append('0') return(l_s(not_list)) ''' SHA-256 Specific Functions: ''' def Ch(x,y,z): return(xor_2str(and_2str(x,y),and_2str(not_str(x),z))) def Maj(x,y,z): return(xor_2str(xor_2str(and_2str(x,y),and_2str(x,z)),and_2str(y,z))) def e_0(x): return(xor_2str(xor_2str(rotate_right(x,2),rotate_right(x,13)),rotate_right(x,22))) def e_1(x): return(xor_2str(xor_2str(rotate_right(x,6),rotate_right(x,11)),rotate_right(x,25))) def s_0(x): return(xor_2str(xor_2str(rotate_right(x,7),rotate_right(x,18)),shift_right(x,3))) def s_1(x): return(xor_2str(xor_2str(rotate_right(x,17),rotate_right(x,19)),shift_right(x,10))) def message_pad(bit_list): pad_one = bit_list + '1' pad_len = len(pad_one) k=0 while ((pad_len+k)-448)%512 != 0: k+=1 back_append_0 = '0'*k back_append_1 = bin_64bit(len(bit_list)) return(pad_one+back_append_0+back_append_1) def message_bit_return(string_input): bit_list=[] for i in range(len(string_input)): bit_list.append(bin_8bit(ord(string_input[i]))) return(l_s(bit_list)) def message_pre_pro(input_string): bit_main = message_bit_return(input_string) return(message_pad(bit_main)) def message_parsing(input_string): return(L_P(message_pre_pro(input_string),32)) def message_schedule(index,w_t): new_word = bin_32bit(mod_32_addition([int(s_1(w_t[index-2]),2),int(w_t[index-7],2),int(s_0(w_t[index-15]),2),int(w_t[index-16],2)])) return(new_word) ''' This example of SHA_256 works for an input string <56 characters. ''' def sha_256(input_string): assert len(input_string) < 56, "This example of SHA_256 works for an input string <56 characters." w_t=message_parsing(input_string) a=bin_32bit(dec_return_hex(initial_hash_values[0])) b=bin_32bit(dec_return_hex(initial_hash_values[1])) c=bin_32bit(dec_return_hex(initial_hash_values[2])) d=bin_32bit(dec_return_hex(initial_hash_values[3])) e=bin_32bit(dec_return_hex(initial_hash_values[4])) f=bin_32bit(dec_return_hex(initial_hash_values[5])) g=bin_32bit(dec_return_hex(initial_hash_values[6])) h=bin_32bit(dec_return_hex(initial_hash_values[7])) for i in range(0,64): if i <= 15: t_1=mod_32_addition([int(h,2),int(e_1(e),2),int(Ch(e,f,g),2),int(sha_256_constants[i],16),int(w_t[i],2)]) t_2=mod_32_addition([int(e_0(a),2),int(Maj(a,b,c),2)]) h=g g=f f=e e=mod_32_addition([int(d,2),t_1]) d=c c=b b=a a=mod_32_addition([t_1,t_2]) a=bin_32bit(a) e=bin_32bit(e) if i > 15: w_t.append(message_schedule(i,w_t)) t_1=mod_32_addition([int(h,2),int(e_1(e),2),int(Ch(e,f,g),2),int(sha_256_constants[i],16),int(w_t[i],2)]) t_2=mod_32_addition([int(e_0(a),2),int(Maj(a,b,c),2)]) h=g g=f f=e e=mod_32_addition([int(d,2),t_1]) d=c c=b b=a a=mod_32_addition([t_1,t_2]) a=bin_32bit(a) e=bin_32bit(e) hash_0 = mod_32_addition([dec_return_hex(initial_hash_values[0]),int(a,2)]) hash_1 = mod_32_addition([dec_return_hex(initial_hash_values[1]),int(b,2)]) hash_2 = mod_32_addition([dec_return_hex(initial_hash_values[2]),int(c,2)]) hash_3 = mod_32_addition([dec_return_hex(initial_hash_values[3]),int(d,2)]) hash_4 = mod_32_addition([dec_return_hex(initial_hash_values[4]),int(e,2)]) hash_5 = mod_32_addition([dec_return_hex(initial_hash_values[5]),int(f,2)]) hash_6 = mod_32_addition([dec_return_hex(initial_hash_values[6]),int(g,2)]) hash_7 = mod_32_addition([dec_return_hex(initial_hash_values[7]),int(h,2)]) final_hash = (hex_return(hash_0), hex_return(hash_1), hex_return(hash_2), hex_return(hash_3), hex_return(hash_4), hex_return(hash_5), hex_return(hash_6), hex_return(hash_7)) return(final_hash) ```
Some time ago I was also studying SHA-256 and created pure-python class that implements this hash. If I remember correctly, mostly I've taken algorithm from Wikipedia [SHA-256 Pseudocode](https://en.wikipedia.org/wiki/SHA-2#Pseudocode) and partially from some open-source projects. Algorithm doesn't import any (even standard) modules. Of cause it is much slower than `hashlib`'s variant and only meant for studying. If you just run the script it executes 1000 tests comparing `hashlib`'s and my variants. Only testing function imports some modules, algorithm's class itself doesn't need any modules. Interface is same as in hashlib's sha256 class. See `test()` function for examples of usage. [Try it online!](https://tio.run/##lVZNc9s2EL37V6CHVmRtKwAIgKQnyfTk6aW9pDdV1QAgYDEWJY9IT2VPp3/dXSwoiZRlN@FF0AL7dvftB/Dw1C036@zlxa5025IvS82lurkg8N235BOZ4TJ8dCd4obkviytY5yzLhShZWBtpqTfWh7UrjayMllcDvayUynJpwr4sPWPMo17JM19wLcJaG2alq0Z6VUFzraM9xotMGop6XGSskMYhnqQ2r2w21Mu5cbLKEbeglTPM49nSVJYqnYe1ZaXxDM4M9JwojSot2nDeOJEXKqyph9OVVdE2tZpZO9TjlSu5VRi/0LkohNbomzVUgyLypYC4otJDvbLInGSSY/xFxqxSFfJJacZzi3EbL8vc23yoZ5Wj1Pgs7FdS5yUTGBNVVqtMov9M8JKXaqTHc5NTXUiMwzHDWYY2RAXeVx79lFkGlLERn0pSnWdSxDiUptpgLgtmuS155JbnnNtilD/NjXeFZjE@ppUSqGe5MAW4gutcWcn0yF7FALRgJcanypIqjra9oC6T0X8GidQUMAZ6rNTCMoZ5Yi4DZIrxcUhJnguMLxOGGmtO6pNZag3yKVxVaC1i/kxprRaYV1Vwp7wf15kooH4dxp8XWqos1kAhbJEXLNaftTnl4Mcw79Q47z3a0EJC2hzyAtJSZz7Wp8pZXnge9eYX@LM87UjIRemUQg1jVK5dZCeDEvFZHitLCu9lNqo8yaiTPPexK6hURYHsMF9kValjpxpHLaRi5MFvGQcX6O62/6K0cp4sFvW67haLpHUrwG3g2O@btUtvDmbDxrRZuXVAGEvNowehmUzG4nsQxkU7u5mP95b7veXrPV8HG7d61brDRu3Bp7ol602Hjh39Oqg9PlS6c0mTxqh@aTvd1bZxMCGrQ5wPukpCEIPAmqoGcxjZT4H828MOiO664CmqkI8fSZZOu83CPHWuTaA4J6a@m6SH8wAe@ZGSXCNucBt@PhKpiIN4CGNl3DoobV33uF0De3/CtJuQS1xRWP28x7vsHXkvru1mm@yuyNMgrh44SXbk82fYIf8QWEIQCVTBNQjSFAKOV8YUKuM9@EZ/Rfgr8nzGwg5wAP@vuHrG1ROu3sO0y2@CTP7dpQMs1Nw0D1vXtn2x2oH@36HF6BzIU@IonFFyQ5iah8163U39dtP0WbSzGvZqIFnM9wklfrMFEZThVq/vXAKjDjKQ2PSKiLRvpfCdHAujS4n0pDTpvtJDiv4Ga9eESTBF8hDeuR1WYOAHSUgfVN4Ylr2GJTwon4ONO@UAFiQBltExLGwGkva2gbHLEMEliYIc/7OQD7RwqJrwwUCEyQODCG5BGKqQmLsrcuzzN2n7H8oAlo9CAgHLTiWcjwPpwqBDz@Pcgvrt/XuPR3BbjZBBwNiphMsTWwFjiczs7UFt9xSke9F9oBaJHFQQXgugfTeS3IHEjyRhvrqRxIU0VQDYjdMxPFPBGTuS2DCnRxIDEj2S6IDchVA6fj7TmMArEgdOSKRbPzZuG6bvc/2QxHxfkdn5ipin6Znpvewrbwd2n16bDW3fD/j@hhqA7C@HcDEQ8C00a5OST3BRjS3F6TIo2bZ12w4vlf3NAzPgV90uiV5tna6eCIj0qn52FdHrili9xtPG9d5UP0wuzlyRl596J463zL7OwmV5SZo326EfNuD/hw9nxglW137@NTMlYNSFCYaLJMwxls7Ti3MXdDPrga9J0q9@RAvzI8dVfefaDjkeEzzk6O3LF9fhjj1QkaavD0cj8ckw/bqp18nueK2K0RTeBWL6Arkp5mfA4mvhj@2jO71EBraOAS7d7nyMnQ6tMKGMZ0KqvIB3lAWFySnq3mU4PzNhhorQ1vFfeD/cztFxc3C8NwdEXAQHOvwT7dbNw2YbeLUA3kJvQOWtaugZKIVq01wcyiMoHUtEUjpwHIjXWFwIAkTeu3XPZYSZhp@oyWU@SEjozzC6otVpi0@BJOCl0yNPcOt9eWPntJF06DlwH2dt@m3un3fiaDQdNcrXI8yr4OAyO@mW76GG8fKkVvW@qjHu8dQ8v9XHosfsme@k7GELb5RkEuPHeoHp0z5aCy3vH1erpym8OS/q8Ghf68YtFgFislg0ul4vFpNIQSyzi5eX/wA "Python 3 – Try It Online") ``` class Sha256: ks = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, ] hs = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, ] M32 = 0xFFFFFFFF def __init__(self, m = None): self.mlen = 0 self.buf = b'' self.k = self.ks[:] self.h = self.hs[:] self.fin = False if m is not None: self.update(m) @staticmethod def pad(mlen): mdi = mlen & 0x3F length = (mlen << 3).to_bytes(8, 'big') padlen = 55 - mdi if mdi < 56 else 119 - mdi return b'\x80' + b'\x00' * padlen + length @staticmethod def ror(x, y): return ((x >> y) | (x << (32 - y))) & Sha256.M32 @staticmethod def maj(x, y, z): return (x & y) ^ (x & z) ^ (y & z) @staticmethod def ch(x, y, z): return (x & y) ^ ((~x) & z) def compress(self, c): w = [0] * 64 w[0 : 16] = [int.from_bytes(c[i : i + 4], 'big') for i in range(0, len(c), 4)] for i in range(16, 64): s0 = self.ror(w[i - 15], 7) ^ self.ror(w[i - 15], 18) ^ (w[i - 15] >> 3) s1 = self.ror(w[i - 2], 17) ^ self.ror(w[i - 2], 19) ^ (w[i - 2] >> 10) w[i] = (w[i - 16] + s0 + w[i - 7] + s1) & self.M32 a, b, c, d, e, f, g, h = self.h for i in range(64): s0 = self.ror(a, 2) ^ self.ror(a, 13) ^ self.ror(a, 22) t2 = s0 + self.maj(a, b, c) s1 = self.ror(e, 6) ^ self.ror(e, 11) ^ self.ror(e, 25) t1 = h + s1 + self.ch(e, f, g) + self.k[i] + w[i] h = g g = f f = e e = (d + t1) & self.M32 d = c c = b b = a a = (t1 + t2) & self.M32 for i, (x, y) in enumerate(zip(self.h, [a, b, c, d, e, f, g, h])): self.h[i] = (x + y) & self.M32 def update(self, m): if m is None or len(m) == 0: return assert not self.fin, 'Hash already finalized and can not be updated!' self.mlen += len(m) m = self.buf + m for i in range(0, len(m) // 64): self.compress(m[64 * i : 64 * (i + 1)]) self.buf = m[len(m) - (len(m) % 64):] def digest(self): if not self.fin: self.update(self.pad(self.mlen)) self.digest = b''.join(x.to_bytes(4, 'big') for x in self.h[:8]) self.fin = True return self.digest def hexdigest(self): tab = '0123456789abcdef' return ''.join(tab[b >> 4] + tab[b & 0xF] for b in self.digest()) def test(): import secrets, hashlib, random for itest in range(500): data = secrets.token_bytes(random.randrange(257)) a, b = hashlib.sha256(data).hexdigest(), Sha256(data).hexdigest() assert a == b, (a, b) for itest in range(500): a, b = hashlib.sha256(), Sha256() for j in range(random.randrange(10)): data = secrets.token_bytes(random.randrange(129)) a.update(data) b.update(data) a, b = a.hexdigest(), b.hexdigest() assert a == b, (a, b) print('Sha256 tested successfully.') if __name__ == '__main__': test() ```
7,321,698
I have used DATEDIFF function but since it requires yyyy/mm/dd this code is giving wrong value ,because i have stored date from date time picker in this formate day,month,dd,yyyy ``` private void button3_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); DataSet ds1 = new DataSet(); DataSet ds2 = new DataSet(); DBHandling db = new DBHandling(); db.GetDataset(" select JoiningDate from Emp where name = '" + textBox2.Text + "'", ref ds); db.GetDataset(" select LeavingDate from AddDate where name = '" + textBox2.Text + "'", ref ds1); string date1, date2; date1 = ds.Tables[0].Rows[0][0].ToString(); date2 = ds1.Tables[0].Rows[0][0].ToString(); db.GetDataset("select DATEDIFF(day,2008/1/15,2008/1/12) ", ref ds2); textBox5.Text = ds2.Tables[0].Rows[0][0].ToString(); } ``` so how should i do this so that i will gate right Difference between 2 dates i.e number of days between 2 dates,thanks in advance
2011/09/06
[ "https://Stackoverflow.com/questions/7321698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/895965/" ]
``` initial_hash_values=[ '6a09e667','bb67ae85','3c6ef372','a54ff53a', '510e527f','9b05688c','1f83d9ab','5be0cd19' ] sha_256_constants=[ '428a2f98','71374491','b5c0fbcf','e9b5dba5', '3956c25b','59f111f1','923f82a4','ab1c5ed5', 'd807aa98','12835b01','243185be','550c7dc3', '72be5d74','80deb1fe','9bdc06a7','c19bf174', 'e49b69c1','efbe4786','0fc19dc6','240ca1cc', '2de92c6f','4a7484aa','5cb0a9dc','76f988da', '983e5152','a831c66d','b00327c8','bf597fc7', 'c6e00bf3','d5a79147','06ca6351','14292967', '27b70a85','2e1b2138','4d2c6dfc','53380d13', '650a7354','766a0abb','81c2c92e','92722c85', 'a2bfe8a1','a81a664b','c24b8b70','c76c51a3', 'd192e819','d6990624','f40e3585','106aa070', '19a4c116','1e376c08','2748774c','34b0bcb5', '391c0cb3','4ed8aa4a','5b9cca4f','682e6ff3', '748f82ee','78a5636f','84c87814','8cc70208', '90befffa','a4506ceb','bef9a3f7','c67178f2' ] def bin_return(dec): return(str(format(dec,'b'))) def bin_8bit(dec): return(str(format(dec,'08b'))) def bin_32bit(dec): return(str(format(dec,'032b'))) def bin_64bit(dec): return(str(format(dec,'064b'))) def hex_return(dec): return(str(format(dec,'x'))) def dec_return_bin(bin_string): return(int(bin_string,2)) def dec_return_hex(hex_string): return(int(hex_string,16)) def L_P(SET,n): to_return=[] j=0 k=n while k<len(SET)+1: to_return.append(SET[j:k]) j=k k+=n return(to_return) def s_l(bit_string): bit_list=[] for i in range(len(bit_string)): bit_list.append(bit_string[i]) return(bit_list) def l_s(bit_list): bit_string='' for i in range(len(bit_list)): bit_string+=bit_list[i] return(bit_string) def rotate_right(bit_string,n): bit_list = s_l(bit_string) count=0 while count <= n-1: list_main=list(bit_list) var_0=list_main.pop(-1) list_main=list([var_0]+list_main) bit_list=list(list_main) count+=1 return(l_s(list_main)) def shift_right(bit_string,n): bit_list=s_l(bit_string) count=0 while count <= n-1: bit_list.pop(-1) count+=1 front_append=['0']*n return(l_s(front_append+bit_list)) def mod_32_addition(input_set): value=0 for i in range(len(input_set)): value+=input_set[i] mod_32 = 4294967296 return(value%mod_32) def xor_2str(bit_string_1,bit_string_2): xor_list=[] for i in range(len(bit_string_1)): if bit_string_1[i]=='0' and bit_string_2[i]=='0': xor_list.append('0') if bit_string_1[i]=='1' and bit_string_2[i]=='1': xor_list.append('0') if bit_string_1[i]=='0' and bit_string_2[i]=='1': xor_list.append('1') if bit_string_1[i]=='1' and bit_string_2[i]=='0': xor_list.append('1') return(l_s(xor_list)) def and_2str(bit_string_1,bit_string_2): and_list=[] for i in range(len(bit_string_1)): if bit_string_1[i]=='1' and bit_string_2[i]=='1': and_list.append('1') else: and_list.append('0') return(l_s(and_list)) def or_2str(bit_string_1,bit_string_2): or_list=[] for i in range(len(bit_string_1)): if bit_string_1[i]=='0' and bit_string_2[i]=='0': or_list.append('0') else: or_list.append('1') return(l_s(or_list)) def not_str(bit_string): not_list=[] for i in range(len(bit_string)): if bit_string[i]=='0': not_list.append('1') else: not_list.append('0') return(l_s(not_list)) ''' SHA-256 Specific Functions: ''' def Ch(x,y,z): return(xor_2str(and_2str(x,y),and_2str(not_str(x),z))) def Maj(x,y,z): return(xor_2str(xor_2str(and_2str(x,y),and_2str(x,z)),and_2str(y,z))) def e_0(x): return(xor_2str(xor_2str(rotate_right(x,2),rotate_right(x,13)),rotate_right(x,22))) def e_1(x): return(xor_2str(xor_2str(rotate_right(x,6),rotate_right(x,11)),rotate_right(x,25))) def s_0(x): return(xor_2str(xor_2str(rotate_right(x,7),rotate_right(x,18)),shift_right(x,3))) def s_1(x): return(xor_2str(xor_2str(rotate_right(x,17),rotate_right(x,19)),shift_right(x,10))) def message_pad(bit_list): pad_one = bit_list + '1' pad_len = len(pad_one) k=0 while ((pad_len+k)-448)%512 != 0: k+=1 back_append_0 = '0'*k back_append_1 = bin_64bit(len(bit_list)) return(pad_one+back_append_0+back_append_1) def message_bit_return(string_input): bit_list=[] for i in range(len(string_input)): bit_list.append(bin_8bit(ord(string_input[i]))) return(l_s(bit_list)) def message_pre_pro(input_string): bit_main = message_bit_return(input_string) return(message_pad(bit_main)) def message_parsing(input_string): return(L_P(message_pre_pro(input_string),32)) def message_schedule(index,w_t): new_word = bin_32bit(mod_32_addition([int(s_1(w_t[index-2]),2),int(w_t[index-7],2),int(s_0(w_t[index-15]),2),int(w_t[index-16],2)])) return(new_word) ''' This example of SHA_256 works for an input string <56 characters. ''' def sha_256(input_string): assert len(input_string) < 56, "This example of SHA_256 works for an input string <56 characters." w_t=message_parsing(input_string) a=bin_32bit(dec_return_hex(initial_hash_values[0])) b=bin_32bit(dec_return_hex(initial_hash_values[1])) c=bin_32bit(dec_return_hex(initial_hash_values[2])) d=bin_32bit(dec_return_hex(initial_hash_values[3])) e=bin_32bit(dec_return_hex(initial_hash_values[4])) f=bin_32bit(dec_return_hex(initial_hash_values[5])) g=bin_32bit(dec_return_hex(initial_hash_values[6])) h=bin_32bit(dec_return_hex(initial_hash_values[7])) for i in range(0,64): if i <= 15: t_1=mod_32_addition([int(h,2),int(e_1(e),2),int(Ch(e,f,g),2),int(sha_256_constants[i],16),int(w_t[i],2)]) t_2=mod_32_addition([int(e_0(a),2),int(Maj(a,b,c),2)]) h=g g=f f=e e=mod_32_addition([int(d,2),t_1]) d=c c=b b=a a=mod_32_addition([t_1,t_2]) a=bin_32bit(a) e=bin_32bit(e) if i > 15: w_t.append(message_schedule(i,w_t)) t_1=mod_32_addition([int(h,2),int(e_1(e),2),int(Ch(e,f,g),2),int(sha_256_constants[i],16),int(w_t[i],2)]) t_2=mod_32_addition([int(e_0(a),2),int(Maj(a,b,c),2)]) h=g g=f f=e e=mod_32_addition([int(d,2),t_1]) d=c c=b b=a a=mod_32_addition([t_1,t_2]) a=bin_32bit(a) e=bin_32bit(e) hash_0 = mod_32_addition([dec_return_hex(initial_hash_values[0]),int(a,2)]) hash_1 = mod_32_addition([dec_return_hex(initial_hash_values[1]),int(b,2)]) hash_2 = mod_32_addition([dec_return_hex(initial_hash_values[2]),int(c,2)]) hash_3 = mod_32_addition([dec_return_hex(initial_hash_values[3]),int(d,2)]) hash_4 = mod_32_addition([dec_return_hex(initial_hash_values[4]),int(e,2)]) hash_5 = mod_32_addition([dec_return_hex(initial_hash_values[5]),int(f,2)]) hash_6 = mod_32_addition([dec_return_hex(initial_hash_values[6]),int(g,2)]) hash_7 = mod_32_addition([dec_return_hex(initial_hash_values[7]),int(h,2)]) final_hash = (hex_return(hash_0), hex_return(hash_1), hex_return(hash_2), hex_return(hash_3), hex_return(hash_4), hex_return(hash_5), hex_return(hash_6), hex_return(hash_7)) return(final_hash) ```
If you only want the hash value: ``` from hashlib import sha256 data = input('Enter plaintext data: ') output = sha256(data.encode('utf-8')) print(output) ``` Python's hashlib also has SHA-1, SHA-384, SHA-512, and MD5 hash functions.