qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
3,455,208
Surely the compiler knows that it's the last label of the `switch` statement?
2010/08/11
[ "https://Stackoverflow.com/questions/3455208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327528/" ]
It's because in C++ this is what happens: ``` switch(a) { case 1: // do stuff case 2: // do other stuff } ``` If `a` is 1, then - according to C++ rules - both "do stuff" *and* "do other stuff" would happen. So that C++ programmers coming to C# do not get tripped up (and to make code clearer all 'round), C# requires that you explicitly specify whether you want to `break` or fall through to a different label. Now, as for why you need the `break` on the *last* block, that's a simple matter of consistency. It also make re factoring easier: if you move the cases around, you don't suddenly end up with errors because of a missing `break` statement. Also, what happens when you want to add another label, etc, etc.
According to <http://msdn.microsoft.com/en-us/library/06tc147t.aspx> > > You cannot "fall through" any switch section, including the last one. > > > Fall through can be avoided by any of the following: break, goto, or return.
3,455,208
Surely the compiler knows that it's the last label of the `switch` statement?
2010/08/11
[ "https://Stackoverflow.com/questions/3455208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327528/" ]
Having a break after your switch's final case statement is good [defensive programming](http://en.wikipedia.org/wiki/Defensive_programming). If, perhaps in the future, another case statement is added below, it removes the risk of the program's flow *falling through* from the case above.
Consistency. Same reason as being able to have a comma after the last enum definition or the last assignment in an object instantiation statement with braces. And the last case might not always be the last case. It also makes it so there are fewer special cases. And if that's the case, then it is easier to learn, write, or read. Although that adds to the consistency thing.
3,455,208
Surely the compiler knows that it's the last label of the `switch` statement?
2010/08/11
[ "https://Stackoverflow.com/questions/3455208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327528/" ]
Having a break after your switch's final case statement is good [defensive programming](http://en.wikipedia.org/wiki/Defensive_programming). If, perhaps in the future, another case statement is added below, it removes the risk of the program's flow *falling through* from the case above.
When using a `switch`, to `break` is not the only option. You also have the option of going to another case, going to the default case, going to another label, or returning. It is also possible to have multiple cases that have a single implementation body. Since there are up to five options plus the ability to have multiple cases for one implementation, the compiler is not able to simply put in the "correct" answer. You have to choose what you intend to do. It ensures the compiler does the right thing, makes your code clearer, and makes it more difficult to do dumb-programmer-things, like add another case after the "last one", and forget to put in a break/goto/return.
3,455,208
Surely the compiler knows that it's the last label of the `switch` statement?
2010/08/11
[ "https://Stackoverflow.com/questions/3455208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327528/" ]
It's because in C++ this is what happens: ``` switch(a) { case 1: // do stuff case 2: // do other stuff } ``` If `a` is 1, then - according to C++ rules - both "do stuff" *and* "do other stuff" would happen. So that C++ programmers coming to C# do not get tripped up (and to make code clearer all 'round), C# requires that you explicitly specify whether you want to `break` or fall through to a different label. Now, as for why you need the `break` on the *last* block, that's a simple matter of consistency. It also make re factoring easier: if you move the cases around, you don't suddenly end up with errors because of a missing `break` statement. Also, what happens when you want to add another label, etc, etc.
When using a `switch`, to `break` is not the only option. You also have the option of going to another case, going to the default case, going to another label, or returning. It is also possible to have multiple cases that have a single implementation body. Since there are up to five options plus the ability to have multiple cases for one implementation, the compiler is not able to simply put in the "correct" answer. You have to choose what you intend to do. It ensures the compiler does the right thing, makes your code clearer, and makes it more difficult to do dumb-programmer-things, like add another case after the "last one", and forget to put in a break/goto/return.
3,455,208
Surely the compiler knows that it's the last label of the `switch` statement?
2010/08/11
[ "https://Stackoverflow.com/questions/3455208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327528/" ]
Actually **There is one case when you don't have to put break** Consider this code: ``` using System; public class Program { public static void DoStuff() { } public static void DoAnotherStuff() { } public static void Main() { switch(1) { case 1: DoStuff(); break; default: DoAnotherStuff(); } } } ``` Using C# 4.0 compiler it only gives you a nice CS0162: Unreachable code warning It appears that since switch has a constant expression the compiler already knows wich path it's going to execute, then just ignores the dafault label. The cool thing is that if you change switch(1) to switch(2) it no longer compiles because the default label lacks its break. **Edit:** From the [C# Reference](http://msdn.microsoft.com/en-us/library/06tc147t.aspx) > > The requirement in C# is that the end of every switch section, including the final one, is unreachable. Although this requirement usually is met by using a jump statement, the following case also is valid, because the end of the statement list cannot be reached. > > > ``` case 4: while (true) Console.WriteLine("Endless looping. . . ."); ``` That explains why the default does not need a break. In fact any unreacheable label doesn't need a break nor return nor goto
When using a `switch`, to `break` is not the only option. You also have the option of going to another case, going to the default case, going to another label, or returning. It is also possible to have multiple cases that have a single implementation body. Since there are up to five options plus the ability to have multiple cases for one implementation, the compiler is not able to simply put in the "correct" answer. You have to choose what you intend to do. It ensures the compiler does the right thing, makes your code clearer, and makes it more difficult to do dumb-programmer-things, like add another case after the "last one", and forget to put in a break/goto/return.
3,455,208
Surely the compiler knows that it's the last label of the `switch` statement?
2010/08/11
[ "https://Stackoverflow.com/questions/3455208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327528/" ]
Consistency. Same reason as being able to have a comma after the last enum definition or the last assignment in an object instantiation statement with braces. And the last case might not always be the last case. It also makes it so there are fewer special cases. And if that's the case, then it is easier to learn, write, or read. Although that adds to the consistency thing.
As mentioned, you can use default:, but consider case null too. case null: does need a break; case null: iEvaluatedToNothing(); break; If you want to "waterfall" down you can do something like this; ``` switch (deliverMail) { case null: case "": case "Address0": deliverMail0(); goto case "1"; case "1": deliverMail1(); break; } ``` You can use this with breaks as needed, but one is required on the last evaluation.
3,455,208
Surely the compiler knows that it's the last label of the `switch` statement?
2010/08/11
[ "https://Stackoverflow.com/questions/3455208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327528/" ]
Having a break after your switch's final case statement is good [defensive programming](http://en.wikipedia.org/wiki/Defensive_programming). If, perhaps in the future, another case statement is added below, it removes the risk of the program's flow *falling through* from the case above.
According to [this blog post](http://blogs.msdn.com/b/ericlippert/archive/2009/08/13/four-switch-oddities.aspx) by Eric Lippert (Case 2), it allows you to be able to arbitrarily re-order your switch sections without accidentally introducing a breaking change: > > It [the compiler] requires that every switch section, > including the last one, have an > unreachable end point. The purpose of > this rule, and of the no-fall-through > rule in general, is that we want you > to be able to arbitrarily re-order > your switch sections without > accidentally introducing a breaking > change. > > >
3,455,208
Surely the compiler knows that it's the last label of the `switch` statement?
2010/08/11
[ "https://Stackoverflow.com/questions/3455208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327528/" ]
It's because in C++ this is what happens: ``` switch(a) { case 1: // do stuff case 2: // do other stuff } ``` If `a` is 1, then - according to C++ rules - both "do stuff" *and* "do other stuff" would happen. So that C++ programmers coming to C# do not get tripped up (and to make code clearer all 'round), C# requires that you explicitly specify whether you want to `break` or fall through to a different label. Now, as for why you need the `break` on the *last* block, that's a simple matter of consistency. It also make re factoring easier: if you move the cases around, you don't suddenly end up with errors because of a missing `break` statement. Also, what happens when you want to add another label, etc, etc.
According to [this blog post](http://blogs.msdn.com/b/ericlippert/archive/2009/08/13/four-switch-oddities.aspx) by Eric Lippert (Case 2), it allows you to be able to arbitrarily re-order your switch sections without accidentally introducing a breaking change: > > It [the compiler] requires that every switch section, > including the last one, have an > unreachable end point. The purpose of > this rule, and of the no-fall-through > rule in general, is that we want you > to be able to arbitrarily re-order > your switch sections without > accidentally introducing a breaking > change. > > >
126,772
Background ---------- I am writing and using a very simple CGI-based (Perl) content management tool for two pro-bono websites. It provides the website administrator with HTML forms for events where they fill the fields (date, place, title, description, links, etc.) and save it. On that form I allow the administrator to upload an image related to the event. On the HTML page displaying the form, I am also showing a preview of the picture uploaded (HTML img tag). The Problem ----------- The problem happens when the administrator wants to change the picture. He would just have to hit the "browse" button, pick a new picture and press ok. And this works fine. Once the image is uploaded, my back-end CGI handles the upload and reloads the form properly. The problem is that the image shown **does not** get refreshed. The old image is still shown, even though the database holds the right image. I have narrowed it down to the fact that the IMAGE IS CACHED in the web browser. If the administrator hits the RELOAD button in Firefox/Explorer/Safari, everything gets refreshed fine and the new image just appears. My Solution - Not Working ------------------------- I am trying to control the cache by writing a HTTP Expires instruction with a date very far in the past. ``` Expires: Mon, 15 Sep 2003 1:00:00 GMT ``` Remember that I am on the administrative side and I don't really care if the pages takes a little longer to load because they are always expired. But, this does not work either. Notes ----- When uploading an image, its filename is not kept in the database. It is renamed as **Image.jpg** (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes. The webserver is provided by the hosting service/ISP. It uses Apache. Question -------- Is there a way to force the web browser to NOT cache things from this page, not even images? I am juggling with the option to actually "save the filename" with the database. This way, if the image is changed, the src of the IMG tag will also change. However, this requires a lot of changes throughout the site and I rather not do it if I have a better solution. Also, this will still not work if the new image uploaded has the same name (say the image is photoshopped a bit and re-uploaded).
2008/09/24
[ "https://Stackoverflow.com/questions/126772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7984/" ]
I would use: ``` <img src="picture.jpg?20130910043254"> ``` where "20130910043254" is the modification time of the file. > > When uploading an image, its filename is not kept in the database. It is renamed as Image.jpg (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes. > > > I think there are two types of simple solutions: 1) those which come to mind first (straightforward solutions, because they are easy to come up with), 2) those which you end up with after thinking things over (because they are easy to use). Apparently, you won't always benefit if you chose to think things over. But the second options is rather underestimated, I believe. Just think why `php` is so popular ;)
I checked all the answers around the web and the best one seemed to be: (actually it isn't) ``` <img src="image.png?cache=none"> ``` at first. However, if you add **cache=none** parameter (which is static "none" word), it doesn't effect anything, browser still loads from cache. Solution to this problem was: ``` <img src="image.png?nocache=<?php echo time(); ?>"> ``` where you basically add unix timestamp to make the parameter dynamic and no cache, it worked. However, my problem was a little different: I was loading on the fly generated php chart image, and controlling the page with $\_GET parameters. I wanted the image to be read from cache when the URL GET parameter stays the same, and do not cache when the GET parameters change. To solve this problem, I needed to hash $\_GET but since it is array here is the solution: ``` $chart_hash = md5(implode('-', $_GET)); echo "<img src='/images/mychart.png?hash=$chart_hash'>"; ``` **Edit**: Although the above solution works just fine, sometimes you want to serve the cached version UNTIL the file is changed. (with the above solution, it disables the cache for that image completely) So, to serve cached image from browser UNTIL there is a change in the image file use: ``` echo "<img src='/images/mychart.png?hash=" . filemtime('mychart.png') . "'>"; ``` > > filemtime() gets file modification time. > > >
126,772
Background ---------- I am writing and using a very simple CGI-based (Perl) content management tool for two pro-bono websites. It provides the website administrator with HTML forms for events where they fill the fields (date, place, title, description, links, etc.) and save it. On that form I allow the administrator to upload an image related to the event. On the HTML page displaying the form, I am also showing a preview of the picture uploaded (HTML img tag). The Problem ----------- The problem happens when the administrator wants to change the picture. He would just have to hit the "browse" button, pick a new picture and press ok. And this works fine. Once the image is uploaded, my back-end CGI handles the upload and reloads the form properly. The problem is that the image shown **does not** get refreshed. The old image is still shown, even though the database holds the right image. I have narrowed it down to the fact that the IMAGE IS CACHED in the web browser. If the administrator hits the RELOAD button in Firefox/Explorer/Safari, everything gets refreshed fine and the new image just appears. My Solution - Not Working ------------------------- I am trying to control the cache by writing a HTTP Expires instruction with a date very far in the past. ``` Expires: Mon, 15 Sep 2003 1:00:00 GMT ``` Remember that I am on the administrative side and I don't really care if the pages takes a little longer to load because they are always expired. But, this does not work either. Notes ----- When uploading an image, its filename is not kept in the database. It is renamed as **Image.jpg** (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes. The webserver is provided by the hosting service/ISP. It uses Apache. Question -------- Is there a way to force the web browser to NOT cache things from this page, not even images? I am juggling with the option to actually "save the filename" with the database. This way, if the image is changed, the src of the IMG tag will also change. However, this requires a lot of changes throughout the site and I rather not do it if I have a better solution. Also, this will still not work if the new image uploaded has the same name (say the image is photoshopped a bit and re-uploaded).
2008/09/24
[ "https://Stackoverflow.com/questions/126772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7984/" ]
You may write a proxy script for serving images - that's a bit more of work though. Something likes this: HTML: ``` <img src="image.php?img=imageFile.jpg&some-random-number-262376" /> ``` Script: ``` // PHP if( isset( $_GET['img'] ) && is_file( IMG_PATH . $_GET['img'] ) ) { // read contents $f = open( IMG_PATH . $_GET['img'] ); $img = $f.read(); $f.close(); // no-cache headers - complete set // these copied from [php.net/header][1], tested myself - works header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Some time in the past header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); // image related headers header('Accept-Ranges: bytes'); header('Content-Length: '.strlen( $img )); // How many bytes we're going to send header('Content-Type: image/jpeg'); // or image/png etc // actual image echo $img; exit(); } ``` Actually either no-cache headers or random number at image src should be sufficient, but since we want to be bullet proof..
I've found Chrome specifically tries to get clever with the URL arguments solution on images. That method to avoid cache only works *some* of the time. The most reliable solution I've found is to add both a URL argument (E.g. time stamp or file version) **AND** also change the capitalisation of the image file extension in the URL. ``` <img src="picture.jpg"> ``` becomes ``` <img src="picture.JPG?t=current_time"> ```
126,772
Background ---------- I am writing and using a very simple CGI-based (Perl) content management tool for two pro-bono websites. It provides the website administrator with HTML forms for events where they fill the fields (date, place, title, description, links, etc.) and save it. On that form I allow the administrator to upload an image related to the event. On the HTML page displaying the form, I am also showing a preview of the picture uploaded (HTML img tag). The Problem ----------- The problem happens when the administrator wants to change the picture. He would just have to hit the "browse" button, pick a new picture and press ok. And this works fine. Once the image is uploaded, my back-end CGI handles the upload and reloads the form properly. The problem is that the image shown **does not** get refreshed. The old image is still shown, even though the database holds the right image. I have narrowed it down to the fact that the IMAGE IS CACHED in the web browser. If the administrator hits the RELOAD button in Firefox/Explorer/Safari, everything gets refreshed fine and the new image just appears. My Solution - Not Working ------------------------- I am trying to control the cache by writing a HTTP Expires instruction with a date very far in the past. ``` Expires: Mon, 15 Sep 2003 1:00:00 GMT ``` Remember that I am on the administrative side and I don't really care if the pages takes a little longer to load because they are always expired. But, this does not work either. Notes ----- When uploading an image, its filename is not kept in the database. It is renamed as **Image.jpg** (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes. The webserver is provided by the hosting service/ISP. It uses Apache. Question -------- Is there a way to force the web browser to NOT cache things from this page, not even images? I am juggling with the option to actually "save the filename" with the database. This way, if the image is changed, the src of the IMG tag will also change. However, this requires a lot of changes throughout the site and I rather not do it if I have a better solution. Also, this will still not work if the new image uploaded has the same name (say the image is photoshopped a bit and re-uploaded).
2008/09/24
[ "https://Stackoverflow.com/questions/126772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7984/" ]
You must use a unique filename(s). Like this ``` <img src="cars.png?1287361287" alt=""> ``` But this technique means high server usage and bandwidth wastage. Instead, you should use the version number or date. Example: ``` <img src="cars.png?2020-02-18" alt=""> ``` But you want it to never serve image from cache. For this, **if the page does not use page cache**, it is possible with PHP or server side. ``` <img src="cars.png?<?php echo time();?>" alt=""> ``` However, it is still not effective. Reason: Browser cache ... The last but most effective method is Native JAVASCRIPT. This simple code **finds all images** with a "NO-CACHE" class and makes the images almost unique. Put this between script tags. ``` var items = document.querySelectorAll("img.NO-CACHE"); for (var i = items.length; i--;) { var img = items[i]; img.src = img.src + '?' + Date.now(); } ``` USAGE ``` <img class="NO-CACHE" src="https://upload.wikimedia.org/wikipedia/commons/6/6a/JavaScript-logo.png" alt=""> ``` RESULT(s) Like This ``` https://example.com/image.png?1582018163634 ```
I made a PHP script that automatically appends the timestamps on all images and also on links. You just need to include this script in your pages. Enjoy! <http://alv90.altervista.org/how-to-force-the-browser-not-to-cache-images/>
126,772
Background ---------- I am writing and using a very simple CGI-based (Perl) content management tool for two pro-bono websites. It provides the website administrator with HTML forms for events where they fill the fields (date, place, title, description, links, etc.) and save it. On that form I allow the administrator to upload an image related to the event. On the HTML page displaying the form, I am also showing a preview of the picture uploaded (HTML img tag). The Problem ----------- The problem happens when the administrator wants to change the picture. He would just have to hit the "browse" button, pick a new picture and press ok. And this works fine. Once the image is uploaded, my back-end CGI handles the upload and reloads the form properly. The problem is that the image shown **does not** get refreshed. The old image is still shown, even though the database holds the right image. I have narrowed it down to the fact that the IMAGE IS CACHED in the web browser. If the administrator hits the RELOAD button in Firefox/Explorer/Safari, everything gets refreshed fine and the new image just appears. My Solution - Not Working ------------------------- I am trying to control the cache by writing a HTTP Expires instruction with a date very far in the past. ``` Expires: Mon, 15 Sep 2003 1:00:00 GMT ``` Remember that I am on the administrative side and I don't really care if the pages takes a little longer to load because they are always expired. But, this does not work either. Notes ----- When uploading an image, its filename is not kept in the database. It is renamed as **Image.jpg** (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes. The webserver is provided by the hosting service/ISP. It uses Apache. Question -------- Is there a way to force the web browser to NOT cache things from this page, not even images? I am juggling with the option to actually "save the filename" with the database. This way, if the image is changed, the src of the IMG tag will also change. However, this requires a lot of changes throughout the site and I rather not do it if I have a better solution. Also, this will still not work if the new image uploaded has the same name (say the image is photoshopped a bit and re-uploaded).
2008/09/24
[ "https://Stackoverflow.com/questions/126772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7984/" ]
I use [PHP's file modified time function](http://php.net/filemtime), for example: ``` echo <img src='Images/image.png?" . filemtime('Images/image.png') . "' />"; ``` If you change the image then the new image is used rather than the cached one, due to having a different modified timestamp.
I've found Chrome specifically tries to get clever with the URL arguments solution on images. That method to avoid cache only works *some* of the time. The most reliable solution I've found is to add both a URL argument (E.g. time stamp or file version) **AND** also change the capitalisation of the image file extension in the URL. ``` <img src="picture.jpg"> ``` becomes ``` <img src="picture.JPG?t=current_time"> ```
126,772
Background ---------- I am writing and using a very simple CGI-based (Perl) content management tool for two pro-bono websites. It provides the website administrator with HTML forms for events where they fill the fields (date, place, title, description, links, etc.) and save it. On that form I allow the administrator to upload an image related to the event. On the HTML page displaying the form, I am also showing a preview of the picture uploaded (HTML img tag). The Problem ----------- The problem happens when the administrator wants to change the picture. He would just have to hit the "browse" button, pick a new picture and press ok. And this works fine. Once the image is uploaded, my back-end CGI handles the upload and reloads the form properly. The problem is that the image shown **does not** get refreshed. The old image is still shown, even though the database holds the right image. I have narrowed it down to the fact that the IMAGE IS CACHED in the web browser. If the administrator hits the RELOAD button in Firefox/Explorer/Safari, everything gets refreshed fine and the new image just appears. My Solution - Not Working ------------------------- I am trying to control the cache by writing a HTTP Expires instruction with a date very far in the past. ``` Expires: Mon, 15 Sep 2003 1:00:00 GMT ``` Remember that I am on the administrative side and I don't really care if the pages takes a little longer to load because they are always expired. But, this does not work either. Notes ----- When uploading an image, its filename is not kept in the database. It is renamed as **Image.jpg** (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes. The webserver is provided by the hosting service/ISP. It uses Apache. Question -------- Is there a way to force the web browser to NOT cache things from this page, not even images? I am juggling with the option to actually "save the filename" with the database. This way, if the image is changed, the src of the IMG tag will also change. However, this requires a lot of changes throughout the site and I rather not do it if I have a better solution. Also, this will still not work if the new image uploaded has the same name (say the image is photoshopped a bit and re-uploaded).
2008/09/24
[ "https://Stackoverflow.com/questions/126772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7984/" ]
I'm a NEW Coder, but here's what I came up with, to stop the Browser from caching and holding onto my webcam views: ``` <meta Http-Equiv="Cache" content="no-cache"> <meta Http-Equiv="Pragma-Control" content="no-cache"> <meta Http-Equiv="Cache-directive" Content="no-cache"> <meta Http-Equiv="Pragma-directive" Content="no-cache"> <meta Http-Equiv="Cache-Control" Content="no-cache"> <meta Http-Equiv="Pragma" Content="no-cache"> <meta Http-Equiv="Expires" Content="0"> <meta Http-Equiv="Pragma-directive: no-cache"> <meta Http-Equiv="Cache-directive: no-cache"> ``` Not sure what works on what Browser, but it does work for some: IE: Works when webpage is refreshed and when website is revisited (without a refresh). CHROME: Works only when webpage is refreshed (even after a revisit). SAFARI and iPad: Doesn't work, I have to clear the History & Web Data. Any Ideas on SAFARI/ iPad?
Add a time stamp `<img src="picture.jpg?t=<?php echo time();?>">` will always give your file a random number at the end and stop it caching
126,772
Background ---------- I am writing and using a very simple CGI-based (Perl) content management tool for two pro-bono websites. It provides the website administrator with HTML forms for events where they fill the fields (date, place, title, description, links, etc.) and save it. On that form I allow the administrator to upload an image related to the event. On the HTML page displaying the form, I am also showing a preview of the picture uploaded (HTML img tag). The Problem ----------- The problem happens when the administrator wants to change the picture. He would just have to hit the "browse" button, pick a new picture and press ok. And this works fine. Once the image is uploaded, my back-end CGI handles the upload and reloads the form properly. The problem is that the image shown **does not** get refreshed. The old image is still shown, even though the database holds the right image. I have narrowed it down to the fact that the IMAGE IS CACHED in the web browser. If the administrator hits the RELOAD button in Firefox/Explorer/Safari, everything gets refreshed fine and the new image just appears. My Solution - Not Working ------------------------- I am trying to control the cache by writing a HTTP Expires instruction with a date very far in the past. ``` Expires: Mon, 15 Sep 2003 1:00:00 GMT ``` Remember that I am on the administrative side and I don't really care if the pages takes a little longer to load because they are always expired. But, this does not work either. Notes ----- When uploading an image, its filename is not kept in the database. It is renamed as **Image.jpg** (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes. The webserver is provided by the hosting service/ISP. It uses Apache. Question -------- Is there a way to force the web browser to NOT cache things from this page, not even images? I am juggling with the option to actually "save the filename" with the database. This way, if the image is changed, the src of the IMG tag will also change. However, this requires a lot of changes throughout the site and I rather not do it if I have a better solution. Also, this will still not work if the new image uploaded has the same name (say the image is photoshopped a bit and re-uploaded).
2008/09/24
[ "https://Stackoverflow.com/questions/126772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7984/" ]
I checked all the answers around the web and the best one seemed to be: (actually it isn't) ``` <img src="image.png?cache=none"> ``` at first. However, if you add **cache=none** parameter (which is static "none" word), it doesn't effect anything, browser still loads from cache. Solution to this problem was: ``` <img src="image.png?nocache=<?php echo time(); ?>"> ``` where you basically add unix timestamp to make the parameter dynamic and no cache, it worked. However, my problem was a little different: I was loading on the fly generated php chart image, and controlling the page with $\_GET parameters. I wanted the image to be read from cache when the URL GET parameter stays the same, and do not cache when the GET parameters change. To solve this problem, I needed to hash $\_GET but since it is array here is the solution: ``` $chart_hash = md5(implode('-', $_GET)); echo "<img src='/images/mychart.png?hash=$chart_hash'>"; ``` **Edit**: Although the above solution works just fine, sometimes you want to serve the cached version UNTIL the file is changed. (with the above solution, it disables the cache for that image completely) So, to serve cached image from browser UNTIL there is a change in the image file use: ``` echo "<img src='/images/mychart.png?hash=" . filemtime('mychart.png') . "'>"; ``` > > filemtime() gets file modification time. > > >
I've found Chrome specifically tries to get clever with the URL arguments solution on images. That method to avoid cache only works *some* of the time. The most reliable solution I've found is to add both a URL argument (E.g. time stamp or file version) **AND** also change the capitalisation of the image file extension in the URL. ``` <img src="picture.jpg"> ``` becomes ``` <img src="picture.JPG?t=current_time"> ```
126,772
Background ---------- I am writing and using a very simple CGI-based (Perl) content management tool for two pro-bono websites. It provides the website administrator with HTML forms for events where they fill the fields (date, place, title, description, links, etc.) and save it. On that form I allow the administrator to upload an image related to the event. On the HTML page displaying the form, I am also showing a preview of the picture uploaded (HTML img tag). The Problem ----------- The problem happens when the administrator wants to change the picture. He would just have to hit the "browse" button, pick a new picture and press ok. And this works fine. Once the image is uploaded, my back-end CGI handles the upload and reloads the form properly. The problem is that the image shown **does not** get refreshed. The old image is still shown, even though the database holds the right image. I have narrowed it down to the fact that the IMAGE IS CACHED in the web browser. If the administrator hits the RELOAD button in Firefox/Explorer/Safari, everything gets refreshed fine and the new image just appears. My Solution - Not Working ------------------------- I am trying to control the cache by writing a HTTP Expires instruction with a date very far in the past. ``` Expires: Mon, 15 Sep 2003 1:00:00 GMT ``` Remember that I am on the administrative side and I don't really care if the pages takes a little longer to load because they are always expired. But, this does not work either. Notes ----- When uploading an image, its filename is not kept in the database. It is renamed as **Image.jpg** (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes. The webserver is provided by the hosting service/ISP. It uses Apache. Question -------- Is there a way to force the web browser to NOT cache things from this page, not even images? I am juggling with the option to actually "save the filename" with the database. This way, if the image is changed, the src of the IMG tag will also change. However, this requires a lot of changes throughout the site and I rather not do it if I have a better solution. Also, this will still not work if the new image uploaded has the same name (say the image is photoshopped a bit and re-uploaded).
2008/09/24
[ "https://Stackoverflow.com/questions/126772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7984/" ]
I use [PHP's file modified time function](http://php.net/filemtime), for example: ``` echo <img src='Images/image.png?" . filemtime('Images/image.png') . "' />"; ``` If you change the image then the new image is used rather than the cached one, due to having a different modified timestamp.
> > When uploading an image, its filename is not kept in the database. It is renamed as Image.jpg (to simply things out when using it). > > > Change this, and you've fixed your problem. I use timestamps, as with the solutions proposed above: **Image-<timestamp>.jpg** Presumably, whatever problems you're avoiding by keeping the same filename for the image can be overcome, but you don't say what they are.
126,772
Background ---------- I am writing and using a very simple CGI-based (Perl) content management tool for two pro-bono websites. It provides the website administrator with HTML forms for events where they fill the fields (date, place, title, description, links, etc.) and save it. On that form I allow the administrator to upload an image related to the event. On the HTML page displaying the form, I am also showing a preview of the picture uploaded (HTML img tag). The Problem ----------- The problem happens when the administrator wants to change the picture. He would just have to hit the "browse" button, pick a new picture and press ok. And this works fine. Once the image is uploaded, my back-end CGI handles the upload and reloads the form properly. The problem is that the image shown **does not** get refreshed. The old image is still shown, even though the database holds the right image. I have narrowed it down to the fact that the IMAGE IS CACHED in the web browser. If the administrator hits the RELOAD button in Firefox/Explorer/Safari, everything gets refreshed fine and the new image just appears. My Solution - Not Working ------------------------- I am trying to control the cache by writing a HTTP Expires instruction with a date very far in the past. ``` Expires: Mon, 15 Sep 2003 1:00:00 GMT ``` Remember that I am on the administrative side and I don't really care if the pages takes a little longer to load because they are always expired. But, this does not work either. Notes ----- When uploading an image, its filename is not kept in the database. It is renamed as **Image.jpg** (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes. The webserver is provided by the hosting service/ISP. It uses Apache. Question -------- Is there a way to force the web browser to NOT cache things from this page, not even images? I am juggling with the option to actually "save the filename" with the database. This way, if the image is changed, the src of the IMG tag will also change. However, this requires a lot of changes throughout the site and I rather not do it if I have a better solution. Also, this will still not work if the new image uploaded has the same name (say the image is photoshopped a bit and re-uploaded).
2008/09/24
[ "https://Stackoverflow.com/questions/126772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7984/" ]
All the Answers are valid as it works fine. But with that, the browser also creates another file in the cache every time it loads that image with a different URL. So instead of changing the URL by adding some query params to it. So, what we can do is we can update the browser cache using `cache.put` ```js caches.open('YOUR_CACHE_NAME').then(cache => { const url = 'URL_OF_IMAGE_TO_UPDATE' fetch(url).then(res => { cache.put(url, res.clone()) }) }) ``` `cache.put` updates the cache with a new response. for more: <https://developer.mozilla.org/en-US/docs/Web/API/Cache/put>
I made a PHP script that automatically appends the timestamps on all images and also on links. You just need to include this script in your pages. Enjoy! <http://alv90.altervista.org/how-to-force-the-browser-not-to-cache-images/>
126,772
Background ---------- I am writing and using a very simple CGI-based (Perl) content management tool for two pro-bono websites. It provides the website administrator with HTML forms for events where they fill the fields (date, place, title, description, links, etc.) and save it. On that form I allow the administrator to upload an image related to the event. On the HTML page displaying the form, I am also showing a preview of the picture uploaded (HTML img tag). The Problem ----------- The problem happens when the administrator wants to change the picture. He would just have to hit the "browse" button, pick a new picture and press ok. And this works fine. Once the image is uploaded, my back-end CGI handles the upload and reloads the form properly. The problem is that the image shown **does not** get refreshed. The old image is still shown, even though the database holds the right image. I have narrowed it down to the fact that the IMAGE IS CACHED in the web browser. If the administrator hits the RELOAD button in Firefox/Explorer/Safari, everything gets refreshed fine and the new image just appears. My Solution - Not Working ------------------------- I am trying to control the cache by writing a HTTP Expires instruction with a date very far in the past. ``` Expires: Mon, 15 Sep 2003 1:00:00 GMT ``` Remember that I am on the administrative side and I don't really care if the pages takes a little longer to load because they are always expired. But, this does not work either. Notes ----- When uploading an image, its filename is not kept in the database. It is renamed as **Image.jpg** (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes. The webserver is provided by the hosting service/ISP. It uses Apache. Question -------- Is there a way to force the web browser to NOT cache things from this page, not even images? I am juggling with the option to actually "save the filename" with the database. This way, if the image is changed, the src of the IMG tag will also change. However, this requires a lot of changes throughout the site and I rather not do it if I have a better solution. Also, this will still not work if the new image uploaded has the same name (say the image is photoshopped a bit and re-uploaded).
2008/09/24
[ "https://Stackoverflow.com/questions/126772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7984/" ]
From my point of view, disable images caching is a bad idea. At all. The root problem here is - how to force browser to update image, when it has been updated on a server side. Again, from my personal point of view, the best solution is to disable direct access to images. Instead access images via server-side filter/servlet/other similar tools/services. In my case it's a rest service, that returns image and attaches ETag in response. The service keeps hash of all files, if file is changed, hash is updated. It works perfectly in all modern browsers. Yes, it takes time to implement it, but it is worth it. The only exception - are favicons. For some reasons, it does not work. I could not force browser to update its cache from server side. ETags, Cache Control, Expires, Pragma headers, nothing helped. In this case, adding some random/version parameter into url, it seems, is the only solution.
I made a PHP script that automatically appends the timestamps on all images and also on links. You just need to include this script in your pages. Enjoy! <http://alv90.altervista.org/how-to-force-the-browser-not-to-cache-images/>
126,772
Background ---------- I am writing and using a very simple CGI-based (Perl) content management tool for two pro-bono websites. It provides the website administrator with HTML forms for events where they fill the fields (date, place, title, description, links, etc.) and save it. On that form I allow the administrator to upload an image related to the event. On the HTML page displaying the form, I am also showing a preview of the picture uploaded (HTML img tag). The Problem ----------- The problem happens when the administrator wants to change the picture. He would just have to hit the "browse" button, pick a new picture and press ok. And this works fine. Once the image is uploaded, my back-end CGI handles the upload and reloads the form properly. The problem is that the image shown **does not** get refreshed. The old image is still shown, even though the database holds the right image. I have narrowed it down to the fact that the IMAGE IS CACHED in the web browser. If the administrator hits the RELOAD button in Firefox/Explorer/Safari, everything gets refreshed fine and the new image just appears. My Solution - Not Working ------------------------- I am trying to control the cache by writing a HTTP Expires instruction with a date very far in the past. ``` Expires: Mon, 15 Sep 2003 1:00:00 GMT ``` Remember that I am on the administrative side and I don't really care if the pages takes a little longer to load because they are always expired. But, this does not work either. Notes ----- When uploading an image, its filename is not kept in the database. It is renamed as **Image.jpg** (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes. The webserver is provided by the hosting service/ISP. It uses Apache. Question -------- Is there a way to force the web browser to NOT cache things from this page, not even images? I am juggling with the option to actually "save the filename" with the database. This way, if the image is changed, the src of the IMG tag will also change. However, this requires a lot of changes throughout the site and I rather not do it if I have a better solution. Also, this will still not work if the new image uploaded has the same name (say the image is photoshopped a bit and re-uploaded).
2008/09/24
[ "https://Stackoverflow.com/questions/126772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7984/" ]
use **Class="NO-CACHE"** sample html: ``` <div> <img class="NO-CACHE" src="images/img1.jpg" /> <img class="NO-CACHE" src="images/imgLogo.jpg" /> </div> ``` jQuery: ``` $(document).ready(function () { $('.NO-CACHE').attr('src',function () { return $(this).attr('src') + "?a=" + Math.random() }); }); ``` javascript: ``` var nods = document.getElementsByClassName('NO-CACHE'); for (var i = 0; i < nods.length; i++) { nods[i].attributes['src'].value += "?a=" + Math.random(); } ``` Result: src="images/img1.jpg" **=>** src="images/img1.jpg?a=0.08749723793963926"
I made a PHP script that automatically appends the timestamps on all images and also on links. You just need to include this script in your pages. Enjoy! <http://alv90.altervista.org/how-to-force-the-browser-not-to-cache-images/>
46,169,615
I want to delete a file, in case it is locked by another process even though I have set try catch, but the program is still dark cash at fi.Delete(), so how to fix it. > > A first chance exception of type 'System.UnauthorizedAccessException' > occurred in mscorlib.dll > > > Additional information: Access to the path 'H:\J\R\sound.MP4' is > denied. > > > ``` private void GView_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e) { try { string cellValue = GView.Rows[e.RowIndex].Cells["NAME"].Value.ToString(); var confirmResult = MessageBox.Show("delete this item " + cellValue, "Confirm Delete!!", MessageBoxButtons.YesNo); if (confirmResult == DialogResult.Yes) { System.IO.FileInfo fi = new System.IO.FileInfo(cellValue); fi.Delete(); } else { } } catch (UnauthorizedAccessException ex) { MessageBox.Show(ex.Message); } } ```
2017/09/12
[ "https://Stackoverflow.com/questions/46169615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766775/" ]
``` private void GView_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e) { try { string cellValue = GView.Rows[e.RowIndex].Cells["NAME"].Value.ToString(); var confirmResult = MessageBox.Show("delete this item " + cellValue, "Confirm Delete!!", MessageBoxButtons.YesNo); if (confirmResult == DialogResult.Yes) { System.IO.FileInfo fi = new System.IO.FileInfo(cellValue); fi.Delete(); } else { } } catch(System.IO.IOException) { // exception when file is in use or any other } catch (UnauthorizedAccessException ex) { MessageBox.Show(ex.Message); } catch(Exception ex) { // all other } } ```
The user, whose account is used to run your application, must have access to that path There are 2 ways to achieve this: 1. Configure a special application pool for your application, that will run under a user that has necessary permissions (can access admin shares on remote server). So your entire application will run under that account and have all its permissions. 2. Using impersonation to execute parts of your code under another account. This doesn't require any IIS configuration and is more secure and flexible than first way (for example? you can impersonate several accounts in a single application).
46,169,615
I want to delete a file, in case it is locked by another process even though I have set try catch, but the program is still dark cash at fi.Delete(), so how to fix it. > > A first chance exception of type 'System.UnauthorizedAccessException' > occurred in mscorlib.dll > > > Additional information: Access to the path 'H:\J\R\sound.MP4' is > denied. > > > ``` private void GView_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e) { try { string cellValue = GView.Rows[e.RowIndex].Cells["NAME"].Value.ToString(); var confirmResult = MessageBox.Show("delete this item " + cellValue, "Confirm Delete!!", MessageBoxButtons.YesNo); if (confirmResult == DialogResult.Yes) { System.IO.FileInfo fi = new System.IO.FileInfo(cellValue); fi.Delete(); } else { } } catch (UnauthorizedAccessException ex) { MessageBox.Show(ex.Message); } } ```
2017/09/12
[ "https://Stackoverflow.com/questions/46169615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766775/" ]
I read this [article](https://stackoverflow.com/questions/58380/avoiding-first-chance-exception-messages-when-the-exception-is-safely-handled/58392), as suggested by @Keyur PATEL, and figuring out this is a configuration of Visual Studio, I solved it by doing the following: * Navigate to "Debug / Exceptions / Common Language Runtime Exceptions / System" * Scroll down to where "NullReferenceException" is, and uncheck the "throw" checkbox, and check the "user-handled". Thanks for your help
The user, whose account is used to run your application, must have access to that path There are 2 ways to achieve this: 1. Configure a special application pool for your application, that will run under a user that has necessary permissions (can access admin shares on remote server). So your entire application will run under that account and have all its permissions. 2. Using impersonation to execute parts of your code under another account. This doesn't require any IIS configuration and is more secure and flexible than first way (for example? you can impersonate several accounts in a single application).
1,569,678
What I am going after is to be able to do something like this ``` public class Class1 { public delegate CollsionType ValidateDelegate< T >(PlayerState<T> state, Vector2 position, CollsionType boundary); public static ValidateDelegate ValidateMove; public void AnotherFunction< T >(PlayerState< T > state) { //option1 ValidateDelegate.Invoke<T>(state,SomeParameter,SomeParamter2) } } public class Class2<TypeIWant> { public void SomeFunction { //option2 Class1.ValidateMove = new ValidateDelegate<TypeIWant>(functionThatHasCorrectSigniture) } } ``` The trick here is I do not know the type T when the delegate is created in Class1. I only know T when a function is added to the delegate or when the delegate is invoked.
2009/10/15
[ "https://Stackoverflow.com/questions/1569678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/190266/" ]
You're almost there - just make Class1 generic, and the delegate generic: ``` public class Class1<T> { public delegate CollsionType ValidateDelegate<T>(PlayerState<T> state, Vector2 position, CollsionType boundary); public static ValidateDelegate<T> ValidateMove; public void AnotherFunction<T>(PlayerState<T> state) { ValidateDelegate.Invoke<T>(state,SomeParameter,SomeParamter2) } } ``` And specify the type parameter twice - once for the class, and once for the delegate: ``` public class Class2 { public void SomeFunction() { Class1<TypeIWant>.ValidateMove = new ValidateDelegate<TypeIWant>(functionThatHasCorrectSigniture) } } ```
I solved the problem by making the function I was calling on Class 2 static(erasing the need for the delegate) and passing in the generic types of Class2 to the function in Class1 that was calling the function on Class2. There could still be more valid answers to this question. This one just works for me for now because I was able to make the function static. if that was not the case I would still be stuck. And I am still interested in answers that don't require the function to be static or Class1 being Generic as this would open up some options for my project.
1,569,678
What I am going after is to be able to do something like this ``` public class Class1 { public delegate CollsionType ValidateDelegate< T >(PlayerState<T> state, Vector2 position, CollsionType boundary); public static ValidateDelegate ValidateMove; public void AnotherFunction< T >(PlayerState< T > state) { //option1 ValidateDelegate.Invoke<T>(state,SomeParameter,SomeParamter2) } } public class Class2<TypeIWant> { public void SomeFunction { //option2 Class1.ValidateMove = new ValidateDelegate<TypeIWant>(functionThatHasCorrectSigniture) } } ``` The trick here is I do not know the type T when the delegate is created in Class1. I only know T when a function is added to the delegate or when the delegate is invoked.
2009/10/15
[ "https://Stackoverflow.com/questions/1569678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/190266/" ]
Here is the closest I could come to the correct answer to my question. I do admit that it goes against some coding standards(because it uses late binding) but it seems to work. public class Class1 { ``` public delegate CollsionType ValidateDelegate< T >(PlayerState<T> state, Vector2 position, CollsionType boundary); public static Object ValidateMove; public void AnotherFunction< T >(PlayerState< T > state) { ValidateDelegate<T> ValFunction = (ValidateDelegate<T>)ValidateMove; ValFunction.Invoke<T>(state,SomeParameter,SomeParamter2); } ``` } public class Class2 { ``` public void SomeFunction { Class1.ValidateMove = new ValidateDelegate<TypeIWant>(functionThatHasCorrectSigniture) } ``` }
I solved the problem by making the function I was calling on Class 2 static(erasing the need for the delegate) and passing in the generic types of Class2 to the function in Class1 that was calling the function on Class2. There could still be more valid answers to this question. This one just works for me for now because I was able to make the function static. if that was not the case I would still be stuck. And I am still interested in answers that don't require the function to be static or Class1 being Generic as this would open up some options for my project.
24,604,626
I want to check if the user ticked the checkbox BEFORE the file is uploaded to the server, so I created a validation on UploadStart with an alert message. I put the break point at this line and it did go through, but the alert message still didn't show. (AjaxFileUpload control is not put under any UpdatePanel) ``` protected void AjaxFileUpload3_UploadStart(object sender, AjaxControlToolkit.AjaxFileUploadStartEventArgs e) { if(CheckBox1.Checked == false) { System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Please accept our TnC, bla bla bla');", true); return; } } ``` I don't want to use javascript, am I doing this right? Please advise me.
2014/07/07
[ "https://Stackoverflow.com/questions/24604626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3431239/" ]
You seem to be misunderstanding what [constants](http://php.net/manual/en/language.constants.php) actually are. In the specific case of `OCI_ASSOC` (and other [OCI constants](http://php.net/manual/en/oci8.constants.php)) it represents a simple integer value. This can be demonstrated by the output of `var_dump(OCI_ASSOC);` which is `int(1)`. Combining constants such as `OCI_ASSOC+OCI_RETURN_NULLS` is a simple addition operation with the result of `int(5)`. To make your function work you should simply pass the constants directly by removing the surrounding apostrophes: ``` db_single_select($conn, $select, $table_name, $condition, OCI_ASSOC); ``` ***SECURITY WARNING:*** Your code is vulnerable to [SQL Injection](http://en.wikipedia.org/wiki/SQL_injection) (also see what the [PHP manual says about it](http://php.net/manual/en/security.database.sql-injection.php)). You should use [parameter binding](http://php.net/manual/en/function.oci-bind-by-name.php) to mitigate the attack possibilities.
You have to be sure if the connection is succeeded or not. check the return if it's *resource* value of `$conn` in your code. wish this help you.
35,208,715
I malloc'd an array of structures called "locations". In said structure is an element called "country". I created a string you can see below that holds "United States" in it. I malloc'd space to hold the string (it's required that I do so) and attempted to use strncpy to place the string into the malloced space. This works elsewhere in my code with strings that are read in from a file, but not for this string which I declared directly. When I print out the result, it says the structure is holding "United State(error symbol)" So in place of the s at the end of "United States" is the error symbol. The error symbol looks like a small box of ones and zeros. ``` char *US_string = "United States"; locations[0].country = malloc(sizeof(US_string)); strncpy(locations[0].country, US_string, strlen(US_string)); ``` Anyone know what's going on? Thanks for any help! And please try not to be too hard on me, I'm a first year CS major. Just trying to get this bug out of a lab.
2016/02/04
[ "https://Stackoverflow.com/questions/35208715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5403466/" ]
You can do something like this (maybe avoiding the recursion): ``` #include <iostream> #include <vector> #include <algorithm> using std::cout; using std::vector; void perm( const vector<int> &v, vector<vector<int>> &p, vector<int> &t, int k, int d) { for ( int i = k; i < v.size(); ++i ) { // skip the repeted value if ( i != k && v[i] == v[i-1]) continue; t.push_back(v[i]); if ( d > 0 ) perm(v,p,t,i+1,d-1); else p.push_back(t); t.pop_back(); } } int main() { int r = 3; vector<int> row {40, 40, 40, 50, 50, 60, 100}; vector<vector<int>> pp; vector<int> pe; std::sort(row.begin(),row.end()); // that's necessary perm(row,pp,pe,0,r-1); cout << pp.size() << '\n'; for ( auto & v : pp ) { for ( int i : v ) { cout << ' ' << i; } cout << '\n'; } return 0; } ``` Which outputs: ``` 11 40 40 40 40 40 50 40 40 60 40 40 100 40 50 50 40 50 60 40 50 100 40 60 100 50 50 60 50 50 100 50 60 100 ``` I know, it's far from efficient, but if you get the idea you may come out with a better implementation.
Here is a class I once wrote in my university times to handle bosons. It's quite long, but it's generally usable and seems to work well. Additionally, it also gives ranking and unranking functionality. Hope that helps -- but don't ever ask me what I was doing back then ... ;-) ``` struct SymmetricIndex { using StateType = std::vector<int>; using IntegerType = int; int M; int N; StateType Nmax; StateType Nmin; IntegerType _size; std::vector<IntegerType> store; StateType state; IntegerType _index; SymmetricIndex() = default; SymmetricIndex(int _M, int _N, int _Nmax = std::numeric_limits<int>::max(), int _Nmin = 0) : SymmetricIndex(_M, _N, std::vector<int>(_M + 1, std::min(_Nmax, _N)), StateType(_M + 1, std::max(_Nmin, 0))) {} SymmetricIndex(int _M, int _N, StateType const& _Nmax, StateType const& _Nmin) : N(_N) , M(_M) , Nmax(_Nmax) , Nmin(_Nmin) , store(addressArray()) , state(M) , _index(0) { reset(); _size = W(M, N); } friend std::ostream& operator<<(std::ostream& os, SymmetricIndex const& sym); SymmetricIndex& reset() { return setBegin(); } bool setBegin(StateType& state, StateType const& Nmax, StateType const& Nmin) const { int n = N; for (int i = 0; i<M; ++i) { state[i] = Nmin[i]; n -= Nmin[i]; } for (int i = 0; i<M; ++i) { state[i] = std::min(n + Nmin[i], Nmax[i]); n -= Nmax[i] - Nmin[i]; if (n <= 0) break; } return true; } SymmetricIndex& setBegin() { setBegin(state, Nmax, Nmin); _index = 0; return *this; } bool isBegin() const { return _index==0; } bool setEnd(StateType& state, StateType const& Nmax, StateType const& Nmin) const { int n = N; for (int i = 0; i < M; ++i) { state[i] = Nmin[i]; n -= Nmin[i]; } for (int i = M - 1; i >= 0; --i) { state[i] = std::min(n + Nmin[i], Nmax[i]); n -= Nmax[i] - Nmin[i]; if (n <= 0) break; } return true; } SymmetricIndex& setEnd() { setEnd(state, Nmax, Nmin); _index = _size - 1; return *this; } bool isEnd() const { return _index == _size-1; } IntegerType index() const { return _index; } IntegerType rank(StateType const& state) const { IntegerType ret = 0; int n = 0; for (int i = 0; i < M; ++i) { n += state[i]; for (int k = Nmin[i]; k < state[i]; ++k) ret += store[(n - k) * M + i]; } return ret; } IntegerType rank() const { return rank(state); } StateType unrank(IntegerType rank) const { StateType ret(M); int n = N; for (int i = M-1; i >= 0; --i) { int ad = 0; int k = std::min(Nmax[i] - 1, n); for (int j = Nmin[i]; j <= k; ++j) ad+=store[(n - j) * M + i]; while (ad > rank && k >= Nmin[i]) { ad -= store[(n - k) * M + i]; --k; } rank -= ad; ret[i] = k+1; n -= ret[i]; if (n <= 0) { return ret; } } return ret; } IntegerType size() const { return _size; } operator StateType& () { return state; } auto operator[](int i) -> StateType::value_type& { return state[i]; } operator StateType const& () const { return state; } auto operator[](int i) const -> StateType::value_type const& { return state[i]; } bool nextState(StateType& state, StateType const& Nmax, StateType const& Nmin) const { //co-lexicographical ordering with Nmin and Nmax: // (1) find first position which can be decreased // then we have state[k] = Nmin[k] for k in [0,pos] int pos = M - 1; for (int k = 0; k < M - 1; ++k) { if (state[k] > Nmin[k]) { pos = k; break; } } // if nothing found to decrease, return if (pos == M - 1) { return false; } // (2) find first position after pos which can be increased // then we have state[k] = Nmin[k] for k in [0,pos] int next = 0; for (int k = pos + 1; k < M; ++k) { if (state[k] < Nmax[k]) { next = k; break; } } if (next == 0) { return false; } --state[pos]; ++state[next]; // (3) get occupation in [pos,next-1] and set to Nmin[k] int n = 0; for (int k = pos; k < next; ++k) { n += state[k] - Nmin[k]; state[k] = Nmin[k]; } // (4) fill up from the start for (int i = 0; i<M; ++i) { if (n <= 0) break; int add = std::min(n, Nmax[i] - state[i]); state[i] += add; n -= add; } return true; } SymmetricIndex& operator++() { bool inc = nextState(state, Nmax, Nmin); if (inc) ++_index; return *this; } SymmetricIndex operator++(int) { auto ret = *this; this->operator++(); return ret; } bool previousState(StateType& state, StateType const& Nmax, StateType const& Nmin) const { ////co-lexicographical ordering with Nmin and Nmax: // (1) find first position which can be increased // then we have state[k] = Nmax[k] for k in [0,pos-1] int pos = M - 1; for (int k = 0; k < M - 1; ++k) { if (state[k] < Nmax[k]) { pos = k; break; } } // if nothing found to increase, return if (pos == M - 1) { return false; } // (2) find first position after pos which can be decreased // then we have state[k] = Nmin[k] for k in [pos+1,next] int next = 0; for (int k = pos + 1; k < M; ++k) { if (state[k] > Nmin[k]) { next = k; break; } } if (next == 0) { return false; } ++state[pos]; --state[next]; int n = 0; for (int k = 0; k <= pos; ++k) { n += state[k] - Nmin[k]; state[k] = Nmin[k]; } if (n == 0) { return true; } for (int i = next-1; i>=0; --i) { int add = std::min(n, Nmax[i] - state[i]); state[i] += add; n -= add; if (n <= 0) break; } return true; } SymmetricIndex operator--() { bool dec = previousState(state, Nmax, Nmin); if (dec) --_index; return *this; } SymmetricIndex operator--(int) { auto ret = *this; this->operator--(); return ret; } int multinomial() const { auto v = const_cast<std::remove_reference<decltype(state)>::type&>(state); return multinomial(v); } int multinomial(StateType& state) const { int ret = 1; int n = state[0]; for (int i = 1; i < M; ++i) { n += state[i]; ret *= binomial(n, state[i]); } return ret; } SymmetricIndex& random(StateType const& _Nmin) { static std::mt19937 rng; state = _Nmin; int n = std::accumulate(std::begin(state), std::end(state), 0); auto weight = [&](int i) { return state[i] < Nmax[i] ? 1 : 0; }; for (int i = n; i < N; ++i) { std::discrete_distribution<int> d(N, 0, N, weight); ++state[d(rng)]; } _index = rank(); return *this; } SymmetricIndex& random() { return random(Nmin); } private: IntegerType W(int m, int n) const { if (m < 0 || n < 0) return 0; else if (m == 0 && n == 0) return 1; else if (m == 0 && n > 0) return 0; //else if (m > 0 && n < Nmin[m-1]) return 0; else { //static std::map<std::tuple<int, int>, IntegerType> memo; //auto it = memo.find(std::make_tuple(k, m)); //if (it != std::end(memo)) //{ // return it->second; //} IntegerType ret = 0; for (int i = Nmin[m-1]; i <= std::min(Nmax[m-1], n); ++i) ret += W(m - 1, n - i); //memo[std::make_tuple(k, m)] = ret; return ret; } } IntegerType binomial(int m, int n) const { static std::vector<int> store; if (store.empty()) { std::function<IntegerType(int, int)> bin = [](int n, int k) { int res = 1; if (k > n - k) k = n - k; for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; }; store.resize(M*M); for (int i = 0; i < M; ++i) { for (int j = 0; j < M; ++j) { store[i*M + j] = bin(i, j); } } } return store[m*M + n]; } auto addressArray() const -> std::vector<int> { std::vector<int> ret((N + 1) * M); for (int n = 0; n <= N; ++n) { for (int m = 0; m < M; ++m) { ret[n*M + m] = W(m, n); } } return ret; } }; std::ostream& operator<<(std::ostream& os, SymmetricIndex const& sym) { for (auto const& i : sym.state) { os << i << " "; } return os; } ``` Use it like ``` int main() { int M=4; int N=3; std::vector<int> Nmax(M, N); std::vector<int> Nmin(M, 0); Nmax[0]=3; Nmax[1]=2; Nmax[2]=1; Nmax[3]=1; SymmetricIndex sym(M, N, Nmax, Nmin); while(!sym.isEnd()) { std::cout<<sym<<" "<<sym.rank()<<std::endl; ++sym; } std::cout<<sym<<" "<<sym.rank()<<std::endl; } ``` This will output ``` 3 0 0 0 0 (corresponds to {40,40,40}) 2 1 0 0 1 (-> {40,40,50}) 1 2 0 0 2 (-> {40,50,50}) 2 0 1 0 3 ... 1 1 1 0 4 0 2 1 0 5 2 0 0 1 6 1 1 0 1 7 0 2 0 1 8 1 0 1 1 9 0 1 1 1 10 (-> {50,60,100}) ``` [DEMO](http://coliru.stacked-crooked.com/a/5439f704e014d7eb) Note that I assumed here an ascending mapping of your set elements (i.e. the number 40's is given by index 0, the number of 50's by index 1, and so on). --- --- More precisely: Turn your list into a `map<std::vector<int>, int>` like ``` std::vector<int> v{40,40,40,50,50,60,100}; std::map<int, int> m; for(auto i : v) { ++m[i]; } ``` Then use ``` int N = 3; int M = m.size(); std::vector<int> Nmin(M,0); std::vector<int> Nmax; std::vector<int> val; for(auto i : m) { Nmax.push_back(m.second); val.push_back(m.first); } SymmetricIndex sym(M, N, Nmax, Nmin); ``` as input to the `SymmetricIndex` class. To print the output, use ``` while(!sym.isEnd()) { for(int i=0; i<M; ++i) { for(int j = 0; j<sym[i]; ++j) { std::cout<<val[i]<<" "; } } std::cout<<std::endl; } for(int i=0; i<M; ++i) { for(int j = 0; j<sym[i]; ++j) { std::cout<<val[i]<<" "; } } std::cout<<std::endl; ``` All untested, but it should give the idea.
35,208,715
I malloc'd an array of structures called "locations". In said structure is an element called "country". I created a string you can see below that holds "United States" in it. I malloc'd space to hold the string (it's required that I do so) and attempted to use strncpy to place the string into the malloced space. This works elsewhere in my code with strings that are read in from a file, but not for this string which I declared directly. When I print out the result, it says the structure is holding "United State(error symbol)" So in place of the s at the end of "United States" is the error symbol. The error symbol looks like a small box of ones and zeros. ``` char *US_string = "United States"; locations[0].country = malloc(sizeof(US_string)); strncpy(locations[0].country, US_string, strlen(US_string)); ``` Anyone know what's going on? Thanks for any help! And please try not to be too hard on me, I'm a first year CS major. Just trying to get this bug out of a lab.
2016/02/04
[ "https://Stackoverflow.com/questions/35208715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5403466/" ]
Combinations by definition do not respect order. This frees us to arrange the numbers in any order we see fit. Most notably we can rely on to provide a combination rank. Certainly the most logical way to rank combinations is in sorted order, so we'll be depending upon our inputs being sorted. There is already precedent for this in the standard library. For example [`lower_bound`](http://en.cppreference.com/w/cpp/algorithm/lower_bound) which we will actually use in this solution. When used generally this may however require the user to sort before passing. The function we will write to do this will take in iterators to the sorted collection which the next combination is to be drawn from, and iterators to the current combination. We'd also need the size but that can be derived from the distance between the combination's iterators. ``` template <typename InputIt, typename OutputIt> bool next_combination(InputIt inFirst, InputIt inLast, OutputIt outFirst, OutputIt outLast) { assert(distance(inFirst, inLast) >= distance(outFirst, outLast)); const auto front = make_reverse_iterator(outFirst); const auto back = make_reverse_iterator(outLast); auto it = mismatch(back, front, make_reverse_iterator(inLast)).first; const auto result = it != front; if (result) { auto ub = upper_bound(inFirst, inLast, *it); copy(ub, next(ub, distance(back, it) + 1), next(it).base()); } return result; } ``` This function is written in the format of the other algorithm functions, so any container that supports bidirectional iterators can be used with it. For our example though we'll use: `const vector<unsigned int> row{ 40U, 40U, 40U, 50U, 50U, 60U, 100U };` which is, necessarily, sorted: ``` vector<unsigned int> it{ row.cbegin(), next(row.cbegin(), 3) }; do { copy(it.cbegin(), it.cend(), ostream_iterator<unsigned int>(cout, " ")); cout << endl; } while(next_combination(row.cbegin(), row.cend(), it.begin(), it.end())); ``` [`Live Example`](http://ideone.com/hThiuK) --- After writing this answer I've done a bit more research and found [N2639](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2639.pdf) which proposes a standardized `next_combination`, which was: > > * Actively under consideration for a future TR, [when work on TR2 was deferred pending](https://stackoverflow.com/q/27069548/2642059) > * Viewed positively at the time > * Due at least one more revision before any adoption > * Needed some reworking to reflect the addition of C++11 language facilities > > > [[Source](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3371.html)] Using N2639's reference implementation requires mutability, so we'll use: `vector<unsigned int> row{ 40U, 40U, 40U, 50U, 50U, 60U, 100U };`. And our example code becomes: ``` vector<unsigned int>::iterator it = next(row.begin(), 3); do { copy(row.begin(), it, ostream_iterator<unsigned int>(cout, " ")); cout << endl; } while(next_combination(row.begin(), it, row.end())); ``` [`Live Example`](http://ideone.com/SjOcy0)
Here is a class I once wrote in my university times to handle bosons. It's quite long, but it's generally usable and seems to work well. Additionally, it also gives ranking and unranking functionality. Hope that helps -- but don't ever ask me what I was doing back then ... ;-) ``` struct SymmetricIndex { using StateType = std::vector<int>; using IntegerType = int; int M; int N; StateType Nmax; StateType Nmin; IntegerType _size; std::vector<IntegerType> store; StateType state; IntegerType _index; SymmetricIndex() = default; SymmetricIndex(int _M, int _N, int _Nmax = std::numeric_limits<int>::max(), int _Nmin = 0) : SymmetricIndex(_M, _N, std::vector<int>(_M + 1, std::min(_Nmax, _N)), StateType(_M + 1, std::max(_Nmin, 0))) {} SymmetricIndex(int _M, int _N, StateType const& _Nmax, StateType const& _Nmin) : N(_N) , M(_M) , Nmax(_Nmax) , Nmin(_Nmin) , store(addressArray()) , state(M) , _index(0) { reset(); _size = W(M, N); } friend std::ostream& operator<<(std::ostream& os, SymmetricIndex const& sym); SymmetricIndex& reset() { return setBegin(); } bool setBegin(StateType& state, StateType const& Nmax, StateType const& Nmin) const { int n = N; for (int i = 0; i<M; ++i) { state[i] = Nmin[i]; n -= Nmin[i]; } for (int i = 0; i<M; ++i) { state[i] = std::min(n + Nmin[i], Nmax[i]); n -= Nmax[i] - Nmin[i]; if (n <= 0) break; } return true; } SymmetricIndex& setBegin() { setBegin(state, Nmax, Nmin); _index = 0; return *this; } bool isBegin() const { return _index==0; } bool setEnd(StateType& state, StateType const& Nmax, StateType const& Nmin) const { int n = N; for (int i = 0; i < M; ++i) { state[i] = Nmin[i]; n -= Nmin[i]; } for (int i = M - 1; i >= 0; --i) { state[i] = std::min(n + Nmin[i], Nmax[i]); n -= Nmax[i] - Nmin[i]; if (n <= 0) break; } return true; } SymmetricIndex& setEnd() { setEnd(state, Nmax, Nmin); _index = _size - 1; return *this; } bool isEnd() const { return _index == _size-1; } IntegerType index() const { return _index; } IntegerType rank(StateType const& state) const { IntegerType ret = 0; int n = 0; for (int i = 0; i < M; ++i) { n += state[i]; for (int k = Nmin[i]; k < state[i]; ++k) ret += store[(n - k) * M + i]; } return ret; } IntegerType rank() const { return rank(state); } StateType unrank(IntegerType rank) const { StateType ret(M); int n = N; for (int i = M-1; i >= 0; --i) { int ad = 0; int k = std::min(Nmax[i] - 1, n); for (int j = Nmin[i]; j <= k; ++j) ad+=store[(n - j) * M + i]; while (ad > rank && k >= Nmin[i]) { ad -= store[(n - k) * M + i]; --k; } rank -= ad; ret[i] = k+1; n -= ret[i]; if (n <= 0) { return ret; } } return ret; } IntegerType size() const { return _size; } operator StateType& () { return state; } auto operator[](int i) -> StateType::value_type& { return state[i]; } operator StateType const& () const { return state; } auto operator[](int i) const -> StateType::value_type const& { return state[i]; } bool nextState(StateType& state, StateType const& Nmax, StateType const& Nmin) const { //co-lexicographical ordering with Nmin and Nmax: // (1) find first position which can be decreased // then we have state[k] = Nmin[k] for k in [0,pos] int pos = M - 1; for (int k = 0; k < M - 1; ++k) { if (state[k] > Nmin[k]) { pos = k; break; } } // if nothing found to decrease, return if (pos == M - 1) { return false; } // (2) find first position after pos which can be increased // then we have state[k] = Nmin[k] for k in [0,pos] int next = 0; for (int k = pos + 1; k < M; ++k) { if (state[k] < Nmax[k]) { next = k; break; } } if (next == 0) { return false; } --state[pos]; ++state[next]; // (3) get occupation in [pos,next-1] and set to Nmin[k] int n = 0; for (int k = pos; k < next; ++k) { n += state[k] - Nmin[k]; state[k] = Nmin[k]; } // (4) fill up from the start for (int i = 0; i<M; ++i) { if (n <= 0) break; int add = std::min(n, Nmax[i] - state[i]); state[i] += add; n -= add; } return true; } SymmetricIndex& operator++() { bool inc = nextState(state, Nmax, Nmin); if (inc) ++_index; return *this; } SymmetricIndex operator++(int) { auto ret = *this; this->operator++(); return ret; } bool previousState(StateType& state, StateType const& Nmax, StateType const& Nmin) const { ////co-lexicographical ordering with Nmin and Nmax: // (1) find first position which can be increased // then we have state[k] = Nmax[k] for k in [0,pos-1] int pos = M - 1; for (int k = 0; k < M - 1; ++k) { if (state[k] < Nmax[k]) { pos = k; break; } } // if nothing found to increase, return if (pos == M - 1) { return false; } // (2) find first position after pos which can be decreased // then we have state[k] = Nmin[k] for k in [pos+1,next] int next = 0; for (int k = pos + 1; k < M; ++k) { if (state[k] > Nmin[k]) { next = k; break; } } if (next == 0) { return false; } ++state[pos]; --state[next]; int n = 0; for (int k = 0; k <= pos; ++k) { n += state[k] - Nmin[k]; state[k] = Nmin[k]; } if (n == 0) { return true; } for (int i = next-1; i>=0; --i) { int add = std::min(n, Nmax[i] - state[i]); state[i] += add; n -= add; if (n <= 0) break; } return true; } SymmetricIndex operator--() { bool dec = previousState(state, Nmax, Nmin); if (dec) --_index; return *this; } SymmetricIndex operator--(int) { auto ret = *this; this->operator--(); return ret; } int multinomial() const { auto v = const_cast<std::remove_reference<decltype(state)>::type&>(state); return multinomial(v); } int multinomial(StateType& state) const { int ret = 1; int n = state[0]; for (int i = 1; i < M; ++i) { n += state[i]; ret *= binomial(n, state[i]); } return ret; } SymmetricIndex& random(StateType const& _Nmin) { static std::mt19937 rng; state = _Nmin; int n = std::accumulate(std::begin(state), std::end(state), 0); auto weight = [&](int i) { return state[i] < Nmax[i] ? 1 : 0; }; for (int i = n; i < N; ++i) { std::discrete_distribution<int> d(N, 0, N, weight); ++state[d(rng)]; } _index = rank(); return *this; } SymmetricIndex& random() { return random(Nmin); } private: IntegerType W(int m, int n) const { if (m < 0 || n < 0) return 0; else if (m == 0 && n == 0) return 1; else if (m == 0 && n > 0) return 0; //else if (m > 0 && n < Nmin[m-1]) return 0; else { //static std::map<std::tuple<int, int>, IntegerType> memo; //auto it = memo.find(std::make_tuple(k, m)); //if (it != std::end(memo)) //{ // return it->second; //} IntegerType ret = 0; for (int i = Nmin[m-1]; i <= std::min(Nmax[m-1], n); ++i) ret += W(m - 1, n - i); //memo[std::make_tuple(k, m)] = ret; return ret; } } IntegerType binomial(int m, int n) const { static std::vector<int> store; if (store.empty()) { std::function<IntegerType(int, int)> bin = [](int n, int k) { int res = 1; if (k > n - k) k = n - k; for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; }; store.resize(M*M); for (int i = 0; i < M; ++i) { for (int j = 0; j < M; ++j) { store[i*M + j] = bin(i, j); } } } return store[m*M + n]; } auto addressArray() const -> std::vector<int> { std::vector<int> ret((N + 1) * M); for (int n = 0; n <= N; ++n) { for (int m = 0; m < M; ++m) { ret[n*M + m] = W(m, n); } } return ret; } }; std::ostream& operator<<(std::ostream& os, SymmetricIndex const& sym) { for (auto const& i : sym.state) { os << i << " "; } return os; } ``` Use it like ``` int main() { int M=4; int N=3; std::vector<int> Nmax(M, N); std::vector<int> Nmin(M, 0); Nmax[0]=3; Nmax[1]=2; Nmax[2]=1; Nmax[3]=1; SymmetricIndex sym(M, N, Nmax, Nmin); while(!sym.isEnd()) { std::cout<<sym<<" "<<sym.rank()<<std::endl; ++sym; } std::cout<<sym<<" "<<sym.rank()<<std::endl; } ``` This will output ``` 3 0 0 0 0 (corresponds to {40,40,40}) 2 1 0 0 1 (-> {40,40,50}) 1 2 0 0 2 (-> {40,50,50}) 2 0 1 0 3 ... 1 1 1 0 4 0 2 1 0 5 2 0 0 1 6 1 1 0 1 7 0 2 0 1 8 1 0 1 1 9 0 1 1 1 10 (-> {50,60,100}) ``` [DEMO](http://coliru.stacked-crooked.com/a/5439f704e014d7eb) Note that I assumed here an ascending mapping of your set elements (i.e. the number 40's is given by index 0, the number of 50's by index 1, and so on). --- --- More precisely: Turn your list into a `map<std::vector<int>, int>` like ``` std::vector<int> v{40,40,40,50,50,60,100}; std::map<int, int> m; for(auto i : v) { ++m[i]; } ``` Then use ``` int N = 3; int M = m.size(); std::vector<int> Nmin(M,0); std::vector<int> Nmax; std::vector<int> val; for(auto i : m) { Nmax.push_back(m.second); val.push_back(m.first); } SymmetricIndex sym(M, N, Nmax, Nmin); ``` as input to the `SymmetricIndex` class. To print the output, use ``` while(!sym.isEnd()) { for(int i=0; i<M; ++i) { for(int j = 0; j<sym[i]; ++j) { std::cout<<val[i]<<" "; } } std::cout<<std::endl; } for(int i=0; i<M; ++i) { for(int j = 0; j<sym[i]; ++j) { std::cout<<val[i]<<" "; } } std::cout<<std::endl; ``` All untested, but it should give the idea.
4,246
I frequent the Electronics Stack Exchange and try to edit questions often which need a little bit of clean up. I am puzzled by a couple of recurring patterns by question authors: 1. failure to capitalize "I," the personal pronoun (even though they capitalize the first word of sentences), and 2. failure to place spaces before opening parenthesis, or around other punctuation. Some examples (from questions I've edited): > > * "up to 1.3V-ish if i dont hook them up to the controller..." > * "I prefer the simplest way(i wonder if its by pre defined software)" > * "I am curious to know about why cant i have controller which has more than ISR and also ,instead of interrupts at timer overflow,why cant it interrupt at its period match." > > > I find this kind of sloppy writing frustrating and often difficult to read. I realize that most of the authors of these questions are not native English speakers, so I expect some grammar issues, which I'm happy to try to improve. Forgive my naivety, but are we simply attracting people of a language or culture where punctuation and capitalization are not used, making these concepts difficult for people to grasp? I believe we have a large percentage of India natives based on usernames. Is there any way to improve the quality of these posts other than editing? It would be nice to educate somewhat, and I feel editing questions go unnoticed by the author, and creates busywork for the rest of us.
2013/10/23
[ "https://english.meta.stackexchange.com/questions/4246", "https://english.meta.stackexchange.com", "https://english.meta.stackexchange.com/users/2241/" ]
This is a bit of a cheeky "answer", but maybe we could change the tag on this question from "discussion" to "feature request"... > > Can we have a pop-up warning whenever uncapitalised **i** is used in the ***Ask Question*** screen? > > >
> > Forgive my naivety, but are we simply attracting people of a language or culture where punctuation and capitalization are not used, making these concepts difficult for people to grasp? > > > I see punctuation and capitalization going downhill across the board, so I don't think it has anything to do with the types of people we're attracting. I also don't think it has anything to do with native vs. non-native speakers. I would attribute it to a combination of dwindling education and a general laziness about grammar/punctuation that is at least abetted by (if not outright caused by) communication on mobile devices. > > Is there any way to improve the quality of these posts other than editing? > > > Well, there's always FumbleFingers' cheeky feature request. :) Some sort of notification when one's post has been edited has been bandied about as another feature request, which would also increase visibility. The browsers have as-you-type spell-checking, but a grammar checker is probably a bit much to hope for. Otherwise, I think you're probably doing the best you can by editing.
52,529
I am extending the width of my stairs, and need to remove the existing sub treads and risers. They appear to be glued (construction adhesive I'm guessing because it is brown) and nailed. Is this going to destroy the stair stringer when I remove them? In case it is helpful, the reason why I am removing them is that I want to install new, wider subtreads and risers so that the wood flooring that is attached to them has a continuous surface. The new wider subtreads and risers would be attached to two new trus joist stringers that will be installed where the previous pony/cheek wall was (where you see the exposed 2x4s in the images below). An alternative would be to just add new subtreads/risers for the additional width of the stairs, and make sure that they are level. But I think that is risky because there would be effectively 2 separate surfaces/platforms that the finished treads and risers would be attached to, which could lead to problems in terms of wood movement, etc. I'm trying to decide which is the less risky path. Images ![Picture of Stairs Existing condition](https://i.imgur.com/Ml3lktt.jpg) ![Sketchup drawing showing existing and new](https://i.imgur.com/iBCarTe.png) ![Detail showing subtreads and risers attached to stringer](https://i.imgur.com/V6KFeBo.jpg)
2014/11/09
[ "https://diy.stackexchange.com/questions/52529", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/27245/" ]
I think the least invasive way to handle this is to add two more stingers, one right against the existing stairs(essentially just a nailer) and one out at the ultimate width of the new treads. This way you don't have to remove the old sub-treads/risers or change the height of your treads, which would cause you grief when you get to the top of your staircase. Once you've got your new stringers in just apply sub-treads and riser to match the existing construction and you're good to go. The bigger problem is that no matter how you construct it, the landing or the the lower staircase will have to be modified to make the intersection work properly. ![enter image description here](https://i.stack.imgur.com/UQKdj.jpg) This illustration shows how the problem could be fixed by lengthening the landing and pushing the lower stairs out (assuming you can do this). You could accomplish the same effect by pushing the landing to the right but it looks like your landing is captured on that side in the pictures. Although this fixes the stairs the railing system will still have an unusual transition but it's not too bad depending on how far you need to extend your treads.
If you used 1" solid oak stair treads they could float that distance; you're going to use hardwood flooring? [stair-treads.com](http://www.stair-treads.com/red-oak-treads) ![enter image description here](https://i.stack.imgur.com/85IRsm.jpg) Stair treads could be directly applied to the existing sub, so long as it will still be an acceptable rise. Continue with hardwood on the second floor to meet the new landing height, transitioning back down further into the hallway if necessary. To answer your question; **it's entirely possible** and I'd expect at least a few of the stringers' beds to split-off unevenly. Prepare for having to make new stringers or at least repairing them; otherwise leave it alone.
57,316,337
I have accidentally committed a password to a BitBucket git repository some time ago, several commits behind the current master. While I removed the password later by committing without it, it still exists in several past commits. I don't mind losing the history of changes during those commits. I'm also not worried about somebody having seen the password during the time it was committed, but I want to delete this history to avoid problems in the future. What steps to take to ensure that, after those steps, nobody who gets access to this BitBucket repository in the future can find this password? Lets say I have the commits (from oldest to newest) with the (fake) SHA1s: c001 c002 c003 c004 c002 and c003 are hashes of "bad" commits that I want to delete entirely. I want master to stay on c004, but for c002 and c003 to no longer be accessible for anybody if I give them access to this repo. I tried following the instructions of similar questions on SO that offer to reset or rebase, but could not get them to work; I either manage to delete the commits on my machine but then cannot push back to BitBucket, or fail to delete on my machine altogether after messing something up. Can somebody please explain the steps needed to: 1. eliminate c002 and c003 from the repository's history 2. make sure it's saved on BitBucket, and that people cannot view those commits neither in BitBucket's GUI, or by cloning the repo to their machine I would appreciate an answer that explains what the commands do, and not just write some magic git commands that either work or don't work for me. Also, this question is specifically about BitBucket in case some things might be specific for it... I had trouble with "Updates were rejected because the tip of your current branch is behind" when trying to push changes back to BitBucket after making local repo changes with reset --hard. After several failed attempts and frustration with git's docs I decided to ask SO. .
2019/08/01
[ "https://Stackoverflow.com/questions/57316337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6086575/" ]
What I would do is: ``` git checkout revision-where-the-file-was-added git rm the-file-with-the-password git commit --amend --no-edit # fix the revision git cherry-pick revision-where-the-file-was-added..the-branch # replay all later revision # if you like the result git branch -f the-branch git push -f origin the-branch git checkout the-branch ``` This assumes there's a single line of revisions after the file was added. If there are merges involved in later history, you might have to need to play with options in cherry-pick.
You can do a combination of a `rebase` and a `git push origin master --force` to rewrite the history of your repository and force-push your changes so that no one would be able to view the password in the commit history. From your main branch you can do `git rebase origin/master -i` and then `edit` the commit where you pushed the password. Then run `git add .` to add it- then `git commit --amend` and `git rebase --continue` to continue with the rebase. When its done, `git push origin master` to force push it through and rewrite the history the way you want to.
2,390,224
i have some WinForms app (Framework to develop some simple apps), written in C#. My framework later would be used to develop win forms applications. Other developers they are beginers often and sometimes do not use Parameters - they write direct SQL in code. So first i need somehow to do protection in my framework base classes in C#. Do solve this, one developer suggested me to using an ORM such as NHibernate, which takes care of this issue for you (and you don't have to write SQL statements yourself most of the time). So I want to ask, is there some general alternatives(other ways and techniques) when i want to get defense from SQL-injections.Some links or examples would be very nice.
2010/03/05
[ "https://Stackoverflow.com/questions/2390224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152006/" ]
I don't see how there is any means to protect any SQL-based library from *developer* misuse without crippling its functionality (i.e. never giving direct access to the database). Even with NHibernate or Linq to SQL it's possible to bypass the mapping layers and directly write a SQL statement. Personally I think your best option would be to write in **BIG BOLD TEXT** that people who use your library need to **PARAMETERIZE THEIR QUERIES**. Failing that, you could try to do some kind of clumsy input sanitization, but that is honestly a flimsy second-rate hack. Parameterized queries have been around for so long now, there's no excuse for anyone writing code that touches any database to not be aware of it or understand how to use it. The only cure for ignorance is education. Maybe if we knew more about what this library is supposed to do with respect to data access, we could offer more targeted suggestions...
Agree with Aaronaught, a framework will not completely prevent the possibility. I would never substitute stringent validation on the data layer. Also provide an abstraction layer around your data access that you open up as the API rather then allow developers to connect directly to database.
2,390,224
i have some WinForms app (Framework to develop some simple apps), written in C#. My framework later would be used to develop win forms applications. Other developers they are beginers often and sometimes do not use Parameters - they write direct SQL in code. So first i need somehow to do protection in my framework base classes in C#. Do solve this, one developer suggested me to using an ORM such as NHibernate, which takes care of this issue for you (and you don't have to write SQL statements yourself most of the time). So I want to ask, is there some general alternatives(other ways and techniques) when i want to get defense from SQL-injections.Some links or examples would be very nice.
2010/03/05
[ "https://Stackoverflow.com/questions/2390224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152006/" ]
I don't see how there is any means to protect any SQL-based library from *developer* misuse without crippling its functionality (i.e. never giving direct access to the database). Even with NHibernate or Linq to SQL it's possible to bypass the mapping layers and directly write a SQL statement. Personally I think your best option would be to write in **BIG BOLD TEXT** that people who use your library need to **PARAMETERIZE THEIR QUERIES**. Failing that, you could try to do some kind of clumsy input sanitization, but that is honestly a flimsy second-rate hack. Parameterized queries have been around for so long now, there's no excuse for anyone writing code that touches any database to not be aware of it or understand how to use it. The only cure for ignorance is education. Maybe if we knew more about what this library is supposed to do with respect to data access, we could offer more targeted suggestions...
It sounds like you need to train your developers to use parameter binding instead of looking for a technical solution. One other alternative would be to keep the database layer in a different project and only allow your SQL savy developers to code in it. The GUI can be in a different project. That way the GUI programmers won't mess up your DB.
2,390,224
i have some WinForms app (Framework to develop some simple apps), written in C#. My framework later would be used to develop win forms applications. Other developers they are beginers often and sometimes do not use Parameters - they write direct SQL in code. So first i need somehow to do protection in my framework base classes in C#. Do solve this, one developer suggested me to using an ORM such as NHibernate, which takes care of this issue for you (and you don't have to write SQL statements yourself most of the time). So I want to ask, is there some general alternatives(other ways and techniques) when i want to get defense from SQL-injections.Some links or examples would be very nice.
2010/03/05
[ "https://Stackoverflow.com/questions/2390224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152006/" ]
I don't see how there is any means to protect any SQL-based library from *developer* misuse without crippling its functionality (i.e. never giving direct access to the database). Even with NHibernate or Linq to SQL it's possible to bypass the mapping layers and directly write a SQL statement. Personally I think your best option would be to write in **BIG BOLD TEXT** that people who use your library need to **PARAMETERIZE THEIR QUERIES**. Failing that, you could try to do some kind of clumsy input sanitization, but that is honestly a flimsy second-rate hack. Parameterized queries have been around for so long now, there's no excuse for anyone writing code that touches any database to not be aware of it or understand how to use it. The only cure for ignorance is education. Maybe if we knew more about what this library is supposed to do with respect to data access, we could offer more targeted suggestions...
Security is usually a process, not a product or api. It is also an evolving process, we have to adapt or get hacked. A heavy handed approach: You can force everyone to write stored procedures,and not allow direct table access from the accounts that are allowed to talk to the database. (GRANT EXECUTE ON etc) Then you would need to ensure that nobody writes any fancy stored procedures that take a sql query as a parameter and evaluates it dynamically. This tends to slow down development, and I personally would not use it, but I have consulted at several shops that did.
2,390,224
i have some WinForms app (Framework to develop some simple apps), written in C#. My framework later would be used to develop win forms applications. Other developers they are beginers often and sometimes do not use Parameters - they write direct SQL in code. So first i need somehow to do protection in my framework base classes in C#. Do solve this, one developer suggested me to using an ORM such as NHibernate, which takes care of this issue for you (and you don't have to write SQL statements yourself most of the time). So I want to ask, is there some general alternatives(other ways and techniques) when i want to get defense from SQL-injections.Some links or examples would be very nice.
2010/03/05
[ "https://Stackoverflow.com/questions/2390224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152006/" ]
Agree with Aaronaught, a framework will not completely prevent the possibility. I would never substitute stringent validation on the data layer. Also provide an abstraction layer around your data access that you open up as the API rather then allow developers to connect directly to database.
Security is usually a process, not a product or api. It is also an evolving process, we have to adapt or get hacked. A heavy handed approach: You can force everyone to write stored procedures,and not allow direct table access from the accounts that are allowed to talk to the database. (GRANT EXECUTE ON etc) Then you would need to ensure that nobody writes any fancy stored procedures that take a sql query as a parameter and evaluates it dynamically. This tends to slow down development, and I personally would not use it, but I have consulted at several shops that did.
2,390,224
i have some WinForms app (Framework to develop some simple apps), written in C#. My framework later would be used to develop win forms applications. Other developers they are beginers often and sometimes do not use Parameters - they write direct SQL in code. So first i need somehow to do protection in my framework base classes in C#. Do solve this, one developer suggested me to using an ORM such as NHibernate, which takes care of this issue for you (and you don't have to write SQL statements yourself most of the time). So I want to ask, is there some general alternatives(other ways and techniques) when i want to get defense from SQL-injections.Some links or examples would be very nice.
2010/03/05
[ "https://Stackoverflow.com/questions/2390224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152006/" ]
It sounds like you need to train your developers to use parameter binding instead of looking for a technical solution. One other alternative would be to keep the database layer in a different project and only allow your SQL savy developers to code in it. The GUI can be in a different project. That way the GUI programmers won't mess up your DB.
Security is usually a process, not a product or api. It is also an evolving process, we have to adapt or get hacked. A heavy handed approach: You can force everyone to write stored procedures,and not allow direct table access from the accounts that are allowed to talk to the database. (GRANT EXECUTE ON etc) Then you would need to ensure that nobody writes any fancy stored procedures that take a sql query as a parameter and evaluates it dynamically. This tends to slow down development, and I personally would not use it, but I have consulted at several shops that did.
11,639,319
I can't seem to return an object from a function, the console.log inside the function prints out the property values fine but once outside the function I'm getting "Uncaught ReferenceError: firstOn is not defined" Any help would be appreciated, thanks! ``` myElement = document.getElementById("testButton"); function Server(name,tables,startTime) { this.name = name; this.tables = tables; this.startTime = startTime; } document.forms.server1.button.onclick = function() { var name = document.forms.server1.servername.value; var tables = document.forms.server1.servertables.value; var startTime = document.forms.server1.servertime.value; var firstOn = new Server(name,tables,startTime); document.forms.server1.button.innerHTML = "Saved!"; console.log(firstOn.name); console.log(firstOn.tables); console.log(firstOn.startTime); return firstOn; }; myElement.onclick = function() { console.log(firstOn.name); console.log(firstOn.tables); console.log(firstOn.startTime); }; ```
2012/07/24
[ "https://Stackoverflow.com/questions/11639319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
That firstOn object was created in the local function scope. It will not be available globally in the second function.
I think this is the appropriate solution to my problem. ``` myElement = document.getElementById("testButton"); function Server(name,tables,startTime) { this.name = name; this.tables = tables; this.startTime = startTime; } var firstOn = new Server(); document.forms.server1.button.onclick = function() { firstOn.name = document.forms.server1.servername.value; firstOn.tables = document.forms.server1.servertables.value; firstOn.startTime = document.forms.server1.servertime.value; document.forms.server1.button.innerHTML = "Saved!"; console.log(firstOn.name); console.log(firstOn.tables); console.log(firstOn.startTime); return firstOn; }; myElement.onclick = function() { console.log(firstOn.name); console.log(firstOn.tables); console.log(firstOn.startTime); }; ```
11,639,319
I can't seem to return an object from a function, the console.log inside the function prints out the property values fine but once outside the function I'm getting "Uncaught ReferenceError: firstOn is not defined" Any help would be appreciated, thanks! ``` myElement = document.getElementById("testButton"); function Server(name,tables,startTime) { this.name = name; this.tables = tables; this.startTime = startTime; } document.forms.server1.button.onclick = function() { var name = document.forms.server1.servername.value; var tables = document.forms.server1.servertables.value; var startTime = document.forms.server1.servertime.value; var firstOn = new Server(name,tables,startTime); document.forms.server1.button.innerHTML = "Saved!"; console.log(firstOn.name); console.log(firstOn.tables); console.log(firstOn.startTime); return firstOn; }; myElement.onclick = function() { console.log(firstOn.name); console.log(firstOn.tables); console.log(firstOn.startTime); }; ```
2012/07/24
[ "https://Stackoverflow.com/questions/11639319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
That firstOn object was created in the local function scope. It will not be available globally in the second function.
`firstOn` is an object that was created and returned from the `document.forms.server1.button.onclick` event handler. The return value from that event handler went into the system (that's where event handlers return to) and was never stored anywhere so it was cleaned up by the system with garbage collection. Meanwhile, your `myElement.onclick` event handler does NOT have access to the `firstOn` object because it wasn't saved anywhere that `myElement.onclick` can reach. If you want `firstOn` to be usable after the `document.forms.server1.button.onclick` event handler, you have to save it somewhere that the second click handler can each. That could be in a global variable or it could be a property of some other object that is globally accessible. As your code is written right now, the `firstOn` object is created, but never stored anywhere so it is happily cleaned up by the garbage collector and is not reachable by other code.
11,639,319
I can't seem to return an object from a function, the console.log inside the function prints out the property values fine but once outside the function I'm getting "Uncaught ReferenceError: firstOn is not defined" Any help would be appreciated, thanks! ``` myElement = document.getElementById("testButton"); function Server(name,tables,startTime) { this.name = name; this.tables = tables; this.startTime = startTime; } document.forms.server1.button.onclick = function() { var name = document.forms.server1.servername.value; var tables = document.forms.server1.servertables.value; var startTime = document.forms.server1.servertime.value; var firstOn = new Server(name,tables,startTime); document.forms.server1.button.innerHTML = "Saved!"; console.log(firstOn.name); console.log(firstOn.tables); console.log(firstOn.startTime); return firstOn; }; myElement.onclick = function() { console.log(firstOn.name); console.log(firstOn.tables); console.log(firstOn.startTime); }; ```
2012/07/24
[ "https://Stackoverflow.com/questions/11639319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
That firstOn object was created in the local function scope. It will not be available globally in the second function.
``` var firstOn = new winMain.Server(name,tables,startTime); ```
11,639,319
I can't seem to return an object from a function, the console.log inside the function prints out the property values fine but once outside the function I'm getting "Uncaught ReferenceError: firstOn is not defined" Any help would be appreciated, thanks! ``` myElement = document.getElementById("testButton"); function Server(name,tables,startTime) { this.name = name; this.tables = tables; this.startTime = startTime; } document.forms.server1.button.onclick = function() { var name = document.forms.server1.servername.value; var tables = document.forms.server1.servertables.value; var startTime = document.forms.server1.servertime.value; var firstOn = new Server(name,tables,startTime); document.forms.server1.button.innerHTML = "Saved!"; console.log(firstOn.name); console.log(firstOn.tables); console.log(firstOn.startTime); return firstOn; }; myElement.onclick = function() { console.log(firstOn.name); console.log(firstOn.tables); console.log(firstOn.startTime); }; ```
2012/07/24
[ "https://Stackoverflow.com/questions/11639319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
`firstOn` is an object that was created and returned from the `document.forms.server1.button.onclick` event handler. The return value from that event handler went into the system (that's where event handlers return to) and was never stored anywhere so it was cleaned up by the system with garbage collection. Meanwhile, your `myElement.onclick` event handler does NOT have access to the `firstOn` object because it wasn't saved anywhere that `myElement.onclick` can reach. If you want `firstOn` to be usable after the `document.forms.server1.button.onclick` event handler, you have to save it somewhere that the second click handler can each. That could be in a global variable or it could be a property of some other object that is globally accessible. As your code is written right now, the `firstOn` object is created, but never stored anywhere so it is happily cleaned up by the garbage collector and is not reachable by other code.
I think this is the appropriate solution to my problem. ``` myElement = document.getElementById("testButton"); function Server(name,tables,startTime) { this.name = name; this.tables = tables; this.startTime = startTime; } var firstOn = new Server(); document.forms.server1.button.onclick = function() { firstOn.name = document.forms.server1.servername.value; firstOn.tables = document.forms.server1.servertables.value; firstOn.startTime = document.forms.server1.servertime.value; document.forms.server1.button.innerHTML = "Saved!"; console.log(firstOn.name); console.log(firstOn.tables); console.log(firstOn.startTime); return firstOn; }; myElement.onclick = function() { console.log(firstOn.name); console.log(firstOn.tables); console.log(firstOn.startTime); }; ```
11,639,319
I can't seem to return an object from a function, the console.log inside the function prints out the property values fine but once outside the function I'm getting "Uncaught ReferenceError: firstOn is not defined" Any help would be appreciated, thanks! ``` myElement = document.getElementById("testButton"); function Server(name,tables,startTime) { this.name = name; this.tables = tables; this.startTime = startTime; } document.forms.server1.button.onclick = function() { var name = document.forms.server1.servername.value; var tables = document.forms.server1.servertables.value; var startTime = document.forms.server1.servertime.value; var firstOn = new Server(name,tables,startTime); document.forms.server1.button.innerHTML = "Saved!"; console.log(firstOn.name); console.log(firstOn.tables); console.log(firstOn.startTime); return firstOn; }; myElement.onclick = function() { console.log(firstOn.name); console.log(firstOn.tables); console.log(firstOn.startTime); }; ```
2012/07/24
[ "https://Stackoverflow.com/questions/11639319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
`firstOn` is an object that was created and returned from the `document.forms.server1.button.onclick` event handler. The return value from that event handler went into the system (that's where event handlers return to) and was never stored anywhere so it was cleaned up by the system with garbage collection. Meanwhile, your `myElement.onclick` event handler does NOT have access to the `firstOn` object because it wasn't saved anywhere that `myElement.onclick` can reach. If you want `firstOn` to be usable after the `document.forms.server1.button.onclick` event handler, you have to save it somewhere that the second click handler can each. That could be in a global variable or it could be a property of some other object that is globally accessible. As your code is written right now, the `firstOn` object is created, but never stored anywhere so it is happily cleaned up by the garbage collector and is not reachable by other code.
``` var firstOn = new winMain.Server(name,tables,startTime); ```
12,016,262
I have listview on the UI thread. I have some operations to be performed through the background worker's DoWork event handler since they are time consuming. But I cant acess the listview items in my DoWork handler since it raises an exception:`Cross-thread operation not valid: Control 'bufferedListView1' accessed from a thread other than the thread it was created on.` So how do I acess my bufferedlistview in my DoWork event handler. This is the code to be handled in DoWork: ``` foreach (ListViewItem item in bufferedListView1.Items) { string lname = bufferedListView1.Items[i].Text; string lno = bufferedListView1.Items[i].SubItems[1].Text; string gname = bufferedListView1.Items[i].SubItems[2].Text; string line = lname + "@" + lno + "@" + gname; if (gname.Contains(sgroup)) { var m = Regex.Match(line, @"([\w]+)@([+\d]+)@([\w]+)"); if (m.Success) { port.WriteLine("AT+CMGS=\"" + m.Groups[2].Value + "\""); port.Write(txt_msgbox.Text + char.ConvertFromUtf32(26)); Thread.Sleep(4000); } sno++; } i++; } ```
2012/08/18
[ "https://Stackoverflow.com/questions/12016262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1528699/" ]
[Here's](http://www.perceler.com/articles1.php?art=crossthreads1) a good article on the topic of cross-threaded access to controls in winforms. Basically, whenever you access controls not from the UI thread, you have to use ``` control.Invoke ``` construct.
the mistake come from the fact that you try to access to UIThread from another thread (backgrounworker thread) to get a UI control use InvokeRequired you have to implement a delegate here a sample ``` delegate void valueDelegate(string value); private void SetValue(string value) { if (InvokeRequired) { BeginInvoke(new valueDelegate(SetValue),value); } else { someControl.Text = value; } } ```
12,016,262
I have listview on the UI thread. I have some operations to be performed through the background worker's DoWork event handler since they are time consuming. But I cant acess the listview items in my DoWork handler since it raises an exception:`Cross-thread operation not valid: Control 'bufferedListView1' accessed from a thread other than the thread it was created on.` So how do I acess my bufferedlistview in my DoWork event handler. This is the code to be handled in DoWork: ``` foreach (ListViewItem item in bufferedListView1.Items) { string lname = bufferedListView1.Items[i].Text; string lno = bufferedListView1.Items[i].SubItems[1].Text; string gname = bufferedListView1.Items[i].SubItems[2].Text; string line = lname + "@" + lno + "@" + gname; if (gname.Contains(sgroup)) { var m = Regex.Match(line, @"([\w]+)@([+\d]+)@([\w]+)"); if (m.Success) { port.WriteLine("AT+CMGS=\"" + m.Groups[2].Value + "\""); port.Write(txt_msgbox.Text + char.ConvertFromUtf32(26)); Thread.Sleep(4000); } sno++; } i++; } ```
2012/08/18
[ "https://Stackoverflow.com/questions/12016262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1528699/" ]
All I wanted was to **read the listview in UI thread in other thread**. All the solutions given were using `invoke` method but I found a rather easy way to do this: ``` ListView lvItems = new ListView(); \\in global scope ``` At the required location in my code: ``` foreach (ListViewItem item in bufferedListView1.Items) { lvItems.Items.Add((ListViewItem)item.Clone()); // Copied the bufferedListview's items that are to be accessed in other thread to another listview- listItems } ``` Then used the `lvItems` listview in my `DoWork` event handler. Simple n Easy :)
the mistake come from the fact that you try to access to UIThread from another thread (backgrounworker thread) to get a UI control use InvokeRequired you have to implement a delegate here a sample ``` delegate void valueDelegate(string value); private void SetValue(string value) { if (InvokeRequired) { BeginInvoke(new valueDelegate(SetValue),value); } else { someControl.Text = value; } } ```
9,716,744
I want to send the form after clicking on the label next to checkbox. So I have created simple function below. Html code: ``` <input class="myinput" type="checkbox" name="photo"id="photo" value="1" /> <label class="autosend" for="photo">Photos</label> <input class="myinput" type="checkbox" name="text"id="photo" value="1" /> <label class="autosend" for="text">Text</label> ``` Jquery code: ``` $('.autosend').click(function() { $('form#search').submit(); }); ``` The main problem is - after clicking on the label form is being sent, but without checked checkbox. Why is that? I see in my webbrowser that checkbox is checking just for a few seconds before send. Is there any way to use this jquery code above with possibility to check or uncheck checkbox which belongs to a specific label? I know I can add additional line before send a form: ``` $(this).prev(".myinput").attr('checked','checked'); ``` But that is not solution, because I need to check if previous input is checked and just toggle (between state checked and not checked).
2012/03/15
[ "https://Stackoverflow.com/questions/9716744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/907736/" ]
``` $('input:checkbox').change(function() { $('form#search').submit(); }); ```
First of all the `for` attribute of the `label` element should be set to the `id` of the related input. ``` <input class="myinput" type="checkbox" name="photo" id="photo" value="1" /> <label class="autosend" for="photo">Photos</label> <input class="myinput" type="checkbox" name="text" id="text" value="1" /> <label class="autosend" for="text">Text</label> ``` Secondly you should use the `change` event to cover users selecting the box via keyboard input, and you should also check to make sure that the box is being checked, not unchecked ``` $('input:checkbox').change(function() { if ($(this).is(":checked")) { $('form#search').submit(); } }); ``` [**Example fiddle**](http://jsfiddle.net/dK4Wa/2/)
9,716,744
I want to send the form after clicking on the label next to checkbox. So I have created simple function below. Html code: ``` <input class="myinput" type="checkbox" name="photo"id="photo" value="1" /> <label class="autosend" for="photo">Photos</label> <input class="myinput" type="checkbox" name="text"id="photo" value="1" /> <label class="autosend" for="text">Text</label> ``` Jquery code: ``` $('.autosend').click(function() { $('form#search').submit(); }); ``` The main problem is - after clicking on the label form is being sent, but without checked checkbox. Why is that? I see in my webbrowser that checkbox is checking just for a few seconds before send. Is there any way to use this jquery code above with possibility to check or uncheck checkbox which belongs to a specific label? I know I can add additional line before send a form: ``` $(this).prev(".myinput").attr('checked','checked'); ``` But that is not solution, because I need to check if previous input is checked and just toggle (between state checked and not checked).
2012/03/15
[ "https://Stackoverflow.com/questions/9716744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/907736/" ]
``` $('input:checkbox').change(function() { $('form#search').submit(); }); ```
The problem is that the `for` attribute of the `<label>` element corresponds to the **ID** not the name of the element that you want it to refer to. Your label and your checkbox aren't connected, so clicking the label won't toggle the checkbox.
9,716,744
I want to send the form after clicking on the label next to checkbox. So I have created simple function below. Html code: ``` <input class="myinput" type="checkbox" name="photo"id="photo" value="1" /> <label class="autosend" for="photo">Photos</label> <input class="myinput" type="checkbox" name="text"id="photo" value="1" /> <label class="autosend" for="text">Text</label> ``` Jquery code: ``` $('.autosend').click(function() { $('form#search').submit(); }); ``` The main problem is - after clicking on the label form is being sent, but without checked checkbox. Why is that? I see in my webbrowser that checkbox is checking just for a few seconds before send. Is there any way to use this jquery code above with possibility to check or uncheck checkbox which belongs to a specific label? I know I can add additional line before send a form: ``` $(this).prev(".myinput").attr('checked','checked'); ``` But that is not solution, because I need to check if previous input is checked and just toggle (between state checked and not checked).
2012/03/15
[ "https://Stackoverflow.com/questions/9716744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/907736/" ]
You can send the form on the change event of checkbox: ``` $('input[name=text]').on('change', function(){ $(this).parents('form').submit(); }); ```
First of all the `for` attribute of the `label` element should be set to the `id` of the related input. ``` <input class="myinput" type="checkbox" name="photo" id="photo" value="1" /> <label class="autosend" for="photo">Photos</label> <input class="myinput" type="checkbox" name="text" id="text" value="1" /> <label class="autosend" for="text">Text</label> ``` Secondly you should use the `change` event to cover users selecting the box via keyboard input, and you should also check to make sure that the box is being checked, not unchecked ``` $('input:checkbox').change(function() { if ($(this).is(":checked")) { $('form#search').submit(); } }); ``` [**Example fiddle**](http://jsfiddle.net/dK4Wa/2/)
9,716,744
I want to send the form after clicking on the label next to checkbox. So I have created simple function below. Html code: ``` <input class="myinput" type="checkbox" name="photo"id="photo" value="1" /> <label class="autosend" for="photo">Photos</label> <input class="myinput" type="checkbox" name="text"id="photo" value="1" /> <label class="autosend" for="text">Text</label> ``` Jquery code: ``` $('.autosend').click(function() { $('form#search').submit(); }); ``` The main problem is - after clicking on the label form is being sent, but without checked checkbox. Why is that? I see in my webbrowser that checkbox is checking just for a few seconds before send. Is there any way to use this jquery code above with possibility to check or uncheck checkbox which belongs to a specific label? I know I can add additional line before send a form: ``` $(this).prev(".myinput").attr('checked','checked'); ``` But that is not solution, because I need to check if previous input is checked and just toggle (between state checked and not checked).
2012/03/15
[ "https://Stackoverflow.com/questions/9716744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/907736/" ]
You can send the form on the change event of checkbox: ``` $('input[name=text]').on('change', function(){ $(this).parents('form').submit(); }); ```
The problem is that the `for` attribute of the `<label>` element corresponds to the **ID** not the name of the element that you want it to refer to. Your label and your checkbox aren't connected, so clicking the label won't toggle the checkbox.
55,279,663
How to mask the last string using swift, I have made the code as below. but the code only shows the last number, my expectation is that the code displays the first 5 digits here my code: ``` extension StringProtocol { var masked: String { return String(repeating: "•", count: Swift.max(0, count-5)) + suffix(5) } } var name = "0123456789" print(name.masked) ``` I get output: •••••56789 but my expectations: 01234•••••
2019/03/21
[ "https://Stackoverflow.com/questions/55279663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10003917/" ]
Use a prefix instead of a suffix ``` extension StringProtocol { var masked: String { return prefix(5) + String(repeating: "•", count: Swift.max(0, count-5)) } } ``` You could also create a function instead for parameterizing the number of digits and direction (or even the mask character) ``` extension StringProtocol { func masked(_ n: Int = 5, reversed: Bool = false) -> String { let mask = String(repeating: "•", count: Swift.max(0, count-n)) return reversed ? mask + suffix(n) : prefix(n) + mask } } var name = "0123456789" print(name.masked(5)) // 01234••••• print(name.masked(5, reversed: true)) // •••••56789 ```
If you have a case of wanting to mask an email address. here's the code ``` func maskingEmail(email: String) -> String { let emailComponents = email.components(separatedBy: "@") let emailDomainComponents = emailComponents[1].components(separatedBy: ".") let maskedEmailName = String(repeating: "•", count: Swift.max(0, emailComponents[0].count-3)) + emailComponents[0].suffix(3) let maskedEmailProvider = String(repeating: "•", count: Swift.max(0, emailDomainComponents[0].count-3)) + emailDomainComponents[0].suffix(3) let emailDomain = emailDomainComponents[1] return "\(maskedEmailName)@\(maskedEmailProvider).\(emailDomain)" } // The Output print(maskingEmail(email: "pr1vaterelay@gmail.com")) // •••••••••lay@••ail.com print(maskingEmail(email: "private_relay@bk.ru")) // ••••••••••lay@bk.ru print(maskingEmail(email: "private.relay@protonmail.com")) // ••••••••••lay@•••••••ail.com ```
6,513,821
I have a page thisfile.htm, which is included in thisfile.php I used to load thisfile.htm into an iframe on thisfile.php but because of iPad scrolling trouble, I recently converted everything to scrolling divs and php includes. I need to prevent the htm file from being loaded independently of the php parent. When I used iframes, I had no problem doing this with some javascript. But I can't get it to work with my php include - I get a loop. This is in child: ``` <script type="text/javascript"> if(top.location.href==self.location.href) { location.replace("thisfile.php"); } </script> ``` This is in parent: ``` <div class="bigdiv"><?php include "thisfile.htm" ?></div> ``` Thank you in advance.
2011/06/28
[ "https://Stackoverflow.com/questions/6513821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/798124/" ]
If you are using `include` in php, the easiest way to protect the file you are including, is to place it outside of the web-root. That way php can get to it, but a browser can´t so it can never be loaded separately. You don´t need any javascript in the child if you do it like this.
If thisfile.htm is to be included in a div in thisfile.php, just include it in php, using `include`. You don't have to call thisfile.htm from the outside at all. In fact, you could place it outside your doc root, in which case you cannot reach it from outside at all. It will only be included in thisfile.php.
56,005,112
I have two dates as `datetime.date` objects, what is the most Pythonic way to find a number of workdays between these two dates (including starting and excluding ending date)? For example: ``` from datetime import date, timedelta d1 = date(2019, 3, 1) d2 = date(2019, 5, 6) # The difference between d2 and d1 is 46 workdays ``` Writting a loop comes to my mind: ``` workdays = 0 for i in range((d2 - d1).days): if (d1 + timedelta(days=i)).isoweekday() <= 5: workdays += 1 ``` However, I think there is a simpler way to solve this problem.
2019/05/06
[ "https://Stackoverflow.com/questions/56005112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2609806/" ]
use the numpy function busday\_count: ``` from datetime import date import numpy as np d1 = date(2019, 3, 1) d2 = date(2019, 5, 6) days = np.busday_count( d1, d2 ) print (days) ``` or ``` from datetime import date,timedelta d1 = date(2019, 3, 1) d2 = date(2019, 5, 6) daygenerator = (d1 + timedelta(x + 1) for x in range((d2 - d1).days)) # generate all days from d1 to d2 print (sum(1 for day in daygenerator if day.weekday() < 5)) ```
You can try this: It does not take holidays,.. into account: ``` import numpy as np np.busday_count(d1.strftime("%Y-%m-%d"), d2.strftime("%Y-%m-%d")) ```
68,419,840
I was doing my homework when I encountered this problem: > > Write a function, mysum\_bigger\_than , that works the same as mysum , > except that it takes a first argument that precedes \*args . That > argument indicates the threshold for including an argument in the sum. > Thus, calling mysum\_bigger > \_than(10, 5, 20, 30, 6) would return 50 —because 5 and 6 aren’t greater than 10 . This function should similarly work with any type > and assumes that all of the arguments are of the same type. Note that '>' and '<' work on many different types in Python, not just on numbers; with strings, lists, and tuples, it refers to their sort order. > > > **THE PROBLEM WITH THE CODE UNDERNEATH: I can't sum elements which are bigger than threshold value without threshold value itself!** ``` def mysum_bigger_than(*values): if not values: return values output = values[0] for value in values[1:]: if value < output: continue else: output += value return output print(mysum_bigger_than(10,5,20,30,6)) #returns 60 instead of 50 print(mysum_bigger_than('mno', 'abc', 'pqr', 'uvw', 'efg', 'xyz')) #returns everything i need with unnecessary 'mno' ```
2021/07/17
[ "https://Stackoverflow.com/questions/68419840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14270371/" ]
One problem with your attempt: You use the threshold (`output`) as a starting point of the summation. Another: You check for *bigger and equal than* the threshold. And I think you should actually model your function signature according to this part of the instructions: > > ... except that it takes a first argument that precedes \*args ... > > > So ``` def mysum_bigger_than(threshold, *values): ``` This has the advantage that (1) without providing a `threshold` the function would return an error. And (2) you don't have to separate the threshold from the `values` list in the function definition. Here's a suggestion: ``` def mysum_bigger_than(threshold, *values): summing = False result = None for value in values: if value > threshold: if summing: result += value else: result = value summing = True return result ``` `summing` is a control variable: It's value is `False` as long as the values in `values` are below the threshold. Once the first value is above the threshold it's value is set to `True`. And at the same time the `result` variable gets "properly" initialized and is used afterwards as summation variable. If no value in `values` is above the threshold the function returns `None`, otherwise the required sum. Here's another suggestion, which is more compact but probably not as efficient (which would only matter for an extremely large `values` list): ``` def mysum_bigger_than(threshold, *values): sum_values = [value for value in values if value > threshold] if not sum_values: return None result = sum_values[0] for value in sum_values[1:]: result += value return result ``` The first step filters those values from `values` that meet the requirement of being bigger than the threshold (using a list comprehension). The next step checks if there are actually values that are bigger than the threshold. The function returns `None` if that's not the case. The rest is just summing up over the filtered values, if there are any. If you're allowed to, you could use some tools from the standard library, `reduce` and `add`: ``` from functools import reduce from operator import add def mysum_bigger_than(threshold, *values): sum_values = [value for value in values if value > threshold] if not sum_values: return None return reduce(add, sum_values) ``` But I think this is a bit overkill. (One thing you definitely shouldn't use here is `sum`, because by design it doesn't work for strings.)
Try this approach: ```py def mysum_bigger_than(*values): if not values: return values cond = lambda x: x > values[0] return sum(filter(cond, values[1:])) ```
51,809,274
I develop a toy compiler, and trying to implement strings and arrays. I have noticed that clang creates always a global variable for those types, even if they where defined within a function. I guess that there is a good reason for that, so I try to do the same. My problem is that I cannot figure out how to do it via c++ API. [kalidoscope tutorial](https://llvm.org/docs/tutorial/LangImpl01.html) does not cover strings and arrays, so the only source that I have found is [the documentation](http://llvm.org/doxygen/classllvm_1_1Module.html). In the documentation for the Module class, there is the function [getOrInsertGlobal](http://llvm.org/doxygen/classllvm_1_1Module.html#a1ec20a6f23ced1a328d4b1223fa22d96), which looks relevant, but I cannot understand how I set the actual value of the global. The function arguments include only the name and the type of the variable. So where does the value go? So the question is: how can I define a global string, such as "hello" or array, such as [i32 1, i32 2] in llvm c++ API? Any example would be really appreciated.
2018/08/12
[ "https://Stackoverflow.com/questions/51809274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7441319/" ]
What you want is called a read-only [GlobalVariable](https://llvm.org/docs/LangRef.html#global-variables) and you need that variable, an initializer, and probably a [constant cast](https://llvm.org/docs/LangRef.html#constant-expressions) so that all of your strings can have the same type. Suppose your strings are the C kind — null-terminated sequences of bytes. In that case you'll want your strings to be an array of zero bytes, so that all arrays have the same type. But the initialisers need to be arrays of the right numbers of bytes, so that each initialiser's type will match its value. So you create your array using something like this (cut and pasted together from bits of code I've written, won't even compile, is not the most efficient way, but does contain most of the building blocks you need): ``` std::vector<llvm::Constant *> chars(utf8string.size()); for(unsigned int i = 0; i < utf8string.size(); i++) chars[i] = ConstantInt::get(i8, utf8string[i]); auto init = ConstantArray::get(ArrayType::get(i8, chars.size()), entries); GlobalVariable * v = new GlobalVariable(module, init->getType(), true, GlobalVariable::ExternalLinkage, init, utf8string); return ConstantExpr::getBitCast(v, i8->getPointerTo()); ``` Note that a GlobalVariable is a pointer to whatever it's been initialised as, so if you initialise it with the five-byte sequence "test\0", then it'll be a pointer to a five bytes. Or, if you cast, it can be a pointer to 0 bytes (LLVM lets you index past the official end), or it can be an instance if an abstract type you define.
Using the code and the help of @arnt on the answer above, and I ended up with the following code to implement a string initialization. It now works, and also avoids the call to new, so it does not require any cleanup later. I post it, hoping that it may be useful for someone. ``` llvm::Value* EulStringToken::generateValue(llvm::Module* module, llvm::LLVMContext context) { //0. Defs auto str = this->value; auto charType = llvm::IntegerType::get(context, 8); //1. Initialize chars vector std::vector<llvm::Constant *> chars(str.length()); for(unsigned int i = 0; i < str.size(); i++) { chars[i] = llvm::ConstantInt::get(charType, str[i]); } //1b. add a zero terminator too chars.push_back(llvm::ConstantInt::get(charType, 0)); //2. Initialize the string from the characters auto stringType = llvm::ArrayType::get(charType, chars.size()); //3. Create the declaration statement auto globalDeclaration = (llvm::GlobalVariable*) module->getOrInsertGlobal(".str", stringType); globalDeclaration->setInitializer(llvm::ConstantArray::get(stringType, chars)); globalDeclaration->setConstant(true); globalDeclaration->setLinkage(llvm::GlobalValue::LinkageTypes::PrivateLinkage); globalDeclaration->setUnnamedAddr (llvm::GlobalValue::UnnamedAddr::Global); //4. Return a cast to an i8* return llvm::ConstantExpr::getBitCast(globalDeclaration, charType->getPointerTo()); } ```
84,476
Does AJAX need to use a server-side language such as PHP/ASP.NET/Java to access a database? Or some sort of web service tied to these languages? Or is AJAX able to communicate directly with the database?
2011/06/16
[ "https://softwareengineering.stackexchange.com/questions/84476", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/27782/" ]
Ajax cannot access any database, since it's not a language, nor a precise technology. Do you mean javascript? I don't think js can open a socket directly to your sql server. Anyway, that would require your db server to be open wide, which is a bad idea in most cases. You could also use the localstorage api, if all you need is storing a limited piece of data clint side.
AJAX is client side. You need a server-side connection to the database. This is mostly done in PHP, ASP.NET or Java. It is possible to connect to a database from the client, for example like this: ``` <script language="JavaScript" > function getSubmit() { var LastName; var Firstn = names.value ; var cn = new ActiveXObject("ADODB.Connection"); //here you must use forward slash to point strait var strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:/clientDB.mdb"; var rs = new ActiveXObject("ADODB.Recordset"); //var SQL = "INSERT INTO Customers(FirstName, Surname)" //+ " VALUES ( '"+ names.value +"', '" + surname.value +"')"; var SQL = "select Surname, DOB from Customers where FirstName = '" + Firstn + "'"; cn.Open(strConn); rs.Open(SQL, cn); surname.value = rs(0); DOB.value = rs(1); //alert(rs(0)); rs.Close(); cn.Close(); } </script> ``` [source](http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/84847/474843#post474843) But that will tell your visitors the username and password to the database. That's why a server side language is used.
84,476
Does AJAX need to use a server-side language such as PHP/ASP.NET/Java to access a database? Or some sort of web service tied to these languages? Or is AJAX able to communicate directly with the database?
2011/06/16
[ "https://softwareengineering.stackexchange.com/questions/84476", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/27782/" ]
Ajax cannot access any database, since it's not a language, nor a precise technology. Do you mean javascript? I don't think js can open a socket directly to your sql server. Anyway, that would require your db server to be open wide, which is a bad idea in most cases. You could also use the localstorage api, if all you need is storing a limited piece of data clint side.
It can if the database engine itself has public endpoints (a webserver) built into it. I don't know of any off the top of my head but some are not far off. For example, you already communicate with MongoDb via Json. [This question](https://stackoverflow.com/questions/2133246/access-mongodb-directly-via-javascript) implies that there is some middle layers that you can just drop into place that will expose those endpoints via Http. Also you can probably use [OData plugins](http://seroter.wordpress.com/2011/03/24/exposing-on-premise-sql-server-tables-as-odata-through-windows-azure-appfabric/). In any case it isn't easy and it is definitely a bad idea - how would you do authentication? Are you going to allow anyone over the internet to push data directly into your database? To delete things?
84,476
Does AJAX need to use a server-side language such as PHP/ASP.NET/Java to access a database? Or some sort of web service tied to these languages? Or is AJAX able to communicate directly with the database?
2011/06/16
[ "https://softwareengineering.stackexchange.com/questions/84476", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/27782/" ]
Ajax cannot access any database, since it's not a language, nor a precise technology. Do you mean javascript? I don't think js can open a socket directly to your sql server. Anyway, that would require your db server to be open wide, which is a bad idea in most cases. You could also use the localstorage api, if all you need is storing a limited piece of data clint side.
First off, note that AJAX stands for [Asynchronous JavaScript And XML](http://en.wikipedia.org/wiki/Ajax_%28programming%29). Knowing that doesn't directly answer your question, but it is helpful. Anyway, AJAX is an umbrella term for a certain use of a cluster of client-side technologies, so by definition it isn't accessing the server directly. I mean, the definition of the term is pretty much "using JavaScript in a webpage to communicate with the server". Although JavaScript itself can be used to program on the server, that is unusual and anyway the code is definitely still server-side (ie. JavaScript in the webpage is communicating with JavaScript on the server). So the answer is that you don't access the database directly from client-side code and need code running on the server to access the database. The client-side code communicates with the server-side code using something like a RESTful API of GET/PUSH requests.
84,476
Does AJAX need to use a server-side language such as PHP/ASP.NET/Java to access a database? Or some sort of web service tied to these languages? Or is AJAX able to communicate directly with the database?
2011/06/16
[ "https://softwareengineering.stackexchange.com/questions/84476", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/27782/" ]
Ajax cannot access any database, since it's not a language, nor a precise technology. Do you mean javascript? I don't think js can open a socket directly to your sql server. Anyway, that would require your db server to be open wide, which is a bad idea in most cases. You could also use the localstorage api, if all you need is storing a limited piece of data clint side.
First of all, AJAX operates using HTTP protocol with JSON or XML payload. Most databases operate using proprietary protocols, with payload being SQL input, raw data as output. Second, most web application provide security at application level. Giving direct access to the database would be huge security hole. With webapps, real security can only be achieved server side logic. In theory you could achieve this using views, stored procedures and having each webapp user as separate DB account. But that would be impractical, it's much easier and more efficient to do that with generic server-side language.
84,476
Does AJAX need to use a server-side language such as PHP/ASP.NET/Java to access a database? Or some sort of web service tied to these languages? Or is AJAX able to communicate directly with the database?
2011/06/16
[ "https://softwareengineering.stackexchange.com/questions/84476", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/27782/" ]
It can if the database engine itself has public endpoints (a webserver) built into it. I don't know of any off the top of my head but some are not far off. For example, you already communicate with MongoDb via Json. [This question](https://stackoverflow.com/questions/2133246/access-mongodb-directly-via-javascript) implies that there is some middle layers that you can just drop into place that will expose those endpoints via Http. Also you can probably use [OData plugins](http://seroter.wordpress.com/2011/03/24/exposing-on-premise-sql-server-tables-as-odata-through-windows-azure-appfabric/). In any case it isn't easy and it is definitely a bad idea - how would you do authentication? Are you going to allow anyone over the internet to push data directly into your database? To delete things?
AJAX is client side. You need a server-side connection to the database. This is mostly done in PHP, ASP.NET or Java. It is possible to connect to a database from the client, for example like this: ``` <script language="JavaScript" > function getSubmit() { var LastName; var Firstn = names.value ; var cn = new ActiveXObject("ADODB.Connection"); //here you must use forward slash to point strait var strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:/clientDB.mdb"; var rs = new ActiveXObject("ADODB.Recordset"); //var SQL = "INSERT INTO Customers(FirstName, Surname)" //+ " VALUES ( '"+ names.value +"', '" + surname.value +"')"; var SQL = "select Surname, DOB from Customers where FirstName = '" + Firstn + "'"; cn.Open(strConn); rs.Open(SQL, cn); surname.value = rs(0); DOB.value = rs(1); //alert(rs(0)); rs.Close(); cn.Close(); } </script> ``` [source](http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/84847/474843#post474843) But that will tell your visitors the username and password to the database. That's why a server side language is used.
84,476
Does AJAX need to use a server-side language such as PHP/ASP.NET/Java to access a database? Or some sort of web service tied to these languages? Or is AJAX able to communicate directly with the database?
2011/06/16
[ "https://softwareengineering.stackexchange.com/questions/84476", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/27782/" ]
AJAX is client side. You need a server-side connection to the database. This is mostly done in PHP, ASP.NET or Java. It is possible to connect to a database from the client, for example like this: ``` <script language="JavaScript" > function getSubmit() { var LastName; var Firstn = names.value ; var cn = new ActiveXObject("ADODB.Connection"); //here you must use forward slash to point strait var strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:/clientDB.mdb"; var rs = new ActiveXObject("ADODB.Recordset"); //var SQL = "INSERT INTO Customers(FirstName, Surname)" //+ " VALUES ( '"+ names.value +"', '" + surname.value +"')"; var SQL = "select Surname, DOB from Customers where FirstName = '" + Firstn + "'"; cn.Open(strConn); rs.Open(SQL, cn); surname.value = rs(0); DOB.value = rs(1); //alert(rs(0)); rs.Close(); cn.Close(); } </script> ``` [source](http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/84847/474843#post474843) But that will tell your visitors the username and password to the database. That's why a server side language is used.
First off, note that AJAX stands for [Asynchronous JavaScript And XML](http://en.wikipedia.org/wiki/Ajax_%28programming%29). Knowing that doesn't directly answer your question, but it is helpful. Anyway, AJAX is an umbrella term for a certain use of a cluster of client-side technologies, so by definition it isn't accessing the server directly. I mean, the definition of the term is pretty much "using JavaScript in a webpage to communicate with the server". Although JavaScript itself can be used to program on the server, that is unusual and anyway the code is definitely still server-side (ie. JavaScript in the webpage is communicating with JavaScript on the server). So the answer is that you don't access the database directly from client-side code and need code running on the server to access the database. The client-side code communicates with the server-side code using something like a RESTful API of GET/PUSH requests.
84,476
Does AJAX need to use a server-side language such as PHP/ASP.NET/Java to access a database? Or some sort of web service tied to these languages? Or is AJAX able to communicate directly with the database?
2011/06/16
[ "https://softwareengineering.stackexchange.com/questions/84476", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/27782/" ]
AJAX is client side. You need a server-side connection to the database. This is mostly done in PHP, ASP.NET or Java. It is possible to connect to a database from the client, for example like this: ``` <script language="JavaScript" > function getSubmit() { var LastName; var Firstn = names.value ; var cn = new ActiveXObject("ADODB.Connection"); //here you must use forward slash to point strait var strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:/clientDB.mdb"; var rs = new ActiveXObject("ADODB.Recordset"); //var SQL = "INSERT INTO Customers(FirstName, Surname)" //+ " VALUES ( '"+ names.value +"', '" + surname.value +"')"; var SQL = "select Surname, DOB from Customers where FirstName = '" + Firstn + "'"; cn.Open(strConn); rs.Open(SQL, cn); surname.value = rs(0); DOB.value = rs(1); //alert(rs(0)); rs.Close(); cn.Close(); } </script> ``` [source](http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/84847/474843#post474843) But that will tell your visitors the username and password to the database. That's why a server side language is used.
First of all, AJAX operates using HTTP protocol with JSON or XML payload. Most databases operate using proprietary protocols, with payload being SQL input, raw data as output. Second, most web application provide security at application level. Giving direct access to the database would be huge security hole. With webapps, real security can only be achieved server side logic. In theory you could achieve this using views, stored procedures and having each webapp user as separate DB account. But that would be impractical, it's much easier and more efficient to do that with generic server-side language.
84,476
Does AJAX need to use a server-side language such as PHP/ASP.NET/Java to access a database? Or some sort of web service tied to these languages? Or is AJAX able to communicate directly with the database?
2011/06/16
[ "https://softwareengineering.stackexchange.com/questions/84476", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/27782/" ]
It can if the database engine itself has public endpoints (a webserver) built into it. I don't know of any off the top of my head but some are not far off. For example, you already communicate with MongoDb via Json. [This question](https://stackoverflow.com/questions/2133246/access-mongodb-directly-via-javascript) implies that there is some middle layers that you can just drop into place that will expose those endpoints via Http. Also you can probably use [OData plugins](http://seroter.wordpress.com/2011/03/24/exposing-on-premise-sql-server-tables-as-odata-through-windows-azure-appfabric/). In any case it isn't easy and it is definitely a bad idea - how would you do authentication? Are you going to allow anyone over the internet to push data directly into your database? To delete things?
First off, note that AJAX stands for [Asynchronous JavaScript And XML](http://en.wikipedia.org/wiki/Ajax_%28programming%29). Knowing that doesn't directly answer your question, but it is helpful. Anyway, AJAX is an umbrella term for a certain use of a cluster of client-side technologies, so by definition it isn't accessing the server directly. I mean, the definition of the term is pretty much "using JavaScript in a webpage to communicate with the server". Although JavaScript itself can be used to program on the server, that is unusual and anyway the code is definitely still server-side (ie. JavaScript in the webpage is communicating with JavaScript on the server). So the answer is that you don't access the database directly from client-side code and need code running on the server to access the database. The client-side code communicates with the server-side code using something like a RESTful API of GET/PUSH requests.
84,476
Does AJAX need to use a server-side language such as PHP/ASP.NET/Java to access a database? Or some sort of web service tied to these languages? Or is AJAX able to communicate directly with the database?
2011/06/16
[ "https://softwareengineering.stackexchange.com/questions/84476", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/27782/" ]
It can if the database engine itself has public endpoints (a webserver) built into it. I don't know of any off the top of my head but some are not far off. For example, you already communicate with MongoDb via Json. [This question](https://stackoverflow.com/questions/2133246/access-mongodb-directly-via-javascript) implies that there is some middle layers that you can just drop into place that will expose those endpoints via Http. Also you can probably use [OData plugins](http://seroter.wordpress.com/2011/03/24/exposing-on-premise-sql-server-tables-as-odata-through-windows-azure-appfabric/). In any case it isn't easy and it is definitely a bad idea - how would you do authentication? Are you going to allow anyone over the internet to push data directly into your database? To delete things?
First of all, AJAX operates using HTTP protocol with JSON or XML payload. Most databases operate using proprietary protocols, with payload being SQL input, raw data as output. Second, most web application provide security at application level. Giving direct access to the database would be huge security hole. With webapps, real security can only be achieved server side logic. In theory you could achieve this using views, stored procedures and having each webapp user as separate DB account. But that would be impractical, it's much easier and more efficient to do that with generic server-side language.
16,163,647
I tried to subclass `UISegmentedControl`. I'm passing an `NSArray` from the view and try to set the titles for the `UISegmentedControl` from that `NSArray`. I used the `initWithArray` method but it is not setting the value from the array. Here is my subclass of `UISegmentedControl`. **WTSegmentedControl.h** ``` @interface WTSegmentedControl : UISegmentedControl { } @end ``` **WTSegmentedControl.m** ``` #import "WTSegmentedControl.h" @implementation WTSegmentedControl - (id)initWithItems:(NSArray *)items { if (self = [super initWithItems:items]) { } return self; } ``` Now from the view I'm calling this method. I have connected the outlet like this: ``` @property (nonatomic,strong) IBOutlet WTSegmentedControl *control; - (void)viewDidLoad { NSArray *names = [[NSArray alloc] initWithObjects:@"yes", @"no", nil]; control = [[WTSegmentedControl alloc] initWithItems:names]; } ``` `NSArray` is passing correctly but the `titles` are not set. Can anyone please help me with this?
2013/04/23
[ "https://Stackoverflow.com/questions/16163647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/923370/" ]
Ok so you are creating the control in the Interface Builder or by code!? You cannot do both. If you want to create it in code, remove the `IBOutlet` part in your property and add the control to the subView after initializing: ``` // adding the control by code - (void)viewDidLoad { [super viewDidLoad]; NSArray *names = [[NSArray alloc] initWithObjects:@"yes", @"no", nil]; control = [[WTSegmentedControl alloc] initWithItems:names]; control.frame = CGRectMake(x,z,width,height); [self.view addSubview: control]; } ``` But if you want to create it in the InterfaceBuilder, you should not re-initalize it. Set your custom class in Interface Builder and then just set the titles like this: ``` // using Interface Builder - (void)viewDidLoad { [super viewDidLoad]; NSArray *names = [[NSArray alloc] initWithObjects:@"yes", @"no", nil]; [names enumerateObjectsUsingBlock:^(NSString *title, NSUInteger idx, BOOL *stop) { [control setTitle:title forSegmentAtIndex:idx]; }]; } ```
If you have correctly connected your IBOutlet control, then the control variable is automatically set at this point. This is done when the view is loaded. So the line: ``` control = [[WTSegmentedControl alloc] initWithItems:names]; ``` should be changed to this: ``` [control initWithItems:names]; ```
677,508
I'm using ANTLR 3.1 and ANTLRWorks to generate a parser class in Java. The parser performs better if I mark the generated class with the Java final keyword. The problem is: I am adding this keyword manually after each time I re-generated the code from the ANTLR grammar. Is there anyway, in the grammar, of telling ANTLR to add the final keyword to the generated parser class definition?
2009/03/24
[ "https://Stackoverflow.com/questions/677508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What version of Java are you using? The more recent ones should detect leaf classes automatically, as should any since 1.3 in -server mode.
From [this thread](https://stackoverflow.com/questions/357695/how-do-you-specify-the-access-specifier-on-an-antlr-v3-generated-parser-or-lexer) (oops- my bad), it looks like it's not possible to do it yet. :(
22,163,199
I want to select a `RADIO button` when a click action is performed on a specific DIV. I am using following code and it is working fine but it is not validated by W3 as according to them, I cannot use DIV tag inside LABEL tag. I will not prefer JQuery as the whole work can be done using LABEL at proper place Following is my code ``` <div class="col-md-4 col-sm-4 padding"><label style="height:100%; width:100%;"> <div class="boxtyle2"> <div class="checkbox"> <div class="donate-option-box"> <input type="radio" checked="checked" onclick="ChangeGivingTextColor('10');" class="styled" value="10" name="asd"> </div> <h4 id="giving10" style="color: rgb(241, 55, 133);"><span class="pink2 currencysymbol">$</span>10</h4>Text </div> <div class="clear"></div> </div><!--boxtyle2--> </label></div> ``` Can someone modify my code so I can use it with LABEL but if there is no option for LABEL then what should I do in JQuery ?
2014/03/04
[ "https://Stackoverflow.com/questions/22163199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114966/" ]
Here is the code by which you can select radio onclick on div elements. ``` $("div").on("click", function(){ $("input[type='radio']").prop("checked", true); }); ```
Though i am clear enough about your question but what i`ll answer according to my understanding. First, labels are in-line elements where as div`s are block elements so it is obvious that you cannot use block elements inside an in-line element. Secondly, for on-click action on a div you can use jQuery .click() method **Example:** ``` $("#divID").click(function(){ alert("The paragraph was clicked."); }); ```
1,853,309
Instead of appending "abc" (and thus eventually getting a file full of abcabcabc....), no matter how many times I run this, myfile only containst "abc".... how can I append? ``` #include <stdio.h> #include <string.h> int main(){ char strng[10]; strcpy(strng,"abc"); FILE *my_file; my_file = fopen("myfile","a+"); if (my_file == NULL){ printf("problem\n");} fwrite(strng, sizeof(strng), 1, my_file); printf("appending %s\n",strng); fclose(my_file); } ```
2009/12/05
[ "https://Stackoverflow.com/questions/1853309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225532/" ]
Apart from the fact that: ``` fwrite(strng, sizeof(strng), 1, my_file); ``` should be: ``` fwrite(strng, strlen(strng), 1, my_file); ``` it works for me.
Don't use `sizeof`, use `strlen`. sizeof is 10, so you're writing "abc\0\0\0\0\0\0\0".
1,853,309
Instead of appending "abc" (and thus eventually getting a file full of abcabcabc....), no matter how many times I run this, myfile only containst "abc".... how can I append? ``` #include <stdio.h> #include <string.h> int main(){ char strng[10]; strcpy(strng,"abc"); FILE *my_file; my_file = fopen("myfile","a+"); if (my_file == NULL){ printf("problem\n");} fwrite(strng, sizeof(strng), 1, my_file); printf("appending %s\n",strng); fclose(my_file); } ```
2009/12/05
[ "https://Stackoverflow.com/questions/1853309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225532/" ]
Apart from the fact that: ``` fwrite(strng, sizeof(strng), 1, my_file); ``` should be: ``` fwrite(strng, strlen(strng), 1, my_file); ``` it works for me.
That program works and does what you said to do: append 10 characters (`sizeof(strng)`) to file, including `\0` and rest of the array. Change `sizeof` to `strlen`. Besides that you should not only print "problem" when you can't open file, but also not write to it. And last problem in your code - you declared `main` as returning `int`, but end program without setting return code. If you end program correctly, always return `EXIT_SUCCESS`. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #define BUF_SIZE 10 char buf[BUF_SIZE]; int main(int ac, char **av) { FILE *my_file; strncpy(buf, "abc", BUF_SIZE-1); buf[BUF_SIZE-1] = '\0'; my_file = fopen("myfile", "a+"); if (my_file == NULL) { fprintf(stderr, "problem opening file\n"); return EXIT_FAILURE; } else { fwrite(buf, strlen(buf), 1, my_file); printf("appending %s\n", buf); fclose(my_file); return EXIT_SUCCESS; } } ```
1,853,309
Instead of appending "abc" (and thus eventually getting a file full of abcabcabc....), no matter how many times I run this, myfile only containst "abc".... how can I append? ``` #include <stdio.h> #include <string.h> int main(){ char strng[10]; strcpy(strng,"abc"); FILE *my_file; my_file = fopen("myfile","a+"); if (my_file == NULL){ printf("problem\n");} fwrite(strng, sizeof(strng), 1, my_file); printf("appending %s\n",strng); fclose(my_file); } ```
2009/12/05
[ "https://Stackoverflow.com/questions/1853309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225532/" ]
Apart from the fact that: ``` fwrite(strng, sizeof(strng), 1, my_file); ``` should be: ``` fwrite(strng, strlen(strng), 1, my_file); ``` it works for me.
When you fopen the file, the stream position is at the beginning of the file. Surely you have to seek to the end before writing in order to get the string appended?
1,853,309
Instead of appending "abc" (and thus eventually getting a file full of abcabcabc....), no matter how many times I run this, myfile only containst "abc".... how can I append? ``` #include <stdio.h> #include <string.h> int main(){ char strng[10]; strcpy(strng,"abc"); FILE *my_file; my_file = fopen("myfile","a+"); if (my_file == NULL){ printf("problem\n");} fwrite(strng, sizeof(strng), 1, my_file); printf("appending %s\n",strng); fclose(my_file); } ```
2009/12/05
[ "https://Stackoverflow.com/questions/1853309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225532/" ]
That program works and does what you said to do: append 10 characters (`sizeof(strng)`) to file, including `\0` and rest of the array. Change `sizeof` to `strlen`. Besides that you should not only print "problem" when you can't open file, but also not write to it. And last problem in your code - you declared `main` as returning `int`, but end program without setting return code. If you end program correctly, always return `EXIT_SUCCESS`. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #define BUF_SIZE 10 char buf[BUF_SIZE]; int main(int ac, char **av) { FILE *my_file; strncpy(buf, "abc", BUF_SIZE-1); buf[BUF_SIZE-1] = '\0'; my_file = fopen("myfile", "a+"); if (my_file == NULL) { fprintf(stderr, "problem opening file\n"); return EXIT_FAILURE; } else { fwrite(buf, strlen(buf), 1, my_file); printf("appending %s\n", buf); fclose(my_file); return EXIT_SUCCESS; } } ```
Don't use `sizeof`, use `strlen`. sizeof is 10, so you're writing "abc\0\0\0\0\0\0\0".
1,853,309
Instead of appending "abc" (and thus eventually getting a file full of abcabcabc....), no matter how many times I run this, myfile only containst "abc".... how can I append? ``` #include <stdio.h> #include <string.h> int main(){ char strng[10]; strcpy(strng,"abc"); FILE *my_file; my_file = fopen("myfile","a+"); if (my_file == NULL){ printf("problem\n");} fwrite(strng, sizeof(strng), 1, my_file); printf("appending %s\n",strng); fclose(my_file); } ```
2009/12/05
[ "https://Stackoverflow.com/questions/1853309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225532/" ]
Don't use `sizeof`, use `strlen`. sizeof is 10, so you're writing "abc\0\0\0\0\0\0\0".
When you fopen the file, the stream position is at the beginning of the file. Surely you have to seek to the end before writing in order to get the string appended?
1,853,309
Instead of appending "abc" (and thus eventually getting a file full of abcabcabc....), no matter how many times I run this, myfile only containst "abc".... how can I append? ``` #include <stdio.h> #include <string.h> int main(){ char strng[10]; strcpy(strng,"abc"); FILE *my_file; my_file = fopen("myfile","a+"); if (my_file == NULL){ printf("problem\n");} fwrite(strng, sizeof(strng), 1, my_file); printf("appending %s\n",strng); fclose(my_file); } ```
2009/12/05
[ "https://Stackoverflow.com/questions/1853309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225532/" ]
That program works and does what you said to do: append 10 characters (`sizeof(strng)`) to file, including `\0` and rest of the array. Change `sizeof` to `strlen`. Besides that you should not only print "problem" when you can't open file, but also not write to it. And last problem in your code - you declared `main` as returning `int`, but end program without setting return code. If you end program correctly, always return `EXIT_SUCCESS`. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #define BUF_SIZE 10 char buf[BUF_SIZE]; int main(int ac, char **av) { FILE *my_file; strncpy(buf, "abc", BUF_SIZE-1); buf[BUF_SIZE-1] = '\0'; my_file = fopen("myfile", "a+"); if (my_file == NULL) { fprintf(stderr, "problem opening file\n"); return EXIT_FAILURE; } else { fwrite(buf, strlen(buf), 1, my_file); printf("appending %s\n", buf); fclose(my_file); return EXIT_SUCCESS; } } ```
When you fopen the file, the stream position is at the beginning of the file. Surely you have to seek to the end before writing in order to get the string appended?
38,401,301
Hi I have the plot below and there are 2 legends showing up. I have a question: Currently the legend I added has 6 entries "A Value", "Ad value", "au value", "b", "bD Value" and "bU value". I really want to the legend to show only 4 entries * "A" and in the legend this should be a blue solid line like it already is * "bd & bu" and in the legend this should be a blue DASHED line ...not sure how to get this * "A" and in the legend this should be a red solid line like it already is * "ad & au" and in the legend this should be a red DASHED line...not sure how to implement this Any thoughts? [![enter image description here](https://i.stack.imgur.com/f6eyh.png)](https://i.stack.imgur.com/f6eyh.png) ``` d = data.frame (title = c( rep(c("aU","A","ad"),2), rep( c("bU","b","bD"),2 ) ) , time = c(1,1,1,2,2,2,1,1,1,2,2,2) , value = c(10,8,4,9,7,3,5,3,1,4,2,0)) d ggplot(data=d , aes(x=time, y=value, group=title, colour = title, linetype =title))+ geom_line() + geom_point() + scale_colour_manual( name = "Metric", values = c( A = "red", ad = "red", aU = "red", b = "blue", bU ="blue", bD= "blue"), labels = c( A = "A value", ad = "Ad value", aU = "au value", b = "b", bU ="bU vlaue", bD= "dD Value") )+ scale_linetype_manual(name = "Metric", values =c( A = "solid", ad = "dashed", aU = "dashed", b = "solid", bU ="dashed", bD= "dashed"), labels = c( A = "A value", ad = "Ad value", aU = "au value", b = "b", bU ="bU vlaue", bD= "dD Value") ) ```
2016/07/15
[ "https://Stackoverflow.com/questions/38401301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3022875/" ]
The second legend is showing up because you changed the labels and title in just one of the two guides. If you change the other to match it (or better yet, change the `title` column to match the labels you want), the color and linetype will show up together in one legend. Alternatively, if the groupings match up (i.e., if the "U" means the same thing in "A" and "B"), you could set the color on one of those and the linetype on the other (which appears to be what you are currently doing). Like this: ``` d2 <- tidyr::separate(d , title , c("group","subgroup") , 1 , FALSE) ggplot(data=d2 , aes(x=time, y=value, group=title, colour = group, linetype =subgroup))+ geom_line() + geom_point() ``` You could then manually set colors and linetypes if you still wanted. [![enter image description here](https://i.stack.imgur.com/QA7ZH.png)](https://i.stack.imgur.com/QA7ZH.png) Or, for your current approach: ``` ggplot(data=d , aes(x=time, y=value, group=title, colour = title, linetype =title))+ geom_line() + geom_point() + scale_colour_manual( values = c( A = "red", ad = "red", aU = "red", b = "blue", bU ="blue", bD= "blue") )+ scale_linetype_manual(values =c( A = "solid", ad = "dashed", aU = "dashed", b = "solid", bU ="dashed", bD= "dashed") ) ``` To set just two line types, you can use: ``` d2$forLabel <- ifelse(d2$subgroup == "", "Value", "Limit") ggplot(data=d2 , aes(x=time, y=value, group=title, colour = group, linetype =forLabel))+ geom_line() + geom_point() + scale_linetype_manual(values = c(Limit = "dashed" , Value = "solid")) ``` [![enter image description here](https://i.stack.imgur.com/prS6x.png)](https://i.stack.imgur.com/prS6x.png) I'd recommend this instead of separate labels for everything (in particular, in case you add more groups later) As another alternative, if you are displaying intervals, would you instead consider using a ribbon, instead of two lines? ``` d3 <- d2 %>% group_by(group,time) %>% summarise(min = min(value), max=max(value) , value = value[forLabel=="Value"]) d3 <- d2 %>% group_by(group,time) %>% summarise(min = min(value), max=max(value) , value = value[forLabel=="Value"]) ggplot(data=d3 , aes(x=time, y=value, color = group))+ geom_line() + geom_point() + geom_ribbon(aes(ymin = min, ymax = max , fill = group , color = NULL) , alpha = 0.2 , color = NA) + theme_minimal() ``` [![enter image description here](https://i.stack.imgur.com/QJLlK.png)](https://i.stack.imgur.com/QJLlK.png)
``` d1 <- data.frame(title = c("aU","A","ad","bU","b","bD"), title2 = c("aU & ad", "A", "aU & ad", "bU & bD", "b", "bU & bD")) d2 <- merge(d, d1, by = "title") ggplot(d2 , aes(x = time, y = value, group = title, colour = title2, linetype = title2)) + geom_line() + geom_point() + scale_colour_manual(name = "Metric", values = c("A" = "red", "aU & ad" = "red", "bU & bD" = "blue", "b" = "blue")) + scale_linetype_manual(name = "Metric", values = c("A" = "solid", "aU & ad" = "dashed", "bU & bD" = "dashed", "b" = "solid")) ``` [![enter image description here](https://i.stack.imgur.com/P8Wow.jpg)](https://i.stack.imgur.com/P8Wow.jpg) You can use `ifelse` to create `title2`, I used `merge` because I feel its a bit cleaner
17,982,537
this is my html ``` <a href="/name/nm3515425/?ref_=tt_cl_i1"><img height="44" width="32" alt="Ross Lynch" title="Ross Lynch" src="http://ia.media-imdb.com/images/G/01/imdb/images/nopicture/32x44/name-2138558783._V379389446_.png" class="loadlate hidden " loadlate="http://ia.media-imdb.com/images/M/MV5BMjYyODA4ODcyOF5BMl5BanBnXkFtZTcwMDk4NDg4OQ@@._V1_SY44_CR1,0,32,44_.jpg"></a> ``` i want to change the src image to loadlate i tried searching but i didn't get my answer
2013/07/31
[ "https://Stackoverflow.com/questions/17982537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2640014/" ]
Actually, it's a bug (?), you cant use "Number" as a room id. Only string.
i think the problem is in this: "starting from 0". Dont use 0 for room name.
7,233,877
``` int f(int b[][3]); int main() { int a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; f(a); printf("%d\n", a[2][1]); } int f(int b[][3]) { ++b; b[1][1] = 1; } ``` `3x3 => 9` elements contained in the 2-D array `a`. When it's passed, then `b` will contain the the base address of the `a`. If suppose base address is `1000` then `++b` how does it to 3 locations and not 9 locations ahead? Are we doing typecasting when the variable `a` is passed to `b[][3]` as only the three elements? How does `b[1][1]` correspond to the address of `8` and not `5`? We can't do incrementing or decrementing in an array as array is a `const` pointer, but how is that they are incrementing `++b` as its an array?
2011/08/29
[ "https://Stackoverflow.com/questions/7233877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/713179/" ]
The function heading ``` int f(int b[][3]) ``` is a nothing more than a confusing way to write (and is *exactly equivalent* to) ``` int f(int (*b)[3]) ``` The type of `b` is "pointer to three-element array of `int`". When you increment the `b` parameter you adjust it to point to the next three-element array of `int` -- now it points to `{4,5,6}`. Then `b[1]` indexes once more and gives you the array `{7,8,9}` and finally `b[1][1]` gives you the oneth element of that array, namely `8`.
> > How is b[1][1] corresponds to the address of 8 and not address of 5? > > > This is expected behavior: ``` int f(int b[][3]) { //at this point b[0][0] is 1, b[1][1] is 5 ++b; //now b[0][0] is 4, b[1][1] is 8 b[1][1]=1; } ``` The pointer has incremented to point to the next memory slot, which is the second slot of array `a`. Basically: ``` b -> a[0] ++b -> a[1] ```
7,233,877
``` int f(int b[][3]); int main() { int a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; f(a); printf("%d\n", a[2][1]); } int f(int b[][3]) { ++b; b[1][1] = 1; } ``` `3x3 => 9` elements contained in the 2-D array `a`. When it's passed, then `b` will contain the the base address of the `a`. If suppose base address is `1000` then `++b` how does it to 3 locations and not 9 locations ahead? Are we doing typecasting when the variable `a` is passed to `b[][3]` as only the three elements? How does `b[1][1]` correspond to the address of `8` and not `5`? We can't do incrementing or decrementing in an array as array is a `const` pointer, but how is that they are incrementing `++b` as its an array?
2011/08/29
[ "https://Stackoverflow.com/questions/7233877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/713179/" ]
C multidimensional arrays are really linear, except that there is syntactic sugar to do the arithmetic correctly. so with `b[][3]`, it excepts a 1-D array and implicitly translates `b[i][j] --> b[3*i+j]` `++b` works as follows: `(++b)[i][j] = ORIGINAL_b[i+1][j]`. So in your case, you are accessing `ORIGINAL_b[1+1][1] = ORIGINAL_b[2*3+1] = ORIGINAL_b[7]` (the 8th element) Note: this is in stark contrast to the dynamic malloc version (in `**b`, `b` is a array of pointers)
> > How is b[1][1] corresponds to the address of 8 and not address of 5? > > > This is expected behavior: ``` int f(int b[][3]) { //at this point b[0][0] is 1, b[1][1] is 5 ++b; //now b[0][0] is 4, b[1][1] is 8 b[1][1]=1; } ``` The pointer has incremented to point to the next memory slot, which is the second slot of array `a`. Basically: ``` b -> a[0] ++b -> a[1] ```
7,233,877
``` int f(int b[][3]); int main() { int a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; f(a); printf("%d\n", a[2][1]); } int f(int b[][3]) { ++b; b[1][1] = 1; } ``` `3x3 => 9` elements contained in the 2-D array `a`. When it's passed, then `b` will contain the the base address of the `a`. If suppose base address is `1000` then `++b` how does it to 3 locations and not 9 locations ahead? Are we doing typecasting when the variable `a` is passed to `b[][3]` as only the three elements? How does `b[1][1]` correspond to the address of `8` and not `5`? We can't do incrementing or decrementing in an array as array is a `const` pointer, but how is that they are incrementing `++b` as its an array?
2011/08/29
[ "https://Stackoverflow.com/questions/7233877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/713179/" ]
The function heading ``` int f(int b[][3]) ``` is a nothing more than a confusing way to write (and is *exactly equivalent* to) ``` int f(int (*b)[3]) ``` The type of `b` is "pointer to three-element array of `int`". When you increment the `b` parameter you adjust it to point to the next three-element array of `int` -- now it points to `{4,5,6}`. Then `b[1]` indexes once more and gives you the array `{7,8,9}` and finally `b[1][1]` gives you the oneth element of that array, namely `8`.
C multidimensional arrays are really linear, except that there is syntactic sugar to do the arithmetic correctly. so with `b[][3]`, it excepts a 1-D array and implicitly translates `b[i][j] --> b[3*i+j]` `++b` works as follows: `(++b)[i][j] = ORIGINAL_b[i+1][j]`. So in your case, you are accessing `ORIGINAL_b[1+1][1] = ORIGINAL_b[2*3+1] = ORIGINAL_b[7]` (the 8th element) Note: this is in stark contrast to the dynamic malloc version (in `**b`, `b` is a array of pointers)
1,403
Say you've spent a considerable amount of time, and perhaps some money as well, documenting a set of families. The work has paid off, and one of the rewards is to share it with people who may be living descendants of those documented by your research. The problem is that once you publish your research on a public web site of your choice, nothing prevents other (well-meaning) people—often your relatives!—from copying your work without attribution and incorporating the metadata and images related to the records you uncovered into their trees. In some areas of human intellectual endeavor (e.g., academic publishing), this would be considered plagiarism. In other areas [Creative Commons](http://creativecommons.org/) or other licensing may be used to allow reuse but to require people to give credit to the authors of the documents or other artifacts (e.g., software source code). How should genealogists approach this situation? I can imagine several possible tactics, each with its own trade-offs: 1. Don't publish anything in machine-readable ways. Making it difficult to incorporate information into other people's trees will deter some people; those who are not deterred are much more likely to cite the source. The downside is that fewer people will see the information because it will not be as easy to find, and that re-typing information from it (using it as a source) will be a source of errors. 2. Publish machine-readable information, but do so with privacy settings that require others to ask for documents. This makes it easier to keep track of who gets the information, and you might be able to ask them to attribute to work appropriately. No guarantees, of course. 3. Publish machine-readable information publicly, and contact those who use your information after the fact to ask them to give due credit. They are less likely to bother, but it does benefit more people who have access to the evidence you have collected. 4. Don't care about who does what. After all, as we used to say in an early (and successful) non-genealogical research project I was involved in, "[your ideas will be stolen, whether they are yours or not.](http://www.cs.cmu.edu/~mprice/quotes.htm)" I am curious to know which of these, or what other, solutions people have adopted, and if there are ways in which we can change best practices in the field to reward the effort that goes into our research. **Clarification**: Many of the excellent answers below had assumed a more polished form of publication than I had intended to convey in my question. I was referring merely to the accumulation of historical records associated with people in a tree, such as one that might be maintained at Ancestry.com. Clearly the copyright-able aspect of this is not the individual record, but the accumulation of such records to document an individual's (or a family) history. My gut feeling about this is that since it may have taken a considerable effort to put this together, that effort should be recognized. That was the point of my question: how best to protect that intellectual (and modest financial) effort?
2012/10/15
[ "https://genealogy.stackexchange.com/questions/1403", "https://genealogy.stackexchange.com", "https://genealogy.stackexchange.com/users/8/" ]
Personally, I'd use a combination of your (4) and (3): don't be too uptight about it, and make it as freely copyable as possible -- with a catch. > > Publish machine-readable information publicly, and contact those who use your information after the fact to ask them to give due credit. > > > For the purposes of this discussion, it seems like there are going to be four broad types of copying taking place: 1. People who will do a wholesale import of your tree into theirs, without thinking about attribution. 2. People who will retype information from your non-machine-readable tree into theirs, without thinking about attribution. 3. People who will selectively use information from your published tree with proper attribution. 4. People who will copy your information in any form, and intentionally remove attribution. Forget about the fourth case, there's not much you can do here that's worth the effort. In the third case, you're going to get credit, so that's fine. The first and second cases are the lazy copiers, and the second case is the one we really care about: since they have to retype (or cut & paste), and they're lazy, you're not going to get credit. You could largely eliminate the second case by making the work machine-readable -- anyone smart enough to do an import will just suck in your tree. And if you add citations to your own work, then they will import those citations and voilà, you get credit. (Of course, the risk is that they will still publish in a format that does not display source citations.) Automatically adding self-citations to a machine-readable format just prior to publication as a post-processing step should not be difficult (at least in theory!); whether it's worth the effort is a consideration for you, the author. As @Tom Wetmore mentioned in a comment on another answer, the copiers will often include your notes verbatim. If you simply want to know how much influence your work has had, include lots of notes! (Perhaps initial & date each note, too, for built-in self-citation?)
I try to take a practical approach: make it as easy as possible for people to give credit where it is due. One way towards this is to provide *actual citation text* for users to include in their sources (or in the material they cut-and-paste). The citation format will not always be the form they want, but it gets them most of the way there. An extension of this is to make GEDCOMs available which have the source credits built into them. These would have a source record for your article or website which has the reseach laid out, and would have references to that source record attached to each individual in the GEDCOM file. (It can also have textual references embedded as part of the included notes.) It's true that GEDCOM importers may intentionally or unintentionally strip off the source references, but at least you've made it easy to do the right thing. (Note: the source references are to your published research, not to the underlying genealogical sources, which are given in your published location. There are utilities available to help easily insert the source references into a GEDCOM.)
1,403
Say you've spent a considerable amount of time, and perhaps some money as well, documenting a set of families. The work has paid off, and one of the rewards is to share it with people who may be living descendants of those documented by your research. The problem is that once you publish your research on a public web site of your choice, nothing prevents other (well-meaning) people—often your relatives!—from copying your work without attribution and incorporating the metadata and images related to the records you uncovered into their trees. In some areas of human intellectual endeavor (e.g., academic publishing), this would be considered plagiarism. In other areas [Creative Commons](http://creativecommons.org/) or other licensing may be used to allow reuse but to require people to give credit to the authors of the documents or other artifacts (e.g., software source code). How should genealogists approach this situation? I can imagine several possible tactics, each with its own trade-offs: 1. Don't publish anything in machine-readable ways. Making it difficult to incorporate information into other people's trees will deter some people; those who are not deterred are much more likely to cite the source. The downside is that fewer people will see the information because it will not be as easy to find, and that re-typing information from it (using it as a source) will be a source of errors. 2. Publish machine-readable information, but do so with privacy settings that require others to ask for documents. This makes it easier to keep track of who gets the information, and you might be able to ask them to attribute to work appropriately. No guarantees, of course. 3. Publish machine-readable information publicly, and contact those who use your information after the fact to ask them to give due credit. They are less likely to bother, but it does benefit more people who have access to the evidence you have collected. 4. Don't care about who does what. After all, as we used to say in an early (and successful) non-genealogical research project I was involved in, "[your ideas will be stolen, whether they are yours or not.](http://www.cs.cmu.edu/~mprice/quotes.htm)" I am curious to know which of these, or what other, solutions people have adopted, and if there are ways in which we can change best practices in the field to reward the effort that goes into our research. **Clarification**: Many of the excellent answers below had assumed a more polished form of publication than I had intended to convey in my question. I was referring merely to the accumulation of historical records associated with people in a tree, such as one that might be maintained at Ancestry.com. Clearly the copyright-able aspect of this is not the individual record, but the accumulation of such records to document an individual's (or a family) history. My gut feeling about this is that since it may have taken a considerable effort to put this together, that effort should be recognized. That was the point of my question: how best to protect that intellectual (and modest financial) effort?
2012/10/15
[ "https://genealogy.stackexchange.com/questions/1403", "https://genealogy.stackexchange.com", "https://genealogy.stackexchange.com/users/8/" ]
"how best to protect that intellectual (and modest financial) effort?" 1. Protect it from copycat relatives? Hide it. 2. Protect it from being lost forever? Share it. 3. Protect it from both? Share it with all your distant relatives, encourage them to share it, and include a request for old pictures or updates on their families. Few will respond, but they will save your contact info.
These comments have been very informative and have confirmed my own feelings. Since 1999 I have been working on my extended family trees, researching, connecting with newly found relatives, going to locations, cemeteries, finding skeletons in the closet and finding cherished pictures that would have been in the trash if I had not found them. This documentation of the lives of my family and all the work has been my passion. My hopes that the next generation will enjoy. Though, I find it disrespectful to see all this information incorporated by others, including relatives, and use it as their own "edition" of the family history, but not crediting or acknowledging the source of the information. I have received information from many distant relatives, and if not noted, I can later forget where it came from, but it is not the norm. As a writer I find it uncouth/unprofessional. It is not a matter of using the information, but of not giving the credit by acknowledgement to the person who did the work. It isn't about a fee, for I would rather give information to others than have them pay for it on genealogy sites that charge. I have had other researchers go out of their way to help me in research, and I appreciate them and give credit to them for their help. Just my rant...,for what it is worth. Thanks
1,403
Say you've spent a considerable amount of time, and perhaps some money as well, documenting a set of families. The work has paid off, and one of the rewards is to share it with people who may be living descendants of those documented by your research. The problem is that once you publish your research on a public web site of your choice, nothing prevents other (well-meaning) people—often your relatives!—from copying your work without attribution and incorporating the metadata and images related to the records you uncovered into their trees. In some areas of human intellectual endeavor (e.g., academic publishing), this would be considered plagiarism. In other areas [Creative Commons](http://creativecommons.org/) or other licensing may be used to allow reuse but to require people to give credit to the authors of the documents or other artifacts (e.g., software source code). How should genealogists approach this situation? I can imagine several possible tactics, each with its own trade-offs: 1. Don't publish anything in machine-readable ways. Making it difficult to incorporate information into other people's trees will deter some people; those who are not deterred are much more likely to cite the source. The downside is that fewer people will see the information because it will not be as easy to find, and that re-typing information from it (using it as a source) will be a source of errors. 2. Publish machine-readable information, but do so with privacy settings that require others to ask for documents. This makes it easier to keep track of who gets the information, and you might be able to ask them to attribute to work appropriately. No guarantees, of course. 3. Publish machine-readable information publicly, and contact those who use your information after the fact to ask them to give due credit. They are less likely to bother, but it does benefit more people who have access to the evidence you have collected. 4. Don't care about who does what. After all, as we used to say in an early (and successful) non-genealogical research project I was involved in, "[your ideas will be stolen, whether they are yours or not.](http://www.cs.cmu.edu/~mprice/quotes.htm)" I am curious to know which of these, or what other, solutions people have adopted, and if there are ways in which we can change best practices in the field to reward the effort that goes into our research. **Clarification**: Many of the excellent answers below had assumed a more polished form of publication than I had intended to convey in my question. I was referring merely to the accumulation of historical records associated with people in a tree, such as one that might be maintained at Ancestry.com. Clearly the copyright-able aspect of this is not the individual record, but the accumulation of such records to document an individual's (or a family) history. My gut feeling about this is that since it may have taken a considerable effort to put this together, that effort should be recognized. That was the point of my question: how best to protect that intellectual (and modest financial) effort?
2012/10/15
[ "https://genealogy.stackexchange.com/questions/1403", "https://genealogy.stackexchange.com", "https://genealogy.stackexchange.com/users/8/" ]
Personally, I'd use a combination of your (4) and (3): don't be too uptight about it, and make it as freely copyable as possible -- with a catch. > > Publish machine-readable information publicly, and contact those who use your information after the fact to ask them to give due credit. > > > For the purposes of this discussion, it seems like there are going to be four broad types of copying taking place: 1. People who will do a wholesale import of your tree into theirs, without thinking about attribution. 2. People who will retype information from your non-machine-readable tree into theirs, without thinking about attribution. 3. People who will selectively use information from your published tree with proper attribution. 4. People who will copy your information in any form, and intentionally remove attribution. Forget about the fourth case, there's not much you can do here that's worth the effort. In the third case, you're going to get credit, so that's fine. The first and second cases are the lazy copiers, and the second case is the one we really care about: since they have to retype (or cut & paste), and they're lazy, you're not going to get credit. You could largely eliminate the second case by making the work machine-readable -- anyone smart enough to do an import will just suck in your tree. And if you add citations to your own work, then they will import those citations and voilà, you get credit. (Of course, the risk is that they will still publish in a format that does not display source citations.) Automatically adding self-citations to a machine-readable format just prior to publication as a post-processing step should not be difficult (at least in theory!); whether it's worth the effort is a consideration for you, the author. As @Tom Wetmore mentioned in a comment on another answer, the copiers will often include your notes verbatim. If you simply want to know how much influence your work has had, include lots of notes! (Perhaps initial & date each note, too, for built-in self-citation?)
I publish (or will publish) all the results of my research online, with exclusions mentioned elsewhere in discussions about privacy. I don't publish material to which other people hold the copyright (e.g. copyrighted images of sources, or oral testimony which I don't have permission to share). My own copyright statement says: > > Except where otherwise noted, I own the copyright on all material on this site — but not (of course) on the underlying facts. > > > If you want to make use of any of my copyright material, in your own family history research or for another purpose, contact me to ask permission. If you want to make use of the facts in your own research, it would be nice if you let me know. If you do re-publish any of the information here, please acknowledge me with a link to this site — and do check the facts for yourself. > > > My view is that I want to share the results of my research and it's impossible to stop other people using what I've done. If somebody asks permission to use copyrighted material, I'll almost certainly grant it although nobody has asked yet! And a polite request for acknowledgement may bear fruit. I take a less relaxed view to copyright violations with one of my other "hats" on, where there are commercial implications, but I'm losing nothing except maybe a little kudos if somebody rips off my family history research. I've already done the work and spent the money for my own satisfaction.
1,403
Say you've spent a considerable amount of time, and perhaps some money as well, documenting a set of families. The work has paid off, and one of the rewards is to share it with people who may be living descendants of those documented by your research. The problem is that once you publish your research on a public web site of your choice, nothing prevents other (well-meaning) people—often your relatives!—from copying your work without attribution and incorporating the metadata and images related to the records you uncovered into their trees. In some areas of human intellectual endeavor (e.g., academic publishing), this would be considered plagiarism. In other areas [Creative Commons](http://creativecommons.org/) or other licensing may be used to allow reuse but to require people to give credit to the authors of the documents or other artifacts (e.g., software source code). How should genealogists approach this situation? I can imagine several possible tactics, each with its own trade-offs: 1. Don't publish anything in machine-readable ways. Making it difficult to incorporate information into other people's trees will deter some people; those who are not deterred are much more likely to cite the source. The downside is that fewer people will see the information because it will not be as easy to find, and that re-typing information from it (using it as a source) will be a source of errors. 2. Publish machine-readable information, but do so with privacy settings that require others to ask for documents. This makes it easier to keep track of who gets the information, and you might be able to ask them to attribute to work appropriately. No guarantees, of course. 3. Publish machine-readable information publicly, and contact those who use your information after the fact to ask them to give due credit. They are less likely to bother, but it does benefit more people who have access to the evidence you have collected. 4. Don't care about who does what. After all, as we used to say in an early (and successful) non-genealogical research project I was involved in, "[your ideas will be stolen, whether they are yours or not.](http://www.cs.cmu.edu/~mprice/quotes.htm)" I am curious to know which of these, or what other, solutions people have adopted, and if there are ways in which we can change best practices in the field to reward the effort that goes into our research. **Clarification**: Many of the excellent answers below had assumed a more polished form of publication than I had intended to convey in my question. I was referring merely to the accumulation of historical records associated with people in a tree, such as one that might be maintained at Ancestry.com. Clearly the copyright-able aspect of this is not the individual record, but the accumulation of such records to document an individual's (or a family) history. My gut feeling about this is that since it may have taken a considerable effort to put this together, that effort should be recognized. That was the point of my question: how best to protect that intellectual (and modest financial) effort?
2012/10/15
[ "https://genealogy.stackexchange.com/questions/1403", "https://genealogy.stackexchange.com", "https://genealogy.stackexchange.com/users/8/" ]
Personally, I'd use a combination of your (4) and (3): don't be too uptight about it, and make it as freely copyable as possible -- with a catch. > > Publish machine-readable information publicly, and contact those who use your information after the fact to ask them to give due credit. > > > For the purposes of this discussion, it seems like there are going to be four broad types of copying taking place: 1. People who will do a wholesale import of your tree into theirs, without thinking about attribution. 2. People who will retype information from your non-machine-readable tree into theirs, without thinking about attribution. 3. People who will selectively use information from your published tree with proper attribution. 4. People who will copy your information in any form, and intentionally remove attribution. Forget about the fourth case, there's not much you can do here that's worth the effort. In the third case, you're going to get credit, so that's fine. The first and second cases are the lazy copiers, and the second case is the one we really care about: since they have to retype (or cut & paste), and they're lazy, you're not going to get credit. You could largely eliminate the second case by making the work machine-readable -- anyone smart enough to do an import will just suck in your tree. And if you add citations to your own work, then they will import those citations and voilà, you get credit. (Of course, the risk is that they will still publish in a format that does not display source citations.) Automatically adding self-citations to a machine-readable format just prior to publication as a post-processing step should not be difficult (at least in theory!); whether it's worth the effort is a consideration for you, the author. As @Tom Wetmore mentioned in a comment on another answer, the copiers will often include your notes verbatim. If you simply want to know how much influence your work has had, include lots of notes! (Perhaps initial & date each note, too, for built-in self-citation?)
These comments have been very informative and have confirmed my own feelings. Since 1999 I have been working on my extended family trees, researching, connecting with newly found relatives, going to locations, cemeteries, finding skeletons in the closet and finding cherished pictures that would have been in the trash if I had not found them. This documentation of the lives of my family and all the work has been my passion. My hopes that the next generation will enjoy. Though, I find it disrespectful to see all this information incorporated by others, including relatives, and use it as their own "edition" of the family history, but not crediting or acknowledging the source of the information. I have received information from many distant relatives, and if not noted, I can later forget where it came from, but it is not the norm. As a writer I find it uncouth/unprofessional. It is not a matter of using the information, but of not giving the credit by acknowledgement to the person who did the work. It isn't about a fee, for I would rather give information to others than have them pay for it on genealogy sites that charge. I have had other researchers go out of their way to help me in research, and I appreciate them and give credit to them for their help. Just my rant...,for what it is worth. Thanks
1,403
Say you've spent a considerable amount of time, and perhaps some money as well, documenting a set of families. The work has paid off, and one of the rewards is to share it with people who may be living descendants of those documented by your research. The problem is that once you publish your research on a public web site of your choice, nothing prevents other (well-meaning) people—often your relatives!—from copying your work without attribution and incorporating the metadata and images related to the records you uncovered into their trees. In some areas of human intellectual endeavor (e.g., academic publishing), this would be considered plagiarism. In other areas [Creative Commons](http://creativecommons.org/) or other licensing may be used to allow reuse but to require people to give credit to the authors of the documents or other artifacts (e.g., software source code). How should genealogists approach this situation? I can imagine several possible tactics, each with its own trade-offs: 1. Don't publish anything in machine-readable ways. Making it difficult to incorporate information into other people's trees will deter some people; those who are not deterred are much more likely to cite the source. The downside is that fewer people will see the information because it will not be as easy to find, and that re-typing information from it (using it as a source) will be a source of errors. 2. Publish machine-readable information, but do so with privacy settings that require others to ask for documents. This makes it easier to keep track of who gets the information, and you might be able to ask them to attribute to work appropriately. No guarantees, of course. 3. Publish machine-readable information publicly, and contact those who use your information after the fact to ask them to give due credit. They are less likely to bother, but it does benefit more people who have access to the evidence you have collected. 4. Don't care about who does what. After all, as we used to say in an early (and successful) non-genealogical research project I was involved in, "[your ideas will be stolen, whether they are yours or not.](http://www.cs.cmu.edu/~mprice/quotes.htm)" I am curious to know which of these, or what other, solutions people have adopted, and if there are ways in which we can change best practices in the field to reward the effort that goes into our research. **Clarification**: Many of the excellent answers below had assumed a more polished form of publication than I had intended to convey in my question. I was referring merely to the accumulation of historical records associated with people in a tree, such as one that might be maintained at Ancestry.com. Clearly the copyright-able aspect of this is not the individual record, but the accumulation of such records to document an individual's (or a family) history. My gut feeling about this is that since it may have taken a considerable effort to put this together, that effort should be recognized. That was the point of my question: how best to protect that intellectual (and modest financial) effort?
2012/10/15
[ "https://genealogy.stackexchange.com/questions/1403", "https://genealogy.stackexchange.com", "https://genealogy.stackexchange.com/users/8/" ]
Personally, I'd use a combination of your (4) and (3): don't be too uptight about it, and make it as freely copyable as possible -- with a catch. > > Publish machine-readable information publicly, and contact those who use your information after the fact to ask them to give due credit. > > > For the purposes of this discussion, it seems like there are going to be four broad types of copying taking place: 1. People who will do a wholesale import of your tree into theirs, without thinking about attribution. 2. People who will retype information from your non-machine-readable tree into theirs, without thinking about attribution. 3. People who will selectively use information from your published tree with proper attribution. 4. People who will copy your information in any form, and intentionally remove attribution. Forget about the fourth case, there's not much you can do here that's worth the effort. In the third case, you're going to get credit, so that's fine. The first and second cases are the lazy copiers, and the second case is the one we really care about: since they have to retype (or cut & paste), and they're lazy, you're not going to get credit. You could largely eliminate the second case by making the work machine-readable -- anyone smart enough to do an import will just suck in your tree. And if you add citations to your own work, then they will import those citations and voilà, you get credit. (Of course, the risk is that they will still publish in a format that does not display source citations.) Automatically adding self-citations to a machine-readable format just prior to publication as a post-processing step should not be difficult (at least in theory!); whether it's worth the effort is a consideration for you, the author. As @Tom Wetmore mentioned in a comment on another answer, the copiers will often include your notes verbatim. If you simply want to know how much influence your work has had, include lots of notes! (Perhaps initial & date each note, too, for built-in self-citation?)
There are a couple of core issues here. In the research process, you will have typically assimilated information from some source and then used it as evidence for or against a number of conclusions. There are, therefore, a number of separate parts that could be published: the evidence, the citations for the sources, your conclusions derived from the available evidence, and your logic and reasoning in reaching those conclusions. The commonly-used term 'E&C' relates to the differentiation of Evidence from Conclusion but this over-simplifies the process by ignoring all that reasoning. I currently publish my conclusions in an online tree, although not my evidence or citations. This is primarily due to the restricted nature of the content provider's software. I would share more if the interface were greatly improved. I would be less inclined to freely share all my reasoning though. Note that my definitive data is not that published online - that is merely a restricted part of it. The second core issue relates to artefacts (or artifacts in the US) and concerns permissions and prohibitions on their sharing. Copyright is a formal prohibition but there will be many cases of informal permissions/prohibitions requested when these items were shared with yourself, most commonly by a relative. Although there may be no legal impediment to sharing such things, there will be a moral one that could be just as important to you. Things like photos and personal papers will commonly fall into this category. Our software should support some type of permission/prohibition marker for artefacts that can be used as a reminder to prevent accidental sharing. Note that I'm not suggesting some secure prevention mechanism in that software - not even for cases formalised copyright. Machine-readable copyright details would be too complicated to fully implement correctly, and a simple reminder/marker can be used for all of these cases mentioned here.
1,403
Say you've spent a considerable amount of time, and perhaps some money as well, documenting a set of families. The work has paid off, and one of the rewards is to share it with people who may be living descendants of those documented by your research. The problem is that once you publish your research on a public web site of your choice, nothing prevents other (well-meaning) people—often your relatives!—from copying your work without attribution and incorporating the metadata and images related to the records you uncovered into their trees. In some areas of human intellectual endeavor (e.g., academic publishing), this would be considered plagiarism. In other areas [Creative Commons](http://creativecommons.org/) or other licensing may be used to allow reuse but to require people to give credit to the authors of the documents or other artifacts (e.g., software source code). How should genealogists approach this situation? I can imagine several possible tactics, each with its own trade-offs: 1. Don't publish anything in machine-readable ways. Making it difficult to incorporate information into other people's trees will deter some people; those who are not deterred are much more likely to cite the source. The downside is that fewer people will see the information because it will not be as easy to find, and that re-typing information from it (using it as a source) will be a source of errors. 2. Publish machine-readable information, but do so with privacy settings that require others to ask for documents. This makes it easier to keep track of who gets the information, and you might be able to ask them to attribute to work appropriately. No guarantees, of course. 3. Publish machine-readable information publicly, and contact those who use your information after the fact to ask them to give due credit. They are less likely to bother, but it does benefit more people who have access to the evidence you have collected. 4. Don't care about who does what. After all, as we used to say in an early (and successful) non-genealogical research project I was involved in, "[your ideas will be stolen, whether they are yours or not.](http://www.cs.cmu.edu/~mprice/quotes.htm)" I am curious to know which of these, or what other, solutions people have adopted, and if there are ways in which we can change best practices in the field to reward the effort that goes into our research. **Clarification**: Many of the excellent answers below had assumed a more polished form of publication than I had intended to convey in my question. I was referring merely to the accumulation of historical records associated with people in a tree, such as one that might be maintained at Ancestry.com. Clearly the copyright-able aspect of this is not the individual record, but the accumulation of such records to document an individual's (or a family) history. My gut feeling about this is that since it may have taken a considerable effort to put this together, that effort should be recognized. That was the point of my question: how best to protect that intellectual (and modest financial) effort?
2012/10/15
[ "https://genealogy.stackexchange.com/questions/1403", "https://genealogy.stackexchange.com", "https://genealogy.stackexchange.com/users/8/" ]
Personally, I'd use a combination of your (4) and (3): don't be too uptight about it, and make it as freely copyable as possible -- with a catch. > > Publish machine-readable information publicly, and contact those who use your information after the fact to ask them to give due credit. > > > For the purposes of this discussion, it seems like there are going to be four broad types of copying taking place: 1. People who will do a wholesale import of your tree into theirs, without thinking about attribution. 2. People who will retype information from your non-machine-readable tree into theirs, without thinking about attribution. 3. People who will selectively use information from your published tree with proper attribution. 4. People who will copy your information in any form, and intentionally remove attribution. Forget about the fourth case, there's not much you can do here that's worth the effort. In the third case, you're going to get credit, so that's fine. The first and second cases are the lazy copiers, and the second case is the one we really care about: since they have to retype (or cut & paste), and they're lazy, you're not going to get credit. You could largely eliminate the second case by making the work machine-readable -- anyone smart enough to do an import will just suck in your tree. And if you add citations to your own work, then they will import those citations and voilà, you get credit. (Of course, the risk is that they will still publish in a format that does not display source citations.) Automatically adding self-citations to a machine-readable format just prior to publication as a post-processing step should not be difficult (at least in theory!); whether it's worth the effort is a consideration for you, the author. As @Tom Wetmore mentioned in a comment on another answer, the copiers will often include your notes verbatim. If you simply want to know how much influence your work has had, include lots of notes! (Perhaps initial & date each note, too, for built-in self-citation?)
As responsible and courteous users of published information, we all place a lot of emphasis on not breaching the copyright of others. Sometimes that focus gives us a distorted picture of just what we can hold copyright over in our own work. I certainly have no claim on any of the information in my records. The facts are in the public domain and I have no right to restrict others using them. The law recognises that I do have rights over the distinctive manner in which I present that information, or I would, if it was in any way distinctive. I did not devise or invent ancestor trees, descendant charts, ahnentafels, fan diagrams or any of the other standard forms we use. Every member of Ancestry is equally capable of presenting the same facts via the same tools to generate the same product. They do not breach my copyright when they do so. Of course my work is distinguished by its beautifully crafted chain of argument weighing conflicting evidence and scrupulously justifying each knowledge claim. But, guess what, no-one is trying to "steal" that. When I use my family history work as the basis for story-telling and other forms of writing about my family then I am (I hope) creating something genuinely new that is deserving of protection and it will receive that should I choose to enforce my rights regarding subsequent use. Early in my writing career I complained that my work deserved protection (from the evil Xeroxers, not downloaders) because of the effort I had put into its production. A grizzled editor replied "No more effort than a ditch digger, son, and he does not even get a copy to take home." I try not to be too precious about MY work in this field.
1,403
Say you've spent a considerable amount of time, and perhaps some money as well, documenting a set of families. The work has paid off, and one of the rewards is to share it with people who may be living descendants of those documented by your research. The problem is that once you publish your research on a public web site of your choice, nothing prevents other (well-meaning) people—often your relatives!—from copying your work without attribution and incorporating the metadata and images related to the records you uncovered into their trees. In some areas of human intellectual endeavor (e.g., academic publishing), this would be considered plagiarism. In other areas [Creative Commons](http://creativecommons.org/) or other licensing may be used to allow reuse but to require people to give credit to the authors of the documents or other artifacts (e.g., software source code). How should genealogists approach this situation? I can imagine several possible tactics, each with its own trade-offs: 1. Don't publish anything in machine-readable ways. Making it difficult to incorporate information into other people's trees will deter some people; those who are not deterred are much more likely to cite the source. The downside is that fewer people will see the information because it will not be as easy to find, and that re-typing information from it (using it as a source) will be a source of errors. 2. Publish machine-readable information, but do so with privacy settings that require others to ask for documents. This makes it easier to keep track of who gets the information, and you might be able to ask them to attribute to work appropriately. No guarantees, of course. 3. Publish machine-readable information publicly, and contact those who use your information after the fact to ask them to give due credit. They are less likely to bother, but it does benefit more people who have access to the evidence you have collected. 4. Don't care about who does what. After all, as we used to say in an early (and successful) non-genealogical research project I was involved in, "[your ideas will be stolen, whether they are yours or not.](http://www.cs.cmu.edu/~mprice/quotes.htm)" I am curious to know which of these, or what other, solutions people have adopted, and if there are ways in which we can change best practices in the field to reward the effort that goes into our research. **Clarification**: Many of the excellent answers below had assumed a more polished form of publication than I had intended to convey in my question. I was referring merely to the accumulation of historical records associated with people in a tree, such as one that might be maintained at Ancestry.com. Clearly the copyright-able aspect of this is not the individual record, but the accumulation of such records to document an individual's (or a family) history. My gut feeling about this is that since it may have taken a considerable effort to put this together, that effort should be recognized. That was the point of my question: how best to protect that intellectual (and modest financial) effort?
2012/10/15
[ "https://genealogy.stackexchange.com/questions/1403", "https://genealogy.stackexchange.com", "https://genealogy.stackexchange.com/users/8/" ]
I publish (or will publish) all the results of my research online, with exclusions mentioned elsewhere in discussions about privacy. I don't publish material to which other people hold the copyright (e.g. copyrighted images of sources, or oral testimony which I don't have permission to share). My own copyright statement says: > > Except where otherwise noted, I own the copyright on all material on this site — but not (of course) on the underlying facts. > > > If you want to make use of any of my copyright material, in your own family history research or for another purpose, contact me to ask permission. If you want to make use of the facts in your own research, it would be nice if you let me know. If you do re-publish any of the information here, please acknowledge me with a link to this site — and do check the facts for yourself. > > > My view is that I want to share the results of my research and it's impossible to stop other people using what I've done. If somebody asks permission to use copyrighted material, I'll almost certainly grant it although nobody has asked yet! And a polite request for acknowledgement may bear fruit. I take a less relaxed view to copyright violations with one of my other "hats" on, where there are commercial implications, but I'm losing nothing except maybe a little kudos if somebody rips off my family history research. I've already done the work and spent the money for my own satisfaction.
These comments have been very informative and have confirmed my own feelings. Since 1999 I have been working on my extended family trees, researching, connecting with newly found relatives, going to locations, cemeteries, finding skeletons in the closet and finding cherished pictures that would have been in the trash if I had not found them. This documentation of the lives of my family and all the work has been my passion. My hopes that the next generation will enjoy. Though, I find it disrespectful to see all this information incorporated by others, including relatives, and use it as their own "edition" of the family history, but not crediting or acknowledging the source of the information. I have received information from many distant relatives, and if not noted, I can later forget where it came from, but it is not the norm. As a writer I find it uncouth/unprofessional. It is not a matter of using the information, but of not giving the credit by acknowledgement to the person who did the work. It isn't about a fee, for I would rather give information to others than have them pay for it on genealogy sites that charge. I have had other researchers go out of their way to help me in research, and I appreciate them and give credit to them for their help. Just my rant...,for what it is worth. Thanks
1,403
Say you've spent a considerable amount of time, and perhaps some money as well, documenting a set of families. The work has paid off, and one of the rewards is to share it with people who may be living descendants of those documented by your research. The problem is that once you publish your research on a public web site of your choice, nothing prevents other (well-meaning) people—often your relatives!—from copying your work without attribution and incorporating the metadata and images related to the records you uncovered into their trees. In some areas of human intellectual endeavor (e.g., academic publishing), this would be considered plagiarism. In other areas [Creative Commons](http://creativecommons.org/) or other licensing may be used to allow reuse but to require people to give credit to the authors of the documents or other artifacts (e.g., software source code). How should genealogists approach this situation? I can imagine several possible tactics, each with its own trade-offs: 1. Don't publish anything in machine-readable ways. Making it difficult to incorporate information into other people's trees will deter some people; those who are not deterred are much more likely to cite the source. The downside is that fewer people will see the information because it will not be as easy to find, and that re-typing information from it (using it as a source) will be a source of errors. 2. Publish machine-readable information, but do so with privacy settings that require others to ask for documents. This makes it easier to keep track of who gets the information, and you might be able to ask them to attribute to work appropriately. No guarantees, of course. 3. Publish machine-readable information publicly, and contact those who use your information after the fact to ask them to give due credit. They are less likely to bother, but it does benefit more people who have access to the evidence you have collected. 4. Don't care about who does what. After all, as we used to say in an early (and successful) non-genealogical research project I was involved in, "[your ideas will be stolen, whether they are yours or not.](http://www.cs.cmu.edu/~mprice/quotes.htm)" I am curious to know which of these, or what other, solutions people have adopted, and if there are ways in which we can change best practices in the field to reward the effort that goes into our research. **Clarification**: Many of the excellent answers below had assumed a more polished form of publication than I had intended to convey in my question. I was referring merely to the accumulation of historical records associated with people in a tree, such as one that might be maintained at Ancestry.com. Clearly the copyright-able aspect of this is not the individual record, but the accumulation of such records to document an individual's (or a family) history. My gut feeling about this is that since it may have taken a considerable effort to put this together, that effort should be recognized. That was the point of my question: how best to protect that intellectual (and modest financial) effort?
2012/10/15
[ "https://genealogy.stackexchange.com/questions/1403", "https://genealogy.stackexchange.com", "https://genealogy.stackexchange.com/users/8/" ]
I try to take a practical approach: make it as easy as possible for people to give credit where it is due. One way towards this is to provide *actual citation text* for users to include in their sources (or in the material they cut-and-paste). The citation format will not always be the form they want, but it gets them most of the way there. An extension of this is to make GEDCOMs available which have the source credits built into them. These would have a source record for your article or website which has the reseach laid out, and would have references to that source record attached to each individual in the GEDCOM file. (It can also have textual references embedded as part of the included notes.) It's true that GEDCOM importers may intentionally or unintentionally strip off the source references, but at least you've made it easy to do the right thing. (Note: the source references are to your published research, not to the underlying genealogical sources, which are given in your published location. There are utilities available to help easily insert the source references into a GEDCOM.)
These comments have been very informative and have confirmed my own feelings. Since 1999 I have been working on my extended family trees, researching, connecting with newly found relatives, going to locations, cemeteries, finding skeletons in the closet and finding cherished pictures that would have been in the trash if I had not found them. This documentation of the lives of my family and all the work has been my passion. My hopes that the next generation will enjoy. Though, I find it disrespectful to see all this information incorporated by others, including relatives, and use it as their own "edition" of the family history, but not crediting or acknowledging the source of the information. I have received information from many distant relatives, and if not noted, I can later forget where it came from, but it is not the norm. As a writer I find it uncouth/unprofessional. It is not a matter of using the information, but of not giving the credit by acknowledgement to the person who did the work. It isn't about a fee, for I would rather give information to others than have them pay for it on genealogy sites that charge. I have had other researchers go out of their way to help me in research, and I appreciate them and give credit to them for their help. Just my rant...,for what it is worth. Thanks
1,403
Say you've spent a considerable amount of time, and perhaps some money as well, documenting a set of families. The work has paid off, and one of the rewards is to share it with people who may be living descendants of those documented by your research. The problem is that once you publish your research on a public web site of your choice, nothing prevents other (well-meaning) people—often your relatives!—from copying your work without attribution and incorporating the metadata and images related to the records you uncovered into their trees. In some areas of human intellectual endeavor (e.g., academic publishing), this would be considered plagiarism. In other areas [Creative Commons](http://creativecommons.org/) or other licensing may be used to allow reuse but to require people to give credit to the authors of the documents or other artifacts (e.g., software source code). How should genealogists approach this situation? I can imagine several possible tactics, each with its own trade-offs: 1. Don't publish anything in machine-readable ways. Making it difficult to incorporate information into other people's trees will deter some people; those who are not deterred are much more likely to cite the source. The downside is that fewer people will see the information because it will not be as easy to find, and that re-typing information from it (using it as a source) will be a source of errors. 2. Publish machine-readable information, but do so with privacy settings that require others to ask for documents. This makes it easier to keep track of who gets the information, and you might be able to ask them to attribute to work appropriately. No guarantees, of course. 3. Publish machine-readable information publicly, and contact those who use your information after the fact to ask them to give due credit. They are less likely to bother, but it does benefit more people who have access to the evidence you have collected. 4. Don't care about who does what. After all, as we used to say in an early (and successful) non-genealogical research project I was involved in, "[your ideas will be stolen, whether they are yours or not.](http://www.cs.cmu.edu/~mprice/quotes.htm)" I am curious to know which of these, or what other, solutions people have adopted, and if there are ways in which we can change best practices in the field to reward the effort that goes into our research. **Clarification**: Many of the excellent answers below had assumed a more polished form of publication than I had intended to convey in my question. I was referring merely to the accumulation of historical records associated with people in a tree, such as one that might be maintained at Ancestry.com. Clearly the copyright-able aspect of this is not the individual record, but the accumulation of such records to document an individual's (or a family) history. My gut feeling about this is that since it may have taken a considerable effort to put this together, that effort should be recognized. That was the point of my question: how best to protect that intellectual (and modest financial) effort?
2012/10/15
[ "https://genealogy.stackexchange.com/questions/1403", "https://genealogy.stackexchange.com", "https://genealogy.stackexchange.com/users/8/" ]
Personally, I'd use a combination of your (4) and (3): don't be too uptight about it, and make it as freely copyable as possible -- with a catch. > > Publish machine-readable information publicly, and contact those who use your information after the fact to ask them to give due credit. > > > For the purposes of this discussion, it seems like there are going to be four broad types of copying taking place: 1. People who will do a wholesale import of your tree into theirs, without thinking about attribution. 2. People who will retype information from your non-machine-readable tree into theirs, without thinking about attribution. 3. People who will selectively use information from your published tree with proper attribution. 4. People who will copy your information in any form, and intentionally remove attribution. Forget about the fourth case, there's not much you can do here that's worth the effort. In the third case, you're going to get credit, so that's fine. The first and second cases are the lazy copiers, and the second case is the one we really care about: since they have to retype (or cut & paste), and they're lazy, you're not going to get credit. You could largely eliminate the second case by making the work machine-readable -- anyone smart enough to do an import will just suck in your tree. And if you add citations to your own work, then they will import those citations and voilà, you get credit. (Of course, the risk is that they will still publish in a format that does not display source citations.) Automatically adding self-citations to a machine-readable format just prior to publication as a post-processing step should not be difficult (at least in theory!); whether it's worth the effort is a consideration for you, the author. As @Tom Wetmore mentioned in a comment on another answer, the copiers will often include your notes verbatim. If you simply want to know how much influence your work has had, include lots of notes! (Perhaps initial & date each note, too, for built-in self-citation?)
"how best to protect that intellectual (and modest financial) effort?" 1. Protect it from copycat relatives? Hide it. 2. Protect it from being lost forever? Share it. 3. Protect it from both? Share it with all your distant relatives, encourage them to share it, and include a request for old pictures or updates on their families. Few will respond, but they will save your contact info.
1,403
Say you've spent a considerable amount of time, and perhaps some money as well, documenting a set of families. The work has paid off, and one of the rewards is to share it with people who may be living descendants of those documented by your research. The problem is that once you publish your research on a public web site of your choice, nothing prevents other (well-meaning) people—often your relatives!—from copying your work without attribution and incorporating the metadata and images related to the records you uncovered into their trees. In some areas of human intellectual endeavor (e.g., academic publishing), this would be considered plagiarism. In other areas [Creative Commons](http://creativecommons.org/) or other licensing may be used to allow reuse but to require people to give credit to the authors of the documents or other artifacts (e.g., software source code). How should genealogists approach this situation? I can imagine several possible tactics, each with its own trade-offs: 1. Don't publish anything in machine-readable ways. Making it difficult to incorporate information into other people's trees will deter some people; those who are not deterred are much more likely to cite the source. The downside is that fewer people will see the information because it will not be as easy to find, and that re-typing information from it (using it as a source) will be a source of errors. 2. Publish machine-readable information, but do so with privacy settings that require others to ask for documents. This makes it easier to keep track of who gets the information, and you might be able to ask them to attribute to work appropriately. No guarantees, of course. 3. Publish machine-readable information publicly, and contact those who use your information after the fact to ask them to give due credit. They are less likely to bother, but it does benefit more people who have access to the evidence you have collected. 4. Don't care about who does what. After all, as we used to say in an early (and successful) non-genealogical research project I was involved in, "[your ideas will be stolen, whether they are yours or not.](http://www.cs.cmu.edu/~mprice/quotes.htm)" I am curious to know which of these, or what other, solutions people have adopted, and if there are ways in which we can change best practices in the field to reward the effort that goes into our research. **Clarification**: Many of the excellent answers below had assumed a more polished form of publication than I had intended to convey in my question. I was referring merely to the accumulation of historical records associated with people in a tree, such as one that might be maintained at Ancestry.com. Clearly the copyright-able aspect of this is not the individual record, but the accumulation of such records to document an individual's (or a family) history. My gut feeling about this is that since it may have taken a considerable effort to put this together, that effort should be recognized. That was the point of my question: how best to protect that intellectual (and modest financial) effort?
2012/10/15
[ "https://genealogy.stackexchange.com/questions/1403", "https://genealogy.stackexchange.com", "https://genealogy.stackexchange.com/users/8/" ]
There are a couple of core issues here. In the research process, you will have typically assimilated information from some source and then used it as evidence for or against a number of conclusions. There are, therefore, a number of separate parts that could be published: the evidence, the citations for the sources, your conclusions derived from the available evidence, and your logic and reasoning in reaching those conclusions. The commonly-used term 'E&C' relates to the differentiation of Evidence from Conclusion but this over-simplifies the process by ignoring all that reasoning. I currently publish my conclusions in an online tree, although not my evidence or citations. This is primarily due to the restricted nature of the content provider's software. I would share more if the interface were greatly improved. I would be less inclined to freely share all my reasoning though. Note that my definitive data is not that published online - that is merely a restricted part of it. The second core issue relates to artefacts (or artifacts in the US) and concerns permissions and prohibitions on their sharing. Copyright is a formal prohibition but there will be many cases of informal permissions/prohibitions requested when these items were shared with yourself, most commonly by a relative. Although there may be no legal impediment to sharing such things, there will be a moral one that could be just as important to you. Things like photos and personal papers will commonly fall into this category. Our software should support some type of permission/prohibition marker for artefacts that can be used as a reminder to prevent accidental sharing. Note that I'm not suggesting some secure prevention mechanism in that software - not even for cases formalised copyright. Machine-readable copyright details would be too complicated to fully implement correctly, and a simple reminder/marker can be used for all of these cases mentioned here.
These comments have been very informative and have confirmed my own feelings. Since 1999 I have been working on my extended family trees, researching, connecting with newly found relatives, going to locations, cemeteries, finding skeletons in the closet and finding cherished pictures that would have been in the trash if I had not found them. This documentation of the lives of my family and all the work has been my passion. My hopes that the next generation will enjoy. Though, I find it disrespectful to see all this information incorporated by others, including relatives, and use it as their own "edition" of the family history, but not crediting or acknowledging the source of the information. I have received information from many distant relatives, and if not noted, I can later forget where it came from, but it is not the norm. As a writer I find it uncouth/unprofessional. It is not a matter of using the information, but of not giving the credit by acknowledgement to the person who did the work. It isn't about a fee, for I would rather give information to others than have them pay for it on genealogy sites that charge. I have had other researchers go out of their way to help me in research, and I appreciate them and give credit to them for their help. Just my rant...,for what it is worth. Thanks
35,557,156
It seems that permission classes are ANDed when REST framework checks permissions. That is every permission class needs to return True for permission to be granted. This makes things like "if you are a superuser, you can access anything, but if you are a regular user you need explicit permissions" a bit hard to implement, you cannot just return False, it will fail the whole stack. Is there a way to maybe short-circuit permissions? Something like "if this permission is granted, stop checking?" or some other way to deal with cases like that?
2016/02/22
[ "https://Stackoverflow.com/questions/35557156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302268/" ]
Now DRF allows permissions to be composed using bitwise operators: & -and- and | -or-. [From the docs](https://www.django-rest-framework.org/api-guide/permissions/): > > Provided they inherit from `rest_framework.permissions.BasePermission`, permissions can be composed using standard Python bitwise operators. For example, IsAuthenticatedOrReadOnly could be written: > > > ```py from rest_framework.permissions import BasePermission, IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView class ReadOnly(BasePermission): def has_permission(self, request, view): return request.method in SAFE_METHODS class ExampleView(APIView): permission_classes = (IsAuthenticated|ReadOnly,) def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) ``` Edited: Please note there is a comma after `IsAuthenticated|ReadOnly`.
One way would be to add another [permission class](http://www.django-rest-framework.org/api-guide/permissions/) which combines existing classes the way you want it, e.g.: ``` class IsAdmin(BasePermission): """Allow access to admins""" def has_object_permission(self, request, view, obj): return request.user.is_admin() class IsOwner(BasePermission): """Allow access to owners""" def has_object_permission(self, request, view, obj): request.user.is_owner(obj) class IsAdminOrOwner(BasePermission): """Allow access to admins and owners""" def has_object_permission(*args): return (IsAdmin.has_object_permission(*args) or IsOwner.has_object_permission(*args)) ```
35,557,156
It seems that permission classes are ANDed when REST framework checks permissions. That is every permission class needs to return True for permission to be granted. This makes things like "if you are a superuser, you can access anything, but if you are a regular user you need explicit permissions" a bit hard to implement, you cannot just return False, it will fail the whole stack. Is there a way to maybe short-circuit permissions? Something like "if this permission is granted, stop checking?" or some other way to deal with cases like that?
2016/02/22
[ "https://Stackoverflow.com/questions/35557156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302268/" ]
Here is a generic solution: ``` from functools import reduce from rest_framework.decorators import permission_classes from rest_framework.permissions import BasePermission def any_of(*perm_classes): """Returns permission class that allows access for one of permission classes provided in perm_classes""" class Or(BasePermission): def has_permission(*args): allowed = [p.has_permission(*args) for p in perm_classes] return reduce(lambda x, y: x or y, allowed) return Or class IsAdmin(BasePermission): """Allow access to admins""" def has_object_permission(self, request, view, obj): return request.user.is_admin() class IsOwner(BasePermission): """Allow access to owners""" def has_object_permission(self, request, view, obj): request.user.is_owner(obj) """Allow access to admins and owners""" @permission_classes((any_of(IsAdmin, IsOwner),)) def you_function(request): # Your logic ... ```
The easiest way would be to separate them out with `|` in `permission_classes` attribute or `get_permissions` method, but if you have complex rules, you can specify those rules in the `check_permissions` method in the viewsets class that you are defining. Something like this: ``` class UserProfileViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = ProfileSerializerBase def create(self, request, *args, **kwargs): # Create rules here def get_permissions(self): if self.action == "destroy": # Only Super User or Org Admin can delete record permission_classes = [SAPermission, OAPermission] def check_permissions(self, request): """ Original check_permissions denies access if any one of the permission classes returns False, changing it so that it would deny access only if all classes returns False """ all_permissions = [] messages = [] code = [] for permission in self.get_permissions(): all_permissions.append(permission.has_permission(request, self)) messages.append(getattr(permission, "message", None)) code.append(getattr(permission, "code", None)) if True in all_permissions: return message = ",".join(i for i in messages if i) self.permission_denied( request, message=message if message else None, code=code[0], ) ```
35,557,156
It seems that permission classes are ANDed when REST framework checks permissions. That is every permission class needs to return True for permission to be granted. This makes things like "if you are a superuser, you can access anything, but if you are a regular user you need explicit permissions" a bit hard to implement, you cannot just return False, it will fail the whole stack. Is there a way to maybe short-circuit permissions? Something like "if this permission is granted, stop checking?" or some other way to deal with cases like that?
2016/02/22
[ "https://Stackoverflow.com/questions/35557156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302268/" ]
Now DRF allows permissions to be composed using bitwise operators: & -and- and | -or-. [From the docs](https://www.django-rest-framework.org/api-guide/permissions/): > > Provided they inherit from `rest_framework.permissions.BasePermission`, permissions can be composed using standard Python bitwise operators. For example, IsAuthenticatedOrReadOnly could be written: > > > ```py from rest_framework.permissions import BasePermission, IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView class ReadOnly(BasePermission): def has_permission(self, request, view): return request.method in SAFE_METHODS class ExampleView(APIView): permission_classes = (IsAuthenticated|ReadOnly,) def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) ``` Edited: Please note there is a comma after `IsAuthenticated|ReadOnly`.
The easiest way would be to separate them out with `|` in `permission_classes` attribute or `get_permissions` method, but if you have complex rules, you can specify those rules in the `check_permissions` method in the viewsets class that you are defining. Something like this: ``` class UserProfileViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = ProfileSerializerBase def create(self, request, *args, **kwargs): # Create rules here def get_permissions(self): if self.action == "destroy": # Only Super User or Org Admin can delete record permission_classes = [SAPermission, OAPermission] def check_permissions(self, request): """ Original check_permissions denies access if any one of the permission classes returns False, changing it so that it would deny access only if all classes returns False """ all_permissions = [] messages = [] code = [] for permission in self.get_permissions(): all_permissions.append(permission.has_permission(request, self)) messages.append(getattr(permission, "message", None)) code.append(getattr(permission, "code", None)) if True in all_permissions: return message = ",".join(i for i in messages if i) self.permission_denied( request, message=message if message else None, code=code[0], ) ```
35,557,156
It seems that permission classes are ANDed when REST framework checks permissions. That is every permission class needs to return True for permission to be granted. This makes things like "if you are a superuser, you can access anything, but if you are a regular user you need explicit permissions" a bit hard to implement, you cannot just return False, it will fail the whole stack. Is there a way to maybe short-circuit permissions? Something like "if this permission is granted, stop checking?" or some other way to deal with cases like that?
2016/02/22
[ "https://Stackoverflow.com/questions/35557156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302268/" ]
Now DRF allows permissions to be composed using bitwise operators: & -and- and | -or-. [From the docs](https://www.django-rest-framework.org/api-guide/permissions/): > > Provided they inherit from `rest_framework.permissions.BasePermission`, permissions can be composed using standard Python bitwise operators. For example, IsAuthenticatedOrReadOnly could be written: > > > ```py from rest_framework.permissions import BasePermission, IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView class ReadOnly(BasePermission): def has_permission(self, request, view): return request.method in SAFE_METHODS class ExampleView(APIView): permission_classes = (IsAuthenticated|ReadOnly,) def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) ``` Edited: Please note there is a comma after `IsAuthenticated|ReadOnly`.
You need to build your own [custom http://www.django-rest-framework.org/api-guide/permissions/#custom-permissions](http://www.django-rest-framework.org/api-guide/authentication/#custom-authentication) as described in the docs. Something like: ``` from rest_framework import permissions class IsAdminOrStaff(permissions.BasePermission): message = 'None of permissions requirements fulfilled.' def has_permission(self, request, view): return request.user.is_admin() or request.user.is_staff() ``` Then in your view: ``` permission_classes = (IsAdminOrStaff,) ```
35,557,156
It seems that permission classes are ANDed when REST framework checks permissions. That is every permission class needs to return True for permission to be granted. This makes things like "if you are a superuser, you can access anything, but if you are a regular user you need explicit permissions" a bit hard to implement, you cannot just return False, it will fail the whole stack. Is there a way to maybe short-circuit permissions? Something like "if this permission is granted, stop checking?" or some other way to deal with cases like that?
2016/02/22
[ "https://Stackoverflow.com/questions/35557156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302268/" ]
You need to build your own [custom http://www.django-rest-framework.org/api-guide/permissions/#custom-permissions](http://www.django-rest-framework.org/api-guide/authentication/#custom-authentication) as described in the docs. Something like: ``` from rest_framework import permissions class IsAdminOrStaff(permissions.BasePermission): message = 'None of permissions requirements fulfilled.' def has_permission(self, request, view): return request.user.is_admin() or request.user.is_staff() ``` Then in your view: ``` permission_classes = (IsAdminOrStaff,) ```
Here is a generic solution: ``` from functools import reduce from rest_framework.decorators import permission_classes from rest_framework.permissions import BasePermission def any_of(*perm_classes): """Returns permission class that allows access for one of permission classes provided in perm_classes""" class Or(BasePermission): def has_permission(*args): allowed = [p.has_permission(*args) for p in perm_classes] return reduce(lambda x, y: x or y, allowed) return Or class IsAdmin(BasePermission): """Allow access to admins""" def has_object_permission(self, request, view, obj): return request.user.is_admin() class IsOwner(BasePermission): """Allow access to owners""" def has_object_permission(self, request, view, obj): request.user.is_owner(obj) """Allow access to admins and owners""" @permission_classes((any_of(IsAdmin, IsOwner),)) def you_function(request): # Your logic ... ```
35,557,156
It seems that permission classes are ANDed when REST framework checks permissions. That is every permission class needs to return True for permission to be granted. This makes things like "if you are a superuser, you can access anything, but if you are a regular user you need explicit permissions" a bit hard to implement, you cannot just return False, it will fail the whole stack. Is there a way to maybe short-circuit permissions? Something like "if this permission is granted, stop checking?" or some other way to deal with cases like that?
2016/02/22
[ "https://Stackoverflow.com/questions/35557156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302268/" ]
Now DRF allows permissions to be composed using bitwise operators: & -and- and | -or-. [From the docs](https://www.django-rest-framework.org/api-guide/permissions/): > > Provided they inherit from `rest_framework.permissions.BasePermission`, permissions can be composed using standard Python bitwise operators. For example, IsAuthenticatedOrReadOnly could be written: > > > ```py from rest_framework.permissions import BasePermission, IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView class ReadOnly(BasePermission): def has_permission(self, request, view): return request.method in SAFE_METHODS class ExampleView(APIView): permission_classes = (IsAuthenticated|ReadOnly,) def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) ``` Edited: Please note there is a comma after `IsAuthenticated|ReadOnly`.
I think you might be able to use `django-rules` library here. [Link](https://github.com/dfunckt/django-rules) It is a rule based engine very similar to decision trees and it can be easily integrated with permissions\_class framework of DRF. The best part is you can perform set operations on simple permissions and create complex permissions from them. Example ``` >>> @rules.predicate >>> def is_admin(user): ... return user.is_staff ... >>> @rules.predicate >>> def is_object_owner(user, object): return object.owner == user ``` Predicates can do pretty much anything with the given arguments, but must always return True if the condition they check is true, False otherwise. Now combining these two predicates.. ``` is_object_editable = is_object_owner | is_admin ``` You can use this new predicate rule `is_object_editable` inside your has\_permissions method of permission class.
35,557,156
It seems that permission classes are ANDed when REST framework checks permissions. That is every permission class needs to return True for permission to be granted. This makes things like "if you are a superuser, you can access anything, but if you are a regular user you need explicit permissions" a bit hard to implement, you cannot just return False, it will fail the whole stack. Is there a way to maybe short-circuit permissions? Something like "if this permission is granted, stop checking?" or some other way to deal with cases like that?
2016/02/22
[ "https://Stackoverflow.com/questions/35557156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302268/" ]
I think you might be able to use `django-rules` library here. [Link](https://github.com/dfunckt/django-rules) It is a rule based engine very similar to decision trees and it can be easily integrated with permissions\_class framework of DRF. The best part is you can perform set operations on simple permissions and create complex permissions from them. Example ``` >>> @rules.predicate >>> def is_admin(user): ... return user.is_staff ... >>> @rules.predicate >>> def is_object_owner(user, object): return object.owner == user ``` Predicates can do pretty much anything with the given arguments, but must always return True if the condition they check is true, False otherwise. Now combining these two predicates.. ``` is_object_editable = is_object_owner | is_admin ``` You can use this new predicate rule `is_object_editable` inside your has\_permissions method of permission class.
Here is a generic solution: ``` from functools import reduce from rest_framework.decorators import permission_classes from rest_framework.permissions import BasePermission def any_of(*perm_classes): """Returns permission class that allows access for one of permission classes provided in perm_classes""" class Or(BasePermission): def has_permission(*args): allowed = [p.has_permission(*args) for p in perm_classes] return reduce(lambda x, y: x or y, allowed) return Or class IsAdmin(BasePermission): """Allow access to admins""" def has_object_permission(self, request, view, obj): return request.user.is_admin() class IsOwner(BasePermission): """Allow access to owners""" def has_object_permission(self, request, view, obj): request.user.is_owner(obj) """Allow access to admins and owners""" @permission_classes((any_of(IsAdmin, IsOwner),)) def you_function(request): # Your logic ... ```
35,557,156
It seems that permission classes are ANDed when REST framework checks permissions. That is every permission class needs to return True for permission to be granted. This makes things like "if you are a superuser, you can access anything, but if you are a regular user you need explicit permissions" a bit hard to implement, you cannot just return False, it will fail the whole stack. Is there a way to maybe short-circuit permissions? Something like "if this permission is granted, stop checking?" or some other way to deal with cases like that?
2016/02/22
[ "https://Stackoverflow.com/questions/35557156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302268/" ]
Now DRF allows permissions to be composed using bitwise operators: & -and- and | -or-. [From the docs](https://www.django-rest-framework.org/api-guide/permissions/): > > Provided they inherit from `rest_framework.permissions.BasePermission`, permissions can be composed using standard Python bitwise operators. For example, IsAuthenticatedOrReadOnly could be written: > > > ```py from rest_framework.permissions import BasePermission, IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView class ReadOnly(BasePermission): def has_permission(self, request, view): return request.method in SAFE_METHODS class ExampleView(APIView): permission_classes = (IsAuthenticated|ReadOnly,) def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) ``` Edited: Please note there is a comma after `IsAuthenticated|ReadOnly`.
Aside from the custom permission which is simpler approach mentioned in the [earlier answer](https://stackoverflow.com/a/35557412/764592), you can also look for an existing [3rd party](http://www.django-rest-framework.org/api-guide/permissions/#third-party-packages) that handle a much complex permission handling if necessary. As of Feb 2016, those handling complex condition permission includes: * [rest\_condition](https://github.com/caxap/rest_condition#example) * [djangorestframework-composed-permissions](https://djangorestframework-composed-permissions.readthedocs.org/en/latest/#permission-sets)
35,557,156
It seems that permission classes are ANDed when REST framework checks permissions. That is every permission class needs to return True for permission to be granted. This makes things like "if you are a superuser, you can access anything, but if you are a regular user you need explicit permissions" a bit hard to implement, you cannot just return False, it will fail the whole stack. Is there a way to maybe short-circuit permissions? Something like "if this permission is granted, stop checking?" or some other way to deal with cases like that?
2016/02/22
[ "https://Stackoverflow.com/questions/35557156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302268/" ]
I think you might be able to use `django-rules` library here. [Link](https://github.com/dfunckt/django-rules) It is a rule based engine very similar to decision trees and it can be easily integrated with permissions\_class framework of DRF. The best part is you can perform set operations on simple permissions and create complex permissions from them. Example ``` >>> @rules.predicate >>> def is_admin(user): ... return user.is_staff ... >>> @rules.predicate >>> def is_object_owner(user, object): return object.owner == user ``` Predicates can do pretty much anything with the given arguments, but must always return True if the condition they check is true, False otherwise. Now combining these two predicates.. ``` is_object_editable = is_object_owner | is_admin ``` You can use this new predicate rule `is_object_editable` inside your has\_permissions method of permission class.
Aside from the custom permission which is simpler approach mentioned in the [earlier answer](https://stackoverflow.com/a/35557412/764592), you can also look for an existing [3rd party](http://www.django-rest-framework.org/api-guide/permissions/#third-party-packages) that handle a much complex permission handling if necessary. As of Feb 2016, those handling complex condition permission includes: * [rest\_condition](https://github.com/caxap/rest_condition#example) * [djangorestframework-composed-permissions](https://djangorestframework-composed-permissions.readthedocs.org/en/latest/#permission-sets)
35,557,156
It seems that permission classes are ANDed when REST framework checks permissions. That is every permission class needs to return True for permission to be granted. This makes things like "if you are a superuser, you can access anything, but if you are a regular user you need explicit permissions" a bit hard to implement, you cannot just return False, it will fail the whole stack. Is there a way to maybe short-circuit permissions? Something like "if this permission is granted, stop checking?" or some other way to deal with cases like that?
2016/02/22
[ "https://Stackoverflow.com/questions/35557156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302268/" ]
I think you might be able to use `django-rules` library here. [Link](https://github.com/dfunckt/django-rules) It is a rule based engine very similar to decision trees and it can be easily integrated with permissions\_class framework of DRF. The best part is you can perform set operations on simple permissions and create complex permissions from them. Example ``` >>> @rules.predicate >>> def is_admin(user): ... return user.is_staff ... >>> @rules.predicate >>> def is_object_owner(user, object): return object.owner == user ``` Predicates can do pretty much anything with the given arguments, but must always return True if the condition they check is true, False otherwise. Now combining these two predicates.. ``` is_object_editable = is_object_owner | is_admin ``` You can use this new predicate rule `is_object_editable` inside your has\_permissions method of permission class.
The easiest way would be to separate them out with `|` in `permission_classes` attribute or `get_permissions` method, but if you have complex rules, you can specify those rules in the `check_permissions` method in the viewsets class that you are defining. Something like this: ``` class UserProfileViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = ProfileSerializerBase def create(self, request, *args, **kwargs): # Create rules here def get_permissions(self): if self.action == "destroy": # Only Super User or Org Admin can delete record permission_classes = [SAPermission, OAPermission] def check_permissions(self, request): """ Original check_permissions denies access if any one of the permission classes returns False, changing it so that it would deny access only if all classes returns False """ all_permissions = [] messages = [] code = [] for permission in self.get_permissions(): all_permissions.append(permission.has_permission(request, self)) messages.append(getattr(permission, "message", None)) code.append(getattr(permission, "code", None)) if True in all_permissions: return message = ",".join(i for i in messages if i) self.permission_denied( request, message=message if message else None, code=code[0], ) ```
60,238
I've got a low power application which will be powered from a Li coin cell. I've achieved satisfactory sleeping current with my chosen MCU. The application ADC IC however is a different matter: 900µA while inactive -- way too much for a coin cell application. So I thought why not isolate the power to the ADC when it's not in use. Two ideas came to mind: a high-side FET on the ADC's Vdd or just connecting the ADC's Vdd (or Vss) pin to one of the MCU GPIO pins (assuming current is within the MCU's source/sink spec). I assumed there would be plenty of articles, app notes etc discussing this idea, but I've yet to find anything on line. Before I start experimenting, can anyone point me to any relevant articles/app notes online? Or is it just a bad idea? and if so why? (Ya, know most MCUs have ADCs built in. For reasons beyond the scope of the query, I really must use this external ADC IC.) Thanks!
2013/03/08
[ "https://electronics.stackexchange.com/questions/60238", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/18937/" ]
Powering a device through a GPIO pin is usually a bad idea. In the very low power regime, perhaps you could get away with it, but I would not recommend it unless you have very severe constraints. You've already noted that you've checked that the ADC's requirement is lower than the pin's drive capability. That is typically what lot of people don't bother checking. If the consumption is within the required limits, then you may be fine on that count. However, make sure that any transient current requirements from the ADC are also contained within the GPIO drive capability. You would at the very least require reasonably heavy decoupling on the ADC supply. Remember the fact that the GPIO output isn't a low impedance supply line, and will be slower to respond to transient current requirements. Secondly, since you're using an ADC, and at that an ADC that isn't built into a uC (which would be what you should be doing for very low power consumption), I'm presuming you have some requirements which aren't satisfied by the internal ADC. The GPIO, not being a supply line, and more importantly, being a GPIO of a microcontroller, will most definitely be contaminated by atleast the clock frequency of the uC, its harmonics, and possibly subharmonics. Since you're also going to be driving some substantial current through it, I would not be surprised if other effects are brought in as well. You may even end up seeing small components of your SPI/I2C/what have you in the supply, depending on which GPIO you use and how heavy the decoupling is. If ADC resolution and noise performance is important, then perhaps this is not such a good idea even if the GPIOs seem to be capable of driving the IC. The high side FET is a much better bet, and is safer. You could also consider using any number of power related ICs which have Enable control, such as LDOs and the like. An LDO close to the ADC supply may also help with improving performance. Note, though, that this means your ADC will have to run at a slightly lower voltage. This will happen with a simple transistor switch as well, and with a low Rdson FET the effect will, admittedly, be much smaller, but it will exist. One thing that you should note is that connecting an unpowered IC's digital lines to GPIOs of a powered uC is not a good idea. You will end up powering up your ADC through its digital IOs and cause strange, and potentially dangerous behaviour. Specifically, I would be surprised if your ADC did not respond even when OFF. This is capable of causing long term degradation, and eats into the advantage of power saving in the first place. In order to make it turn off well, you should use a level translating buffer for every digital line between the two with the ability to disable (tristate) the outputs. This can be done either using an EN pin, perhaps, or using a buffer with other mechanisms to disable (The SN74LVC1T45 tristates if the supply on one side is pulled to ground, for instance). Whether the scheme is useful depends on the consumption of the buffer in it's OFF state, the consumption in it's ON state, and the duty cycle (the fraction of time you want to turn it ON for), and the ADC consumption (900uA) that you can save by doing this. If you are very careful, you may be able to avoid the need for the buffers by tristating the uC IOs that are connected to the ADC before shutting it off, and thereby producing about the same effect.
Yes, you can do that, just make sure all the constraints are met. I have done this a few times. Using a microcontroller output to actually power a small circuit instead of switcing its power can be a useful way to save space. I used this in one project, for example, to turn on a ultrasound receiver analog front end only when needed. Other than the obvious problem of limited current available from the output pin, you have to watch noise from the micro getting into the switched circuit and deal with transient currents drawn by the circuit. Adding a cap to ground on the digital output pin helps with both problems, but you also have to consider how much capacitance the micro can drive while switching the line on or off. This is not something you should do lightly, and you need to think about the issues carefully, but after you've done your homework and it still makes sense, go ahead.
60,238
I've got a low power application which will be powered from a Li coin cell. I've achieved satisfactory sleeping current with my chosen MCU. The application ADC IC however is a different matter: 900µA while inactive -- way too much for a coin cell application. So I thought why not isolate the power to the ADC when it's not in use. Two ideas came to mind: a high-side FET on the ADC's Vdd or just connecting the ADC's Vdd (or Vss) pin to one of the MCU GPIO pins (assuming current is within the MCU's source/sink spec). I assumed there would be plenty of articles, app notes etc discussing this idea, but I've yet to find anything on line. Before I start experimenting, can anyone point me to any relevant articles/app notes online? Or is it just a bad idea? and if so why? (Ya, know most MCUs have ADCs built in. For reasons beyond the scope of the query, I really must use this external ADC IC.) Thanks!
2013/03/08
[ "https://electronics.stackexchange.com/questions/60238", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/18937/" ]
Powering a device through a GPIO pin is usually a bad idea. In the very low power regime, perhaps you could get away with it, but I would not recommend it unless you have very severe constraints. You've already noted that you've checked that the ADC's requirement is lower than the pin's drive capability. That is typically what lot of people don't bother checking. If the consumption is within the required limits, then you may be fine on that count. However, make sure that any transient current requirements from the ADC are also contained within the GPIO drive capability. You would at the very least require reasonably heavy decoupling on the ADC supply. Remember the fact that the GPIO output isn't a low impedance supply line, and will be slower to respond to transient current requirements. Secondly, since you're using an ADC, and at that an ADC that isn't built into a uC (which would be what you should be doing for very low power consumption), I'm presuming you have some requirements which aren't satisfied by the internal ADC. The GPIO, not being a supply line, and more importantly, being a GPIO of a microcontroller, will most definitely be contaminated by atleast the clock frequency of the uC, its harmonics, and possibly subharmonics. Since you're also going to be driving some substantial current through it, I would not be surprised if other effects are brought in as well. You may even end up seeing small components of your SPI/I2C/what have you in the supply, depending on which GPIO you use and how heavy the decoupling is. If ADC resolution and noise performance is important, then perhaps this is not such a good idea even if the GPIOs seem to be capable of driving the IC. The high side FET is a much better bet, and is safer. You could also consider using any number of power related ICs which have Enable control, such as LDOs and the like. An LDO close to the ADC supply may also help with improving performance. Note, though, that this means your ADC will have to run at a slightly lower voltage. This will happen with a simple transistor switch as well, and with a low Rdson FET the effect will, admittedly, be much smaller, but it will exist. One thing that you should note is that connecting an unpowered IC's digital lines to GPIOs of a powered uC is not a good idea. You will end up powering up your ADC through its digital IOs and cause strange, and potentially dangerous behaviour. Specifically, I would be surprised if your ADC did not respond even when OFF. This is capable of causing long term degradation, and eats into the advantage of power saving in the first place. In order to make it turn off well, you should use a level translating buffer for every digital line between the two with the ability to disable (tristate) the outputs. This can be done either using an EN pin, perhaps, or using a buffer with other mechanisms to disable (The SN74LVC1T45 tristates if the supply on one side is pulled to ground, for instance). Whether the scheme is useful depends on the consumption of the buffer in it's OFF state, the consumption in it's ON state, and the duty cycle (the fraction of time you want to turn it ON for), and the ADC consumption (900uA) that you can save by doing this. If you are very careful, you may be able to avoid the need for the buffers by tristating the uC IOs that are connected to the ADC before shutting it off, and thereby producing about the same effect.
Yes, you can do this. And many have. For example, [Adafruit shows this being done for a ds1307 RTC on an adruino, powered by two gpio (as vcc and gnd)](http://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/wiring-it-up). This is also done for Nokia LCDs, which only need 1 mA for the screen (The backlight leds are a different story, but can still be done by gpio). A power source is a power source. As long as your current draw is low, (Or you can tolerate voltage sag due to current draw on the mcu's port pins), you can do it. Now, it does depend on how clean the gpio output is. Some ICs are less likely to complain about a slightly dirty line than others. An ADC might be one of those that arn't the best option. A dirty source might affect the ADC's resolution or reliability. It might make the external ADC worse than the internal one. Like others have mentioned, a cap might help. **It's unlikely to fry the ADC, so best bet? Wire it up, and run it through some calibration tests. If it works, go with it. If it doesn't, use a npn transistor or similar fet to cut power. Just one thing. make sure that you switch the data pins into inputs when the IC is turned off, and wait until after you turn the power pin on before switching them into the mode they need to be.**
2,469,933
While Compiling the WPF Application for many times in a day it give following error 'Exception of type 'System.OutOfMemoryException' was thrown.' Can anyone know why this error occured and how to remove that error. But if visual studio is restarted then there is no such problem. thanks in advance
2010/03/18
[ "https://Stackoverflow.com/questions/2469933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172718/" ]
It could be that your compiler has a memory leak, or that a plugin of your compiler has a memory leak. There is not your fault, though. It's most probably your compiler's fault. You are encouraged to reproduce the problem and send it to your compiler vendor for a detail investigation.
This happens to me frequently with visual studio 2008. I just assume there's a memory leak somewhere due to poor coding on Microsoft's part. Whenever i see this error I close down and reopen visual studio and it compiles without a hitch.
2,469,933
While Compiling the WPF Application for many times in a day it give following error 'Exception of type 'System.OutOfMemoryException' was thrown.' Can anyone know why this error occured and how to remove that error. But if visual studio is restarted then there is no such problem. thanks in advance
2010/03/18
[ "https://Stackoverflow.com/questions/2469933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172718/" ]
This happens to me frequently with visual studio 2008. I just assume there's a memory leak somewhere due to poor coding on Microsoft's part. Whenever i see this error I close down and reopen visual studio and it compiles without a hitch.
Is your machine up to the minimum specification for developing WPF applications
2,469,933
While Compiling the WPF Application for many times in a day it give following error 'Exception of type 'System.OutOfMemoryException' was thrown.' Can anyone know why this error occured and how to remove that error. But if visual studio is restarted then there is no such problem. thanks in advance
2010/03/18
[ "https://Stackoverflow.com/questions/2469933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172718/" ]
It could be that your compiler has a memory leak, or that a plugin of your compiler has a memory leak. There is not your fault, though. It's most probably your compiler's fault. You are encouraged to reproduce the problem and send it to your compiler vendor for a detail investigation.
Is your machine up to the minimum specification for developing WPF applications
2,469,933
While Compiling the WPF Application for many times in a day it give following error 'Exception of type 'System.OutOfMemoryException' was thrown.' Can anyone know why this error occured and how to remove that error. But if visual studio is restarted then there is no such problem. thanks in advance
2010/03/18
[ "https://Stackoverflow.com/questions/2469933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172718/" ]
It could be that your compiler has a memory leak, or that a plugin of your compiler has a memory leak. There is not your fault, though. It's most probably your compiler's fault. You are encouraged to reproduce the problem and send it to your compiler vendor for a detail investigation.
It sounds like you are saying that after compiling a WPF application many times in Visual Studio you receive an `OutOfMemoryException` error. Can you elaborate further on where exactly this error shows up? * In the Designer * In the output window * etc ... It's possible that there is a bug in either a 3rd party hosted control on the designer or in Visual Studio itself. If you are not using any 3rd party controls then I encourage you to file a bug on connect for the issue. * <http://connect.microsoft.com>
2,469,933
While Compiling the WPF Application for many times in a day it give following error 'Exception of type 'System.OutOfMemoryException' was thrown.' Can anyone know why this error occured and how to remove that error. But if visual studio is restarted then there is no such problem. thanks in advance
2010/03/18
[ "https://Stackoverflow.com/questions/2469933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172718/" ]
It sounds like you are saying that after compiling a WPF application many times in Visual Studio you receive an `OutOfMemoryException` error. Can you elaborate further on where exactly this error shows up? * In the Designer * In the output window * etc ... It's possible that there is a bug in either a 3rd party hosted control on the designer or in Visual Studio itself. If you are not using any 3rd party controls then I encourage you to file a bug on connect for the issue. * <http://connect.microsoft.com>
Is your machine up to the minimum specification for developing WPF applications
4,058,657
> > For a set $\mathscr{F}$, define > > > $$\bigcup!\mathscr{F}=\{x\mid\exists!A\in\mathscr{F}\, x\in A\}$$ > > > (a) If $\mathscr{F}=\big\{\{1,2,3\},\{2,3,4\},\{3,4,5\}\big\}$, what is $\bigcup!\mathscr{F}$? > > > (b) Suppose $\mathscr{F}$ is a set and $\bigcup!\mathscr{F}\cap\bigcap\mathscr{F}\ne\varnothing$. Show that $\mathscr{F}$ has exactly one element. > > > I do not know how to write a formal proof to these, please could someone teach me how to write these types of formal proofs? I am pretty sure it has to do with existence and uniqueness.
2021/03/12
[ "https://math.stackexchange.com/questions/4058657", "https://math.stackexchange.com", "https://math.stackexchange.com/users/899057/" ]
For (b). Assume $[\cup !\mathscr F ]\cap [\cap \mathscr F]\ne \emptyset.$ If $f,g\in\mathscr F$ with $f\ne g$ then $\cup !\mathscr F\subseteq (f\setminus g)\cup (g\setminus f)$ and $\cap\mathscr F)\subseteq f\cap g.$ But for any $f,g$ we have $[(f\setminus g)\cup (g\setminus f)]\,\cap \, [f\cap g]=\emptyset.$ Therefore $\mathscr F$ has at most 1 member. If $\mathscr F=\emptyset$ then $[\cup !\mathscr F ]\cap [\cap \mathscr F]\subseteq\cup !\mathscr F=\emptyset.$ Therefore $\mathscr F$ has at least 1 member.
$(a)$ is $\{1,5\}$, the full union is $\{1,2,3,4,5\}$ but $2,3$ and $4$ occur in two sets in $\mathcal{F}$, so are not in $\bigcup !\mathcal{F}$. $(b)$: Let $x \in \bigcup !\mathcal{F}$ and $x \in \bigcap \mathcal{F}$. Suppose that $F\_1, F\_2 \in \mathcal{F}$ exist with $F\_1 \neq F\_2$. Then $x \in F\_1 \cap F\_2$ as $x$ lies in all members of $\mathcal{F}$ by assumption. But then $x$ cannot be in $\bigcup ! \mathcal{F}$ by definition as it is not in a **unique** member of $\mathcal{F}$, but in at least two. This contradiction shows that $\mathcal{F}$ cannot have two distinct elements and as no elements is ruled out too (an empty union is always empty, also with $!$) $\mathcal{F}$ has a single member, as required.