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
2,771,868
Is there any way we can access other JVM's Heap memory? Will this be possible if I know the memory reference/address?
2010/05/05
[ "https://Stackoverflow.com/questions/2771868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327813/" ]
The closest thing that meets your needs is probably a distributed object cache such as [Coherence](http://www.oracle.com/technology/products/coherence/index.html) or [Terracotta](http://www.terracotta.org/). With these technologies different JVM instances can share objects.
No, that's completely impossible. If you want shared memory, use threads.
2,771,868
Is there any way we can access other JVM's Heap memory? Will this be possible if I know the memory reference/address?
2010/05/05
[ "https://Stackoverflow.com/questions/2771868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327813/" ]
The closest thing that meets your needs is probably a distributed object cache such as [Coherence](http://www.oracle.com/technology/products/coherence/index.html) or [Terracotta](http://www.terracotta.org/). With these technologies different JVM instances can share objects.
What you want to do sound impossible. If you want to access data of another java program and can't implement som interface in the program in question (such as some RMI interface,or somsocket) the closest thing I can come to think of is to go through a debugger or the [JVMTI](http://java.sun.com/j2se/1.5.0/docs/guide/jvmti/index.html) > > The JVM TM Tool Interface (JVM TI) is a new native programming interface for use by tools. It provides both a way to inspect the state and to control the execution of applications running in the Java virtual machine (JVM). JVM applications running in the TI supports the full breadth of tools that need access to JVM state, including but not limited to: profiling, debugging, monitoring, thread analysis, and coverage analysis tools. > > >
2,771,868
Is there any way we can access other JVM's Heap memory? Will this be possible if I know the memory reference/address?
2010/05/05
[ "https://Stackoverflow.com/questions/2771868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327813/" ]
The closest thing that meets your needs is probably a distributed object cache such as [Coherence](http://www.oracle.com/technology/products/coherence/index.html) or [Terracotta](http://www.terracotta.org/). With these technologies different JVM instances can share objects.
Not directly, in the manner you seem to be implying. You would need to have the "other" JVM expose access to these objects via some kind of service like RMI/SOAP, or through distributed object methods like Terracotta, and then call the relevant service methods to obtain the object. Even then, in the vast majority of cases you would end up with an object with the same value, but which was distinct (i.e. calling `setFoo` on your object would not change the corresponding object in the other JVM). If you want to do this, you would need to go with something like Terracotta which will handle the magic for you. But as with a lot of these questions, if you want to do this you should probably rework your design. Different processes should be able to coordinate between themselves without requiring on mutating the exact same instances of an object... :-)
2,771,868
Is there any way we can access other JVM's Heap memory? Will this be possible if I know the memory reference/address?
2010/05/05
[ "https://Stackoverflow.com/questions/2771868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327813/" ]
The closest thing that meets your needs is probably a distributed object cache such as [Coherence](http://www.oracle.com/technology/products/coherence/index.html) or [Terracotta](http://www.terracotta.org/). With these technologies different JVM instances can share objects.
> > Is there any way we can access other JVM's Heap memory? > > > I imagine you are thinking of doing something like creating a shared memory segment and mapping it into the address space of two JVMs. It won't work. You could use JNI to create and map the shared segment, but you won't be able to convince the two JVMs to use that memory as heap memory. And if you got past that hurdle, it would all go horribly wrong due to the respective JVM's memory allocators and garbage collectors interfering with each other. > > Will this be possible if I know the memory reference/address? > > > That won't make any difference.
2,771,868
Is there any way we can access other JVM's Heap memory? Will this be possible if I know the memory reference/address?
2010/05/05
[ "https://Stackoverflow.com/questions/2771868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327813/" ]
> > Is there any way we can access other JVM's Heap memory? > > > I imagine you are thinking of doing something like creating a shared memory segment and mapping it into the address space of two JVMs. It won't work. You could use JNI to create and map the shared segment, but you won't be able to convince the two JVMs to use that memory as heap memory. And if you got past that hurdle, it would all go horribly wrong due to the respective JVM's memory allocators and garbage collectors interfering with each other. > > Will this be possible if I know the memory reference/address? > > > That won't make any difference.
No, that's completely impossible. If you want shared memory, use threads.
2,771,868
Is there any way we can access other JVM's Heap memory? Will this be possible if I know the memory reference/address?
2010/05/05
[ "https://Stackoverflow.com/questions/2771868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327813/" ]
> > Is there any way we can access other JVM's Heap memory? > > > I imagine you are thinking of doing something like creating a shared memory segment and mapping it into the address space of two JVMs. It won't work. You could use JNI to create and map the shared segment, but you won't be able to convince the two JVMs to use that memory as heap memory. And if you got past that hurdle, it would all go horribly wrong due to the respective JVM's memory allocators and garbage collectors interfering with each other. > > Will this be possible if I know the memory reference/address? > > > That won't make any difference.
What you want to do sound impossible. If you want to access data of another java program and can't implement som interface in the program in question (such as some RMI interface,or somsocket) the closest thing I can come to think of is to go through a debugger or the [JVMTI](http://java.sun.com/j2se/1.5.0/docs/guide/jvmti/index.html) > > The JVM TM Tool Interface (JVM TI) is a new native programming interface for use by tools. It provides both a way to inspect the state and to control the execution of applications running in the Java virtual machine (JVM). JVM applications running in the TI supports the full breadth of tools that need access to JVM state, including but not limited to: profiling, debugging, monitoring, thread analysis, and coverage analysis tools. > > >
2,771,868
Is there any way we can access other JVM's Heap memory? Will this be possible if I know the memory reference/address?
2010/05/05
[ "https://Stackoverflow.com/questions/2771868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327813/" ]
> > Is there any way we can access other JVM's Heap memory? > > > I imagine you are thinking of doing something like creating a shared memory segment and mapping it into the address space of two JVMs. It won't work. You could use JNI to create and map the shared segment, but you won't be able to convince the two JVMs to use that memory as heap memory. And if you got past that hurdle, it would all go horribly wrong due to the respective JVM's memory allocators and garbage collectors interfering with each other. > > Will this be possible if I know the memory reference/address? > > > That won't make any difference.
Not directly, in the manner you seem to be implying. You would need to have the "other" JVM expose access to these objects via some kind of service like RMI/SOAP, or through distributed object methods like Terracotta, and then call the relevant service methods to obtain the object. Even then, in the vast majority of cases you would end up with an object with the same value, but which was distinct (i.e. calling `setFoo` on your object would not change the corresponding object in the other JVM). If you want to do this, you would need to go with something like Terracotta which will handle the magic for you. But as with a lot of these questions, if you want to do this you should probably rework your design. Different processes should be able to coordinate between themselves without requiring on mutating the exact same instances of an object... :-)
17,253,252
I have built a binary search tree for my program. This is my code: ``` struct node { int steps; int x; int y; struct node *left; struct node *right; }*head; typedef struct node *Node; Node createStepsBinaryTree(Node head, int newStepsInt, int x, int y){ if (head == NULL) { head = (Node)malloc(sizeof(Node)); if (head==NULL) { return NULL; }else{ head->steps = newStepsInt; head->x = x; head->y = y; head->left = head->right = NULL; } }else{ if (head->steps > newStepsInt) { head->left = createStepsBinaryTree(head->left, newStepsInt, x, y); }else{ head->right = createStepsBinaryTree(head->right, newStepsInt, x, y); } } return head; } ``` This is how i call this function from another recursive function: ``` Coor insertDataToTree(Node stepsTree,Coor root, int x, int y, int map[length][length], int steps){ steps++; stepsTree = createStepsBinaryTree(stepsTree, steps, x, y); . . . ``` And this is how i'm entering it to that recursive function: ``` Node stepsTree = NULL; root = insertDataToTree(stepsTree,root, startPoint.x, startPoint.y, map, startPoint.steps); ``` Now for the main issue i'm having: It runs great the first two runs, but then it runs for the third time through the two structs that are in that tree, but the when it should give itself a NULL struct it gives something that is REALLY close to NULL. It shows (Node \*)0x000000000000000000001. Does anyone know how can i stop this madness?? :)
2013/06/22
[ "https://Stackoverflow.com/questions/17253252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1461635/" ]
As @wildplasser noted, you're allocating enough space for a Node, which is a pointer type. You either need to change your code so that Node is a struct or allocate sizeof(struct node) bytes in your malloc. I strongly suggest you not hide your pointer in a typedef - this is one of several examples of how that causes problems.
``` head = (struct node*)malloc(sizeof( struct node ) ) ``` though sizeof(\*Node) is accepted by most compilers.
8,816,194
> > **Possible Duplicate:** > > [How to parse and process HTML with PHP?](https://stackoverflow.com/questions/3577641/how-to-parse-and-process-html-with-php) > > > I need to fetch the second column of the given HTML table using PHP. How can I do it? **References:** Table to be parsed: <http://bit.ly/Ak2xay> HTML code of this table: <http://bit.ly/ACdLMn>
2012/01/11
[ "https://Stackoverflow.com/questions/8816194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162266/" ]
For tidy HTML codes, one of the parsing approach can be DOM. DOM divides your HTML code into objects and then allows you to call the desired object and its values/tag name etc. The official documentation of PHP HTML DOM parsing is available at <http://php.net/manual/en/book.dom.php> For finding the values of second column for the given table following DOM implementation can be done: ``` <?php $data = file_get_contents('http://mytemporalbucket.s3.amazonaws.com/code.txt'); $dom = new domDocument; @$dom->loadHTML($data); $dom->preserveWhiteSpace = false; $tables = $dom->getElementsByTagName('table'); $rows = $tables->item(1)->getElementsByTagName('tr'); foreach ($rows as $row) { $cols = $row->getElementsByTagName('td'); echo $cols[2]; } ?> ``` **Reference:** Customized the code provided at [How to parse this table and extract data from it?](https://stackoverflow.com/questions/6818335/how-to-parse-this-table-and-extract-data-from-it) to match this question's demand.
This may be of use to you, there are even examples to get you started. <http://simplehtmldom.sourceforge.net/>
8,816,194
> > **Possible Duplicate:** > > [How to parse and process HTML with PHP?](https://stackoverflow.com/questions/3577641/how-to-parse-and-process-html-with-php) > > > I need to fetch the second column of the given HTML table using PHP. How can I do it? **References:** Table to be parsed: <http://bit.ly/Ak2xay> HTML code of this table: <http://bit.ly/ACdLMn>
2012/01/11
[ "https://Stackoverflow.com/questions/8816194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162266/" ]
Using phpQuery <http://code.google.com/p/phpquery/> you could do ``` $file = LINK OR NAME OF YOUR FILE phpQuery::newDocumentFile($file); $data = pq('UNIQUE COLUMN ID OR CLASS AS YOU WOULD FOR CSS ex: .class #id')->html(); echo $data. ```
This may be of use to you, there are even examples to get you started. <http://simplehtmldom.sourceforge.net/>
8,816,194
> > **Possible Duplicate:** > > [How to parse and process HTML with PHP?](https://stackoverflow.com/questions/3577641/how-to-parse-and-process-html-with-php) > > > I need to fetch the second column of the given HTML table using PHP. How can I do it? **References:** Table to be parsed: <http://bit.ly/Ak2xay> HTML code of this table: <http://bit.ly/ACdLMn>
2012/01/11
[ "https://Stackoverflow.com/questions/8816194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162266/" ]
For tidy HTML codes, one of the parsing approach can be DOM. DOM divides your HTML code into objects and then allows you to call the desired object and its values/tag name etc. The official documentation of PHP HTML DOM parsing is available at <http://php.net/manual/en/book.dom.php> For finding the values of second column for the given table following DOM implementation can be done: ``` <?php $data = file_get_contents('http://mytemporalbucket.s3.amazonaws.com/code.txt'); $dom = new domDocument; @$dom->loadHTML($data); $dom->preserveWhiteSpace = false; $tables = $dom->getElementsByTagName('table'); $rows = $tables->item(1)->getElementsByTagName('tr'); foreach ($rows as $row) { $cols = $row->getElementsByTagName('td'); echo $cols[2]; } ?> ``` **Reference:** Customized the code provided at [How to parse this table and extract data from it?](https://stackoverflow.com/questions/6818335/how-to-parse-this-table-and-extract-data-from-it) to match this question's demand.
Maybe have a look at phpQuery: <http://code.google.com/p/phpquery/>? I haven't used it myself so I'm not 100% sure it does what you want, but since it is a server-side implementation of jQuery to select from the DOM, using CSS selectors, I think it could be useful in your case.
8,816,194
> > **Possible Duplicate:** > > [How to parse and process HTML with PHP?](https://stackoverflow.com/questions/3577641/how-to-parse-and-process-html-with-php) > > > I need to fetch the second column of the given HTML table using PHP. How can I do it? **References:** Table to be parsed: <http://bit.ly/Ak2xay> HTML code of this table: <http://bit.ly/ACdLMn>
2012/01/11
[ "https://Stackoverflow.com/questions/8816194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162266/" ]
Using phpQuery <http://code.google.com/p/phpquery/> you could do ``` $file = LINK OR NAME OF YOUR FILE phpQuery::newDocumentFile($file); $data = pq('UNIQUE COLUMN ID OR CLASS AS YOU WOULD FOR CSS ex: .class #id')->html(); echo $data. ```
Maybe have a look at phpQuery: <http://code.google.com/p/phpquery/>? I haven't used it myself so I'm not 100% sure it does what you want, but since it is a server-side implementation of jQuery to select from the DOM, using CSS selectors, I think it could be useful in your case.
8,816,194
> > **Possible Duplicate:** > > [How to parse and process HTML with PHP?](https://stackoverflow.com/questions/3577641/how-to-parse-and-process-html-with-php) > > > I need to fetch the second column of the given HTML table using PHP. How can I do it? **References:** Table to be parsed: <http://bit.ly/Ak2xay> HTML code of this table: <http://bit.ly/ACdLMn>
2012/01/11
[ "https://Stackoverflow.com/questions/8816194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162266/" ]
For tidy HTML codes, one of the parsing approach can be DOM. DOM divides your HTML code into objects and then allows you to call the desired object and its values/tag name etc. The official documentation of PHP HTML DOM parsing is available at <http://php.net/manual/en/book.dom.php> For finding the values of second column for the given table following DOM implementation can be done: ``` <?php $data = file_get_contents('http://mytemporalbucket.s3.amazonaws.com/code.txt'); $dom = new domDocument; @$dom->loadHTML($data); $dom->preserveWhiteSpace = false; $tables = $dom->getElementsByTagName('table'); $rows = $tables->item(1)->getElementsByTagName('tr'); foreach ($rows as $row) { $cols = $row->getElementsByTagName('td'); echo $cols[2]; } ?> ``` **Reference:** Customized the code provided at [How to parse this table and extract data from it?](https://stackoverflow.com/questions/6818335/how-to-parse-this-table-and-extract-data-from-it) to match this question's demand.
Using phpQuery <http://code.google.com/p/phpquery/> you could do ``` $file = LINK OR NAME OF YOUR FILE phpQuery::newDocumentFile($file); $data = pq('UNIQUE COLUMN ID OR CLASS AS YOU WOULD FOR CSS ex: .class #id')->html(); echo $data. ```
17,490,275
I am developing a library which is used for some specific validation operations. Every thing is ok for me in usage, *but when I publish it, every time developers need to read manual document.* So, I want to show usage tips like shown blow. ![enter image description here](https://i.stack.imgur.com/JEHq7.png) How can i do it ?
2013/07/05
[ "https://Stackoverflow.com/questions/17490275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1172945/" ]
You need to write JavaDoc comments in your code and then you can generate JavaDoc html. JavaDoc comments are special comments which are between `/**` and `*/` and can be used to generate JavaDoc. e.g. ``` /** * Class description. * <p> * Some more details * * @author Edd */ public class MyClass { /** * Method description. * * @param param * important parameter */ public static void myMethod(String param) { } } ``` This would then look like this as a tooltip: ![JavaDoc tooltip](https://i.stack.imgur.com/bSpdF.png) When you release your library for other developers to use, you would typically release it as a jar file. When you package up your jar you should also generate a javadoc.jar file to accompany your jar. This can then be used by other developers to get the usage tips.
Write JavaDoc comments and publish them together with your library. If you are using Maven, you can use the [`javadoc:jar` goal](https://maven.apache.org/plugins/maven-javadoc-plugin/jar-mojo.html) of the [Maven Javadoc Plugin](https://maven.apache.org/plugins/maven-javadoc-plugin/).
17,490,275
I am developing a library which is used for some specific validation operations. Every thing is ok for me in usage, *but when I publish it, every time developers need to read manual document.* So, I want to show usage tips like shown blow. ![enter image description here](https://i.stack.imgur.com/JEHq7.png) How can i do it ?
2013/07/05
[ "https://Stackoverflow.com/questions/17490275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1172945/" ]
You need to write JavaDoc comments in your code and then you can generate JavaDoc html. JavaDoc comments are special comments which are between `/**` and `*/` and can be used to generate JavaDoc. e.g. ``` /** * Class description. * <p> * Some more details * * @author Edd */ public class MyClass { /** * Method description. * * @param param * important parameter */ public static void myMethod(String param) { } } ``` This would then look like this as a tooltip: ![JavaDoc tooltip](https://i.stack.imgur.com/bSpdF.png) When you release your library for other developers to use, you would typically release it as a jar file. When you package up your jar you should also generate a javadoc.jar file to accompany your jar. This can then be used by other developers to get the usage tips.
Read about and use javadoc, here: <http://www.oracle.com/technetwork/java/javase/documentation/index-jsp-135444.html>
672,223
Under what circumstances is a reboot of an Ubuntu system necessary? I often read in answers that after changes in the system the system is to be restarted, but is that absolutely necessary?
2015/09/09
[ "https://askubuntu.com/questions/672223", "https://askubuntu.com", "https://askubuntu.com/users/367165/" ]
I can't think of any situations of where a reboot is ***absolutely necessary***. Really, you can leave Ubuntu running indefinitely. It might get malware (because kernel and libc updates aren't applied) and it might panic or crash out... But what are avoiding those actually going to do for you? Given the complexities of life, it might be more necessary to ignore the constant demands of computers, and sustain yourself in other ways. Like breathing, eating, loving... living. But even then, are *they* absolutely necessary? Is your existence on this plane within the absolute definition of necessity? I honestly don't know. Bit of a weird question to ask. --- To the two big-fat-joke-spoilers who downvoted this post and those that follow, This question was incomplete, or at least open-ended. When you throw around words like **necessary**, you need to give a context. Many answers already *assumed* the OP meant **highly desirable** (in a technical sense), so posted answers that fit contexts like **necessary to avoid being hacked** or **necessary if your computer crashes**. They're good answers. Adding another wasn't really warranted. But they say assumptions are the mother of all muck ups (or something like that anyway) so I peeled it back to **absolute necessity**. If you insist on using an old copy of 10.10, Time and Space will carry rolling on, as are their wonts. You'll note I'm not *recommending* that position.
First of all, I appreciate this question because it will always be current. The other answers are correct and very detailed - that is why I go short. There are scenarios where a reboot is necessary, like after installing a new kernel. There are scenarios where it is recommended, like after the install of a new desktop. In most scenarios, like after installing or upgrading software rebooting is not necessary. Whenever you are in doubt I recommend to perform a restart, so you are on the safe side.
672,223
Under what circumstances is a reboot of an Ubuntu system necessary? I often read in answers that after changes in the system the system is to be restarted, but is that absolutely necessary?
2015/09/09
[ "https://askubuntu.com/questions/672223", "https://askubuntu.com", "https://askubuntu.com/users/367165/" ]
> > When is it necessary to reboot an Ubuntu system? > > > A running machine and strictly when doing an update/upgrade? Probably never (but do read on). The Linux system is set up in such a way that after you updated the system where it would require a reboot to activate the new features (ie. read the kernel got changed; changes to apache, mysql only require a restart of the service) you can always keep working with the current state the system is on. Now if you want these new features active the easiest method of doing so is rebooting. But for all we care you keep working on this machine and reboot it the next weekend or the weekend after that. Or next christmas. Is it smart? Maybe not. But there is nobody stopping you from doing so. The system is smart enough to not accept the next update if the server has not rebooted yet. To me the only reasons where a reboot is necessary is after first install or when doing maintenance where single user is required (think things like partitioning, fixing hard disk errors) or when some idiot ran the famous fork bomb (though that one could be fixed from the system itself). For all other reboots to occur is at the grace of the administrator. And I can not call that "necessary".
Install the package `debian-goodies`: ``` sudo apt-get install debian-goodies ``` and run the command ``` sudo checkrestart ``` You will see a list of services and now you have the choice: * Restart each service or * Reboot your system --- ``` $ checkrestart Found 20 processes using old versions of upgraded files (15 distinct programs) (14 distinct packages) Of these, 12 seem to contain init scripts which can be used to restart them: The following packages seem to have init scripts that could be used to restart them: gpm: 3044 /usr/sbin/gpm rpcbind: 2208 /sbin/rpcbind bind9: 8463 /usr/sbin/named openssh-server: 22124 /usr/sbin/sshd ntp: 4078 /usr/sbin/ntpd tftpd-hpa: 3417 /usr/sbin/in.tftpd uptimed: 2704 /usr/sbin/uptimed cron: 3019 /usr/sbin/cron postfix: 22145 /usr/lib/postfix/qmgr 8892 /usr/lib/postfix/master hddtemp: 3174 /usr/sbin/hddtemp autofs: 2792 /usr/sbin/automount openbsd-inetd: 3254 /usr/sbin/inetd These are the init scripts: service gpm restart service rpcbind restart service bind9 restart service ssh restart service ntp restart service tftpd-hpa restart service uptimed restart service cron restart service postfix restart service hddtemp restart service autofs restart service openbsd-inetd restart These processes do not seem to have an associated init script to restart them: isc-dhcp-client: 3775 /sbin/dhclient ```
672,223
Under what circumstances is a reboot of an Ubuntu system necessary? I often read in answers that after changes in the system the system is to be restarted, but is that absolutely necessary?
2015/09/09
[ "https://askubuntu.com/questions/672223", "https://askubuntu.com", "https://askubuntu.com/users/367165/" ]
I can't think of any situations of where a reboot is ***absolutely necessary***. Really, you can leave Ubuntu running indefinitely. It might get malware (because kernel and libc updates aren't applied) and it might panic or crash out... But what are avoiding those actually going to do for you? Given the complexities of life, it might be more necessary to ignore the constant demands of computers, and sustain yourself in other ways. Like breathing, eating, loving... living. But even then, are *they* absolutely necessary? Is your existence on this plane within the absolute definition of necessity? I honestly don't know. Bit of a weird question to ask. --- To the two big-fat-joke-spoilers who downvoted this post and those that follow, This question was incomplete, or at least open-ended. When you throw around words like **necessary**, you need to give a context. Many answers already *assumed* the OP meant **highly desirable** (in a technical sense), so posted answers that fit contexts like **necessary to avoid being hacked** or **necessary if your computer crashes**. They're good answers. Adding another wasn't really warranted. But they say assumptions are the mother of all muck ups (or something like that anyway) so I peeled it back to **absolute necessity**. If you insist on using an old copy of 10.10, Time and Space will carry rolling on, as are their wonts. You'll note I'm not *recommending* that position.
Install the package `debian-goodies`: ``` sudo apt-get install debian-goodies ``` and run the command ``` sudo checkrestart ``` You will see a list of services and now you have the choice: * Restart each service or * Reboot your system --- ``` $ checkrestart Found 20 processes using old versions of upgraded files (15 distinct programs) (14 distinct packages) Of these, 12 seem to contain init scripts which can be used to restart them: The following packages seem to have init scripts that could be used to restart them: gpm: 3044 /usr/sbin/gpm rpcbind: 2208 /sbin/rpcbind bind9: 8463 /usr/sbin/named openssh-server: 22124 /usr/sbin/sshd ntp: 4078 /usr/sbin/ntpd tftpd-hpa: 3417 /usr/sbin/in.tftpd uptimed: 2704 /usr/sbin/uptimed cron: 3019 /usr/sbin/cron postfix: 22145 /usr/lib/postfix/qmgr 8892 /usr/lib/postfix/master hddtemp: 3174 /usr/sbin/hddtemp autofs: 2792 /usr/sbin/automount openbsd-inetd: 3254 /usr/sbin/inetd These are the init scripts: service gpm restart service rpcbind restart service bind9 restart service ssh restart service ntp restart service tftpd-hpa restart service uptimed restart service cron restart service postfix restart service hddtemp restart service autofs restart service openbsd-inetd restart These processes do not seem to have an associated init script to restart them: isc-dhcp-client: 3775 /sbin/dhclient ```
672,223
Under what circumstances is a reboot of an Ubuntu system necessary? I often read in answers that after changes in the system the system is to be restarted, but is that absolutely necessary?
2015/09/09
[ "https://askubuntu.com/questions/672223", "https://askubuntu.com", "https://askubuntu.com/users/367165/" ]
> > When is it necessary to reboot an Ubuntu system? > > > A running machine and strictly when doing an update/upgrade? Probably never (but do read on). The Linux system is set up in such a way that after you updated the system where it would require a reboot to activate the new features (ie. read the kernel got changed; changes to apache, mysql only require a restart of the service) you can always keep working with the current state the system is on. Now if you want these new features active the easiest method of doing so is rebooting. But for all we care you keep working on this machine and reboot it the next weekend or the weekend after that. Or next christmas. Is it smart? Maybe not. But there is nobody stopping you from doing so. The system is smart enough to not accept the next update if the server has not rebooted yet. To me the only reasons where a reboot is necessary is after first install or when doing maintenance where single user is required (think things like partitioning, fixing hard disk errors) or when some idiot ran the famous fork bomb (though that one could be fixed from the system itself). For all other reboots to occur is at the grace of the administrator. And I can not call that "necessary".
First of all, I appreciate this question because it will always be current. The other answers are correct and very detailed - that is why I go short. There are scenarios where a reboot is necessary, like after installing a new kernel. There are scenarios where it is recommended, like after the install of a new desktop. In most scenarios, like after installing or upgrading software rebooting is not necessary. Whenever you are in doubt I recommend to perform a restart, so you are on the safe side.
672,223
Under what circumstances is a reboot of an Ubuntu system necessary? I often read in answers that after changes in the system the system is to be restarted, but is that absolutely necessary?
2015/09/09
[ "https://askubuntu.com/questions/672223", "https://askubuntu.com", "https://askubuntu.com/users/367165/" ]
* After kernel panic; * After partitioning or filesystem modifications (more specifically, resizing root partition; I'd recommend to avoid resizing the hard drive from which you boot in general, regardless of partition; if you are resizing something external, like SD card or USB, no reboots necessary ); * After kernel upgrade and security patches (although that [might not always be necessary]; * After system became unresponsive for whatever reason, and you've no option but to use [magic SYSRQ keys](https://en.wikipedia.org/wiki/Magic_SysRq_key) or hard reset * After making changes to *some* dconf schemas , depending on the way application may have been developed. [Related answer](https://unix.stackexchange.com/a/114706/85039) * Your CPU is overheating (you don't wanna keep on roasting those cores, do you ?)
I can't think of any situations of where a reboot is ***absolutely necessary***. Really, you can leave Ubuntu running indefinitely. It might get malware (because kernel and libc updates aren't applied) and it might panic or crash out... But what are avoiding those actually going to do for you? Given the complexities of life, it might be more necessary to ignore the constant demands of computers, and sustain yourself in other ways. Like breathing, eating, loving... living. But even then, are *they* absolutely necessary? Is your existence on this plane within the absolute definition of necessity? I honestly don't know. Bit of a weird question to ask. --- To the two big-fat-joke-spoilers who downvoted this post and those that follow, This question was incomplete, or at least open-ended. When you throw around words like **necessary**, you need to give a context. Many answers already *assumed* the OP meant **highly desirable** (in a technical sense), so posted answers that fit contexts like **necessary to avoid being hacked** or **necessary if your computer crashes**. They're good answers. Adding another wasn't really warranted. But they say assumptions are the mother of all muck ups (or something like that anyway) so I peeled it back to **absolute necessity**. If you insist on using an old copy of 10.10, Time and Space will carry rolling on, as are their wonts. You'll note I'm not *recommending* that position.
672,223
Under what circumstances is a reboot of an Ubuntu system necessary? I often read in answers that after changes in the system the system is to be restarted, but is that absolutely necessary?
2015/09/09
[ "https://askubuntu.com/questions/672223", "https://askubuntu.com", "https://askubuntu.com/users/367165/" ]
There are generally two situations where a reboot is usually necessary: 1. The kernel is upgraded. 2. `libc` (rather, `glibc`) is upgraded. There is a mechanism for reloading the kernel without restarting ([How can I upgrade my server's kernel without rebooting?](https://askubuntu.com/q/193069/158442)). With `glibc`, the biggest problem is init. It is possible to restart init (see [Restarting init without restarting the system](https://unix.stackexchange.com/q/181782/70524)). For the average user, neither is recommended, and restarting is **necessary**. Apparently, there exists a third case: 3. `dbus` has been upgraded. `dbus-daemon` is apparently incapable of restarting (from what I can understand of [the discussion on this LWN article](http://lwn.net/Articles/657590/)). And since a lot of things rely on DBus...
First of all, I appreciate this question because it will always be current. The other answers are correct and very detailed - that is why I go short. There are scenarios where a reboot is necessary, like after installing a new kernel. There are scenarios where it is recommended, like after the install of a new desktop. In most scenarios, like after installing or upgrading software rebooting is not necessary. Whenever you are in doubt I recommend to perform a restart, so you are on the safe side.
672,223
Under what circumstances is a reboot of an Ubuntu system necessary? I often read in answers that after changes in the system the system is to be restarted, but is that absolutely necessary?
2015/09/09
[ "https://askubuntu.com/questions/672223", "https://askubuntu.com", "https://askubuntu.com/users/367165/" ]
Actually, **it depends what you're trying to accomplish:** * If you do an `apt-get dist-upgrade` and a new kernel comes in, and you want to activate it, you need a reboot. * If a new version of FireFox comes in, you obviously don't. *And in between those two extremes are 50 shades of grey:* [![enter image description here](https://i.stack.imgur.com/E1V0C.png)](https://i.stack.imgur.com/E1V0C.png) **;-)**
Install the package `debian-goodies`: ``` sudo apt-get install debian-goodies ``` and run the command ``` sudo checkrestart ``` You will see a list of services and now you have the choice: * Restart each service or * Reboot your system --- ``` $ checkrestart Found 20 processes using old versions of upgraded files (15 distinct programs) (14 distinct packages) Of these, 12 seem to contain init scripts which can be used to restart them: The following packages seem to have init scripts that could be used to restart them: gpm: 3044 /usr/sbin/gpm rpcbind: 2208 /sbin/rpcbind bind9: 8463 /usr/sbin/named openssh-server: 22124 /usr/sbin/sshd ntp: 4078 /usr/sbin/ntpd tftpd-hpa: 3417 /usr/sbin/in.tftpd uptimed: 2704 /usr/sbin/uptimed cron: 3019 /usr/sbin/cron postfix: 22145 /usr/lib/postfix/qmgr 8892 /usr/lib/postfix/master hddtemp: 3174 /usr/sbin/hddtemp autofs: 2792 /usr/sbin/automount openbsd-inetd: 3254 /usr/sbin/inetd These are the init scripts: service gpm restart service rpcbind restart service bind9 restart service ssh restart service ntp restart service tftpd-hpa restart service uptimed restart service cron restart service postfix restart service hddtemp restart service autofs restart service openbsd-inetd restart These processes do not seem to have an associated init script to restart them: isc-dhcp-client: 3775 /sbin/dhclient ```
672,223
Under what circumstances is a reboot of an Ubuntu system necessary? I often read in answers that after changes in the system the system is to be restarted, but is that absolutely necessary?
2015/09/09
[ "https://askubuntu.com/questions/672223", "https://askubuntu.com", "https://askubuntu.com/users/367165/" ]
* After kernel panic; * After partitioning or filesystem modifications (more specifically, resizing root partition; I'd recommend to avoid resizing the hard drive from which you boot in general, regardless of partition; if you are resizing something external, like SD card or USB, no reboots necessary ); * After kernel upgrade and security patches (although that [might not always be necessary]; * After system became unresponsive for whatever reason, and you've no option but to use [magic SYSRQ keys](https://en.wikipedia.org/wiki/Magic_SysRq_key) or hard reset * After making changes to *some* dconf schemas , depending on the way application may have been developed. [Related answer](https://unix.stackexchange.com/a/114706/85039) * Your CPU is overheating (you don't wanna keep on roasting those cores, do you ?)
Actually, **it depends what you're trying to accomplish:** * If you do an `apt-get dist-upgrade` and a new kernel comes in, and you want to activate it, you need a reboot. * If a new version of FireFox comes in, you obviously don't. *And in between those two extremes are 50 shades of grey:* [![enter image description here](https://i.stack.imgur.com/E1V0C.png)](https://i.stack.imgur.com/E1V0C.png) **;-)**
672,223
Under what circumstances is a reboot of an Ubuntu system necessary? I often read in answers that after changes in the system the system is to be restarted, but is that absolutely necessary?
2015/09/09
[ "https://askubuntu.com/questions/672223", "https://askubuntu.com", "https://askubuntu.com/users/367165/" ]
I actually had a situation earlier today that proves this. Sometimes, there are residual things left over in the system after a change is made. For example, I had a user that was not able to access `/dev/dsp` despite having been added to the appropriate groups. There was a lock placed on it by the first user that accessed it. However, even after killing that user, the lock was still in place and the second user could not access it. However, after a reboot, both users were able to simultaneously use `/dev/dsp` without any conflict. Doing a reboot releases any residual things that could prevent changes from properly taking effect.
Install the package `debian-goodies`: ``` sudo apt-get install debian-goodies ``` and run the command ``` sudo checkrestart ``` You will see a list of services and now you have the choice: * Restart each service or * Reboot your system --- ``` $ checkrestart Found 20 processes using old versions of upgraded files (15 distinct programs) (14 distinct packages) Of these, 12 seem to contain init scripts which can be used to restart them: The following packages seem to have init scripts that could be used to restart them: gpm: 3044 /usr/sbin/gpm rpcbind: 2208 /sbin/rpcbind bind9: 8463 /usr/sbin/named openssh-server: 22124 /usr/sbin/sshd ntp: 4078 /usr/sbin/ntpd tftpd-hpa: 3417 /usr/sbin/in.tftpd uptimed: 2704 /usr/sbin/uptimed cron: 3019 /usr/sbin/cron postfix: 22145 /usr/lib/postfix/qmgr 8892 /usr/lib/postfix/master hddtemp: 3174 /usr/sbin/hddtemp autofs: 2792 /usr/sbin/automount openbsd-inetd: 3254 /usr/sbin/inetd These are the init scripts: service gpm restart service rpcbind restart service bind9 restart service ssh restart service ntp restart service tftpd-hpa restart service uptimed restart service cron restart service postfix restart service hddtemp restart service autofs restart service openbsd-inetd restart These processes do not seem to have an associated init script to restart them: isc-dhcp-client: 3775 /sbin/dhclient ```
672,223
Under what circumstances is a reboot of an Ubuntu system necessary? I often read in answers that after changes in the system the system is to be restarted, but is that absolutely necessary?
2015/09/09
[ "https://askubuntu.com/questions/672223", "https://askubuntu.com", "https://askubuntu.com/users/367165/" ]
Actually, **it depends what you're trying to accomplish:** * If you do an `apt-get dist-upgrade` and a new kernel comes in, and you want to activate it, you need a reboot. * If a new version of FireFox comes in, you obviously don't. *And in between those two extremes are 50 shades of grey:* [![enter image description here](https://i.stack.imgur.com/E1V0C.png)](https://i.stack.imgur.com/E1V0C.png) **;-)**
I can't think of any situations of where a reboot is ***absolutely necessary***. Really, you can leave Ubuntu running indefinitely. It might get malware (because kernel and libc updates aren't applied) and it might panic or crash out... But what are avoiding those actually going to do for you? Given the complexities of life, it might be more necessary to ignore the constant demands of computers, and sustain yourself in other ways. Like breathing, eating, loving... living. But even then, are *they* absolutely necessary? Is your existence on this plane within the absolute definition of necessity? I honestly don't know. Bit of a weird question to ask. --- To the two big-fat-joke-spoilers who downvoted this post and those that follow, This question was incomplete, or at least open-ended. When you throw around words like **necessary**, you need to give a context. Many answers already *assumed* the OP meant **highly desirable** (in a technical sense), so posted answers that fit contexts like **necessary to avoid being hacked** or **necessary if your computer crashes**. They're good answers. Adding another wasn't really warranted. But they say assumptions are the mother of all muck ups (or something like that anyway) so I peeled it back to **absolute necessity**. If you insist on using an old copy of 10.10, Time and Space will carry rolling on, as are their wonts. You'll note I'm not *recommending* that position.
34,393,323
I am using `Telerik Gridview` for displaying list of records and i have more than **10 pages** on which i am using this gridview with this following common events code copy pasted(with some minor changes) on all this pages: ``` protected void Page_Load(object sender, EventArgs e) { DisplayRecords() } public void DisplayRecords() { //Grid view names are different on different pages. GridView1.DataSource=Fetching records from database. GridView1.DataBind(); } protected void GridView1_SortCommand(object sender, GridSortCommandEventArgs e) { DisplayRecords() } protected void GridView1_PageIndexChanged(object sender, GridPageChangedEventArgs e) { var index = e.NewPageIndex; DisplayRecords() } protected void GridView1_PageSizeChanged(object sender, GridPageSizeChangedEventArgs e) { var size = e.NewPageSize; DisplayRecords() } ``` This is my one page which inherits from following page: ``` public partial class LoadSettings : ParentPage { //Load events and other events } [Serializable] public class ParentPage: RadAjaxPage { } Page 1:**ttt.aspx** public void DisplayRecords() { //Grid view names are different on different pages. GridView1.DataSource=this.GetAlltttData() GridView1.DataBind(); } public DataTable GetAlltttData() { using (var context = new MyDataContext()) { var data = from c in context.ttt select c; return MyDataContext.LINQToDataTable(data); } } Page 2:**bbb.aspx** public void DisplayRecords() { //Grid view names are different on different pages. GridView1.DataSource=this.GetAllbbbData() GridView1.DataBind(); } public DataTable GetAllbbbData() { using (var context = new MyDataContext()) { var data = from c in context.bbb select c; return MyDataContext.LINQToDataTable(data); } } protected void rgbbb_SortCommand(object sender, GridSortCommandEventArgs e) { DisplayRecords() } protected void rgbbb_PageIndexChanged(object sender, GridPageChangedEventArgs e) { var index = e.NewPageIndex; DisplayRecords() } protected void rgbbb_PageSizeChanged(object sender, GridPageSizeChangedEventArgs e) { var size = e.NewPageSize; DisplayRecords() } ``` So is this possible that i can place all this events in this **ParentPage** page and just call from every child page instead of polluting my every page with this events?? **Note**:In some of my pages this **DisplayRecords** methods can contains some parameters but rest all events are just common.
2015/12/21
[ "https://Stackoverflow.com/questions/34393323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4927379/" ]
May be you can put you common logic inside abstract class with method (or property) that returns reference on concrete `GridView` and inherit from this class. Then on each page your just have to implement that method. Something like this: ``` public abstract class ParentPage { public virtual void DisplayRecords() { var gridView = this.GetGridView(); gridView.DataSource = this.GetAllData(); gridView.DataBind(); } protected abstract DataTable GetAllData(); protected string GetSortOrder() { if (this.sortOrder != GridSortOrder.Assending) return string.Format("{0} DESC", this.sortExpression) return this.sortExpression; } protected void Page_Load(object sender, EventArgs e) { DisplayRecords(); } protected void GridView1_SortCommand(object sender, GridSortCommandEventArgs e) { if (!e.Item.OwnerTableView.SortExpressions.ContainsExpression(e.SortExpression)) { GridSortExpression sortExpr = new GridSortExpression(); sortExpr.FieldName = e.SortExpression; sortExpr.SortOrder = GridSortOrder.Ascending; e.Item.OwnerTableView.SortExpressions.AddSortExpression(sortExpr); } } protected void GridView1_PageIndexChanged(object sender, GridPageChangedEventArgs e) { e.Item.OwnerTableView.PageIndex = e.NewPageIndex; DisplayRecords(); } protected void GridView1_PageSizeChanged(object sender, GridPageSizeChangedEventArgs e) { e.Item.OwnerTableView.PageSize = e.NewPageSize; DisplayRecords(); } } Page 1:**ttt.aspx** public class **tttPage : BasePage { protected override GridView GetGridView() { //return GridView of this page return GridView1; } protected override DataTable GetAllData() { using (var context = new MyDataContext()) { var data = c in context.ttt select c; return MyDataContext.LINQToDataTable(data); } } } Page 1:**bbb.aspx** public class **bbbPage : BasePage { protected override GridView GetGridView() { //return GridView of this page return GridView1; } protected override DataTable GetAllData() { using (var context = new MyDataContext()) { var data = c in context.bbb select c; return MyDataContext.LINQToDataTable(data); } } } ``` Or you can put you common logic inside base class with virtual methods where use event args for getting `GridView` like `e.Item.OwnerTableView`. By making it virtual you will be able to override this logic in any page class Something like this: ``` public abstract class ParentPage<TEntity> { public virtual void DisplayRecords(GridView gridView) { gridView.DataSource = this.GetAllData(); gridView.DataBind(); } protected abstract DataTable GetAllData(); protected void Page_Load(object sender, EventArgs e) { DisplayRecords(e.Item.OwnerTableView); } protected void GridView_SortCommand(object sender, GridSortCommandEventArgs e) { DisplayRecords(e.Item.OwnerTableView); } protected void GridView_PageIndexChanged(object sender, GridPageChangedEventArgs e) { DisplayRecords(e.Item.OwnerTableView); } protected void GridView_PageSizeChanged(object sender, GridPageSizeChangedEventArgs e) { DisplayRecords(e.Item.OwnerTableView); } } public class **tttPage : ParentPage { protected override DataTable GetAllData() { using (var context = new MyDataContext()) { var data = c in context.ttt select c; return MyDataContext.LINQToDataTable(data); } } } public class **bbbPage : ParentPage { protected override DataTable GetAllData() { using (var context = new MyDataContext()) { var data = c in context.bbb select c; return MyDataContext.LINQToDataTable(data); } } } ``` Also you can use generic parameter for getting values from db.
There are many principles that you generally apply when trying to refactor code. Currently you are trying to refactor your code as to not violate the [DRY](http://en.wikipedia.org/wiki/Don't_repeat_yourself) principle (DRY = don't repeat yourself). But, some other principals might come in to play that you might want to consider. The [single responsibility principle](http://en.wikipedia.org/wiki/Single_responsibility_principle) would suggest that each method does only one unambiguous thing.
39,927,024
I am attempting to connect to MongoDB hosted on an AWS instance with a key file. I am able to ssh into the instance and connect to the database with no issues. When I try to connect to the database from a remote location with pymongo I receive this error: `ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol` Port 27017 is open and the source is set to 0.0.0.0/0. ``` from pymongo import MongoClient client = MongoClient('mongodb://ec2-123-45-678-910.compute-1.amazonaws.com', 27017, ssl=True, ssl_keyfile='/path_to/mykey.pem') db = client.test coll = db.foo coll.insert_many(records) ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol (_ssl.c:645) ``` [This](https://stackoverflow.com/questions/27277061/using-pymongo-to-connect-to-mongodb-on-aws-instance-from-windows) question is nearly identical to mine, however the error is different and the solution posted there does not apply to my issue. The address and key here have been changed, I have been going in circles on this for hours with no luck, any help would be appreciated.
2016/10/07
[ "https://Stackoverflow.com/questions/39927024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3639023/" ]
This issue can cause because of following issue: 1. version of pymongo (suggest to use 3.3.0, which worked for me) 2. It can be a DNS issue, etc, in fact you could check for a DNS issue using: telnet xx.xx.xx.xx port 3. can be a firewall issue 4. Can be an issue with ssl key. Try the following to test: ``` import os import pymongo import ssl URL="url:port/db?ssl=true" client = pymongo.MongoClient(URL, ssl_cert_reqs=ssl.CERT_NONE) db = client.get_default_database() print db print db.collection_names() ```
I had the same problem (SSL handshake) with Pymongo module to connect to DocumentDB Azure (Data Base). The error : `ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol (_ssl.c:590)` I was using pymongo==3.4.0 **To resolve this :** **Change the version of pymongo by installing the 3.3.0 version** `pip install pymongo==3.3.0` **Try:** `import pymongo pymongo.__version__`
39,927,024
I am attempting to connect to MongoDB hosted on an AWS instance with a key file. I am able to ssh into the instance and connect to the database with no issues. When I try to connect to the database from a remote location with pymongo I receive this error: `ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol` Port 27017 is open and the source is set to 0.0.0.0/0. ``` from pymongo import MongoClient client = MongoClient('mongodb://ec2-123-45-678-910.compute-1.amazonaws.com', 27017, ssl=True, ssl_keyfile='/path_to/mykey.pem') db = client.test coll = db.foo coll.insert_many(records) ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol (_ssl.c:645) ``` [This](https://stackoverflow.com/questions/27277061/using-pymongo-to-connect-to-mongodb-on-aws-instance-from-windows) question is nearly identical to mine, however the error is different and the solution posted there does not apply to my issue. The address and key here have been changed, I have been going in circles on this for hours with no luck, any help would be appreciated.
2016/10/07
[ "https://Stackoverflow.com/questions/39927024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3639023/" ]
I had the same problem (SSL handshake) with Pymongo module to connect to DocumentDB Azure (Data Base). The error : `ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol (_ssl.c:590)` I was using pymongo==3.4.0 **To resolve this :** **Change the version of pymongo by installing the 3.3.0 version** `pip install pymongo==3.3.0` **Try:** `import pymongo pymongo.__version__`
For me, the problem was that my Python setup only supported TLS 1.0 – not TLS 1.1 or above. You can check it like this: **Python 3** ``` > from urllib.request import urlopen > urlopen('https://www.howsmyssl.com/a/check').read() ``` **Python 2** ``` > from urllib2 import urlopen > urlopen('https://www.howsmyssl.com/a/check').read() ``` Check the output for the key `tls_version`. If it says `TLS 1.0` and not `TLS 1.1` or `TLS 1.2` that could be the problem. If you're using a virtualenv, be sure to run the command inside. Solution: Install Python with a newer version of OpenSSL -------------------------------------------------------- In order support TLS 1.1 or above, you may need to install a newer version of OpenSSL, and install Python again afterwards. This should give you a Python that supports TLS 1.1. The process depends on your operating system – here's a guide for [OS X](https://comeroutewithme.com/2016/03/13/python-osx-openssl-issue/). **virtualenv users** For me, the Python outside of my virtualenv had TLS 1.2 support, so just I removed my old virtualenv, and created a new one with the same packages and then it worked. Easy peasy! **See also:** * [The warning about TLS 1.0](http://api.mongodb.com/python/current/examples/tls.html#python-3-x)) in the Python 3 section in the PyMongo documenation. Although it's under the Python 3 section it also applies to Python 2
39,927,024
I am attempting to connect to MongoDB hosted on an AWS instance with a key file. I am able to ssh into the instance and connect to the database with no issues. When I try to connect to the database from a remote location with pymongo I receive this error: `ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol` Port 27017 is open and the source is set to 0.0.0.0/0. ``` from pymongo import MongoClient client = MongoClient('mongodb://ec2-123-45-678-910.compute-1.amazonaws.com', 27017, ssl=True, ssl_keyfile='/path_to/mykey.pem') db = client.test coll = db.foo coll.insert_many(records) ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol (_ssl.c:645) ``` [This](https://stackoverflow.com/questions/27277061/using-pymongo-to-connect-to-mongodb-on-aws-instance-from-windows) question is nearly identical to mine, however the error is different and the solution posted there does not apply to my issue. The address and key here have been changed, I have been going in circles on this for hours with no luck, any help would be appreciated.
2016/10/07
[ "https://Stackoverflow.com/questions/39927024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3639023/" ]
I had the same problem (SSL handshake) with Pymongo module to connect to DocumentDB Azure (Data Base). The error : `ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol (_ssl.c:590)` I was using pymongo==3.4.0 **To resolve this :** **Change the version of pymongo by installing the 3.3.0 version** `pip install pymongo==3.3.0` **Try:** `import pymongo pymongo.__version__`
I had the same issue and talked for 30 minutes with the Mongo Atlas support which deployed over AWS. I run the next terminal command: ``` /Applications/Python\ 3.6/Install\ Certificates.command ```
39,927,024
I am attempting to connect to MongoDB hosted on an AWS instance with a key file. I am able to ssh into the instance and connect to the database with no issues. When I try to connect to the database from a remote location with pymongo I receive this error: `ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol` Port 27017 is open and the source is set to 0.0.0.0/0. ``` from pymongo import MongoClient client = MongoClient('mongodb://ec2-123-45-678-910.compute-1.amazonaws.com', 27017, ssl=True, ssl_keyfile='/path_to/mykey.pem') db = client.test coll = db.foo coll.insert_many(records) ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol (_ssl.c:645) ``` [This](https://stackoverflow.com/questions/27277061/using-pymongo-to-connect-to-mongodb-on-aws-instance-from-windows) question is nearly identical to mine, however the error is different and the solution posted there does not apply to my issue. The address and key here have been changed, I have been going in circles on this for hours with no luck, any help would be appreciated.
2016/10/07
[ "https://Stackoverflow.com/questions/39927024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3639023/" ]
I had the same problem (SSL handshake) with Pymongo module to connect to DocumentDB Azure (Data Base). The error : `ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol (_ssl.c:590)` I was using pymongo==3.4.0 **To resolve this :** **Change the version of pymongo by installing the 3.3.0 version** `pip install pymongo==3.3.0` **Try:** `import pymongo pymongo.__version__`
I had the same issue. Please check if you are connected via VPN. when I disconnected it resolved my problem.
39,927,024
I am attempting to connect to MongoDB hosted on an AWS instance with a key file. I am able to ssh into the instance and connect to the database with no issues. When I try to connect to the database from a remote location with pymongo I receive this error: `ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol` Port 27017 is open and the source is set to 0.0.0.0/0. ``` from pymongo import MongoClient client = MongoClient('mongodb://ec2-123-45-678-910.compute-1.amazonaws.com', 27017, ssl=True, ssl_keyfile='/path_to/mykey.pem') db = client.test coll = db.foo coll.insert_many(records) ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol (_ssl.c:645) ``` [This](https://stackoverflow.com/questions/27277061/using-pymongo-to-connect-to-mongodb-on-aws-instance-from-windows) question is nearly identical to mine, however the error is different and the solution posted there does not apply to my issue. The address and key here have been changed, I have been going in circles on this for hours with no luck, any help would be appreciated.
2016/10/07
[ "https://Stackoverflow.com/questions/39927024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3639023/" ]
This issue can cause because of following issue: 1. version of pymongo (suggest to use 3.3.0, which worked for me) 2. It can be a DNS issue, etc, in fact you could check for a DNS issue using: telnet xx.xx.xx.xx port 3. can be a firewall issue 4. Can be an issue with ssl key. Try the following to test: ``` import os import pymongo import ssl URL="url:port/db?ssl=true" client = pymongo.MongoClient(URL, ssl_cert_reqs=ssl.CERT_NONE) db = client.get_default_database() print db print db.collection_names() ```
For me, the problem was that my Python setup only supported TLS 1.0 – not TLS 1.1 or above. You can check it like this: **Python 3** ``` > from urllib.request import urlopen > urlopen('https://www.howsmyssl.com/a/check').read() ``` **Python 2** ``` > from urllib2 import urlopen > urlopen('https://www.howsmyssl.com/a/check').read() ``` Check the output for the key `tls_version`. If it says `TLS 1.0` and not `TLS 1.1` or `TLS 1.2` that could be the problem. If you're using a virtualenv, be sure to run the command inside. Solution: Install Python with a newer version of OpenSSL -------------------------------------------------------- In order support TLS 1.1 or above, you may need to install a newer version of OpenSSL, and install Python again afterwards. This should give you a Python that supports TLS 1.1. The process depends on your operating system – here's a guide for [OS X](https://comeroutewithme.com/2016/03/13/python-osx-openssl-issue/). **virtualenv users** For me, the Python outside of my virtualenv had TLS 1.2 support, so just I removed my old virtualenv, and created a new one with the same packages and then it worked. Easy peasy! **See also:** * [The warning about TLS 1.0](http://api.mongodb.com/python/current/examples/tls.html#python-3-x)) in the Python 3 section in the PyMongo documenation. Although it's under the Python 3 section it also applies to Python 2
39,927,024
I am attempting to connect to MongoDB hosted on an AWS instance with a key file. I am able to ssh into the instance and connect to the database with no issues. When I try to connect to the database from a remote location with pymongo I receive this error: `ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol` Port 27017 is open and the source is set to 0.0.0.0/0. ``` from pymongo import MongoClient client = MongoClient('mongodb://ec2-123-45-678-910.compute-1.amazonaws.com', 27017, ssl=True, ssl_keyfile='/path_to/mykey.pem') db = client.test coll = db.foo coll.insert_many(records) ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol (_ssl.c:645) ``` [This](https://stackoverflow.com/questions/27277061/using-pymongo-to-connect-to-mongodb-on-aws-instance-from-windows) question is nearly identical to mine, however the error is different and the solution posted there does not apply to my issue. The address and key here have been changed, I have been going in circles on this for hours with no luck, any help would be appreciated.
2016/10/07
[ "https://Stackoverflow.com/questions/39927024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3639023/" ]
This issue can cause because of following issue: 1. version of pymongo (suggest to use 3.3.0, which worked for me) 2. It can be a DNS issue, etc, in fact you could check for a DNS issue using: telnet xx.xx.xx.xx port 3. can be a firewall issue 4. Can be an issue with ssl key. Try the following to test: ``` import os import pymongo import ssl URL="url:port/db?ssl=true" client = pymongo.MongoClient(URL, ssl_cert_reqs=ssl.CERT_NONE) db = client.get_default_database() print db print db.collection_names() ```
I had the same issue and talked for 30 minutes with the Mongo Atlas support which deployed over AWS. I run the next terminal command: ``` /Applications/Python\ 3.6/Install\ Certificates.command ```
39,927,024
I am attempting to connect to MongoDB hosted on an AWS instance with a key file. I am able to ssh into the instance and connect to the database with no issues. When I try to connect to the database from a remote location with pymongo I receive this error: `ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol` Port 27017 is open and the source is set to 0.0.0.0/0. ``` from pymongo import MongoClient client = MongoClient('mongodb://ec2-123-45-678-910.compute-1.amazonaws.com', 27017, ssl=True, ssl_keyfile='/path_to/mykey.pem') db = client.test coll = db.foo coll.insert_many(records) ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol (_ssl.c:645) ``` [This](https://stackoverflow.com/questions/27277061/using-pymongo-to-connect-to-mongodb-on-aws-instance-from-windows) question is nearly identical to mine, however the error is different and the solution posted there does not apply to my issue. The address and key here have been changed, I have been going in circles on this for hours with no luck, any help would be appreciated.
2016/10/07
[ "https://Stackoverflow.com/questions/39927024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3639023/" ]
This issue can cause because of following issue: 1. version of pymongo (suggest to use 3.3.0, which worked for me) 2. It can be a DNS issue, etc, in fact you could check for a DNS issue using: telnet xx.xx.xx.xx port 3. can be a firewall issue 4. Can be an issue with ssl key. Try the following to test: ``` import os import pymongo import ssl URL="url:port/db?ssl=true" client = pymongo.MongoClient(URL, ssl_cert_reqs=ssl.CERT_NONE) db = client.get_default_database() print db print db.collection_names() ```
I had the same issue. Please check if you are connected via VPN. when I disconnected it resolved my problem.
37,192
I have this class for use in sorting strings such that if strings have a number in the same position it will order the numbers in increasing order. Alphabetical gives: * file1 * file10 * file2 What I'm calling "number aware" string sorting should give: * file1 * file2 * file10 [Here](https://stackoverflow.com/questions/8270784/how-to-split-a-string-between-letters-and-digits-or-between-digits-and-letters) is what I have using a regex split from there. The code seems to work. Any cases where I could run into problem? If not any suggestions on making it simpler or more efficient. ``` import java.util.Comparator; public class NumberAwareStringComparator implements Comparator<String>{ public int compare(String s1, String s2) { String[] s1Parts = s1.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); String[] s2Parts = s2.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); int i = 0; while(i < s1Parts.length && i < s2Parts.length){ //if parts are the same if(s1Parts[i].compareTo(s2Parts[i]) == 0){ ++i; }else{ try{ int intS1 = Integer.parseInt(s1Parts[i]); int intS2 = Integer.parseInt(s2Parts[i]); //if the parse works int diff = intS1 - intS2; if(diff == 0){ ++i; }else{ return diff; } }catch(Exception ex){ return s1.compareTo(s2); } }//end else }//end while //Handle if one string is a prefix of the other. // nothing comes before something. if(s1.length() < s2.length()){ return -1; }else if(s1.length() > s2.length()){ return 1; }else{ return 0; } } } ```
2013/12/12
[ "https://codereview.stackexchange.com/questions/37192", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/33373/" ]
In general, I think this solutions is doing the right thing, and the algorithm, in a broad sense is doing it the right way. There are two specific areas where I think it can be improved: 1. Regular Expressions can be compiled and reused. This compareTo method is splitting many, many strings, and it would make a big difference to reuse the patterns rather than to recompile them twice each time the method is called. So, compile the pattern and use a static reference to it: ``` private static final Pattern BOUNDARYSPLIT = Pattern.compile("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); ``` Then, in your method you can reuse that pattern easily with: ``` String[] s1Parts = BOUNDARYSPLIT.split(s1); String[] s2Parts = BOUNDARYSPLIT.split(s2); ``` This will save a lot of performance. 2. The second issue is the 'convenience' of using a try/catch block for the ParseInt. Creating, throwing, and catching an exception is a surprisingly slow and complicated process. Using a try/catch as part of a 'routine' code-path is a mistake. Especially in something as frequent as a compareTo method. You should first make an attempt to see whether the input has a small hope of converting before throwing an exception: ``` if (s1parts[i].charAt(0) >= '0' && s1parts[i].charAt(0) <= '9') { // put your try-catch block here.... } else { return s1parts[i].compareTo(s2parts[i]); } ``` 3. I noticed, while writing this up, that in your catch-block, you use: ``` return s1.compareTo(s2); ``` I don't think it makes a difference in the functionality, but, you should probably use: ``` return s1parts[i].compareTo(s2parts[i]); ```
Your approach appears to be basically sound. My main concern is `catch(Exception ex)`. **Catching all exceptions** like that makes me very nervous and puzzled about your intent. I have to wonder, what could possibly go wrong inside the try-block? My thought process: 1. The exception would have to be thrown from the `Integer.parseInt()` calls, since the diff portion is foolproof. 2. Obviously, `Integer.parseInt()` could throw `NumberFormatException`. 3. What about `ArrayIndexOutOfBoundsException`? No, we're safe, because you already checked in the while-loop condition. Furthermore, if `++i` got executed, it wouldn't enter the else-clause. 4. What about `NullPointerException`? It seems impossible, since the parts arrays came from `String.split()`. 5. Anything else? `OutOfMemoryError`, maybe? No, that's a `Throwable` but not an `Exception`. 6. Any other possibilities? No. Am I sure? No. For my sanity, please change that to `catch (NumberFormatException ex)`! Changing the **while-loop into a for-loop** would make it easier to recognize the flow control. You can also save a level of indentation. ``` for (int i = 0; i < s1Parts.length && i < s2Parts.length; ++i) { //if parts are the same if (s1Parts[i].compareTo(s2Parts[i]) == 0) { continue; } try { int intS1 = Integer.parseInt(s1Parts[i]); int intS2 = Integer.parseInt(s2Parts[i]); //if the parse works int diff = intS1 - intS2; if (diff == 0) { // continue; // Actually, this is a no-op } else { return diff; } } catch (NumberFormatException ex) { // Buggy, as noted by @rolfl // return s1.compareTo(s2); return s1Parts[i].compareTo(s2Parts[i]); } } ``` The **epilogue could be simplified** to just `return s1.length() - s2.length()`.
37,192
I have this class for use in sorting strings such that if strings have a number in the same position it will order the numbers in increasing order. Alphabetical gives: * file1 * file10 * file2 What I'm calling "number aware" string sorting should give: * file1 * file2 * file10 [Here](https://stackoverflow.com/questions/8270784/how-to-split-a-string-between-letters-and-digits-or-between-digits-and-letters) is what I have using a regex split from there. The code seems to work. Any cases where I could run into problem? If not any suggestions on making it simpler or more efficient. ``` import java.util.Comparator; public class NumberAwareStringComparator implements Comparator<String>{ public int compare(String s1, String s2) { String[] s1Parts = s1.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); String[] s2Parts = s2.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); int i = 0; while(i < s1Parts.length && i < s2Parts.length){ //if parts are the same if(s1Parts[i].compareTo(s2Parts[i]) == 0){ ++i; }else{ try{ int intS1 = Integer.parseInt(s1Parts[i]); int intS2 = Integer.parseInt(s2Parts[i]); //if the parse works int diff = intS1 - intS2; if(diff == 0){ ++i; }else{ return diff; } }catch(Exception ex){ return s1.compareTo(s2); } }//end else }//end while //Handle if one string is a prefix of the other. // nothing comes before something. if(s1.length() < s2.length()){ return -1; }else if(s1.length() > s2.length()){ return 1; }else{ return 0; } } } ```
2013/12/12
[ "https://codereview.stackexchange.com/questions/37192", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/33373/" ]
Exceptions should be reserved for exceptional situations, and should be avoided if possible. The fundamental reason you have to deal with `NumberFormatException` is that after splitting, you don't know whether each part contains a number or a non-number. Here's a strategy that always compares non-digits to non-digits, and numbers to numbers. ``` import java.math.BigInteger; import java.util.Comparator; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NumberAwareStringComparator implements Comparator<CharSequence> { public static final NumberAwareStringComparator INSTANCE = new NumberAwareStringComparator(); private static final Pattern PATTERN = Pattern.compile("(\\D*)(\\d*)"); private NumberAwareStringComparator() { } public int compare(CharSequence s1, CharSequence s2) { Matcher m1 = PATTERN.matcher(s1); Matcher m2 = PATTERN.matcher(s2); // The only way find() could fail is at the end of a string while (m1.find() && m2.find()) { // matcher.group(1) fetches any non-digits captured by the // first parentheses in PATTERN. int nonDigitCompare = m1.group(1).compareTo(m2.group(1)); if (0 != nonDigitCompare) { return nonDigitCompare; } // matcher.group(2) fetches any digits captured by the // second parentheses in PATTERN. if (m1.group(2).isEmpty()) { return m2.group(2).isEmpty() ? 0 : -1; } else if (m2.group(2).isEmpty()) { return +1; } BigInteger n1 = new BigInteger(m1.group(2)); BigInteger n2 = new BigInteger(m2.group(2)); int numberCompare = n1.compareTo(n2); if (0 != numberCompare) { return numberCompare; } } // Handle if one string is a prefix of the other. // Nothing comes before something. return m1.hitEnd() && m2.hitEnd() ? 0 : m1.hitEnd() ? -1 : +1; } } ``` Since strings of digits (such as those representing dates, like `20131212123456.log`) can overflow an `int`, I've used `java.math.BigInteger`. Also, since the code works just as well with `CharSequence` as with `String`, I've generalized the type to `Comparator<CharSequence>`.
In general, I think this solutions is doing the right thing, and the algorithm, in a broad sense is doing it the right way. There are two specific areas where I think it can be improved: 1. Regular Expressions can be compiled and reused. This compareTo method is splitting many, many strings, and it would make a big difference to reuse the patterns rather than to recompile them twice each time the method is called. So, compile the pattern and use a static reference to it: ``` private static final Pattern BOUNDARYSPLIT = Pattern.compile("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); ``` Then, in your method you can reuse that pattern easily with: ``` String[] s1Parts = BOUNDARYSPLIT.split(s1); String[] s2Parts = BOUNDARYSPLIT.split(s2); ``` This will save a lot of performance. 2. The second issue is the 'convenience' of using a try/catch block for the ParseInt. Creating, throwing, and catching an exception is a surprisingly slow and complicated process. Using a try/catch as part of a 'routine' code-path is a mistake. Especially in something as frequent as a compareTo method. You should first make an attempt to see whether the input has a small hope of converting before throwing an exception: ``` if (s1parts[i].charAt(0) >= '0' && s1parts[i].charAt(0) <= '9') { // put your try-catch block here.... } else { return s1parts[i].compareTo(s2parts[i]); } ``` 3. I noticed, while writing this up, that in your catch-block, you use: ``` return s1.compareTo(s2); ``` I don't think it makes a difference in the functionality, but, you should probably use: ``` return s1parts[i].compareTo(s2parts[i]); ```
37,192
I have this class for use in sorting strings such that if strings have a number in the same position it will order the numbers in increasing order. Alphabetical gives: * file1 * file10 * file2 What I'm calling "number aware" string sorting should give: * file1 * file2 * file10 [Here](https://stackoverflow.com/questions/8270784/how-to-split-a-string-between-letters-and-digits-or-between-digits-and-letters) is what I have using a regex split from there. The code seems to work. Any cases where I could run into problem? If not any suggestions on making it simpler or more efficient. ``` import java.util.Comparator; public class NumberAwareStringComparator implements Comparator<String>{ public int compare(String s1, String s2) { String[] s1Parts = s1.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); String[] s2Parts = s2.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); int i = 0; while(i < s1Parts.length && i < s2Parts.length){ //if parts are the same if(s1Parts[i].compareTo(s2Parts[i]) == 0){ ++i; }else{ try{ int intS1 = Integer.parseInt(s1Parts[i]); int intS2 = Integer.parseInt(s2Parts[i]); //if the parse works int diff = intS1 - intS2; if(diff == 0){ ++i; }else{ return diff; } }catch(Exception ex){ return s1.compareTo(s2); } }//end else }//end while //Handle if one string is a prefix of the other. // nothing comes before something. if(s1.length() < s2.length()){ return -1; }else if(s1.length() > s2.length()){ return 1; }else{ return 0; } } } ```
2013/12/12
[ "https://codereview.stackexchange.com/questions/37192", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/33373/" ]
In general, I think this solutions is doing the right thing, and the algorithm, in a broad sense is doing it the right way. There are two specific areas where I think it can be improved: 1. Regular Expressions can be compiled and reused. This compareTo method is splitting many, many strings, and it would make a big difference to reuse the patterns rather than to recompile them twice each time the method is called. So, compile the pattern and use a static reference to it: ``` private static final Pattern BOUNDARYSPLIT = Pattern.compile("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); ``` Then, in your method you can reuse that pattern easily with: ``` String[] s1Parts = BOUNDARYSPLIT.split(s1); String[] s2Parts = BOUNDARYSPLIT.split(s2); ``` This will save a lot of performance. 2. The second issue is the 'convenience' of using a try/catch block for the ParseInt. Creating, throwing, and catching an exception is a surprisingly slow and complicated process. Using a try/catch as part of a 'routine' code-path is a mistake. Especially in something as frequent as a compareTo method. You should first make an attempt to see whether the input has a small hope of converting before throwing an exception: ``` if (s1parts[i].charAt(0) >= '0' && s1parts[i].charAt(0) <= '9') { // put your try-catch block here.... } else { return s1parts[i].compareTo(s2parts[i]); } ``` 3. I noticed, while writing this up, that in your catch-block, you use: ``` return s1.compareTo(s2); ``` I don't think it makes a difference in the functionality, but, you should probably use: ``` return s1parts[i].compareTo(s2parts[i]); ```
Changes the pattern to this if you want to use decimals: ``` private static Pattern BOUNDARYSPLIT = Pattern.compile("(?<=\\D\\.)(?=\\d)|(?<=\\d)(?=\\D)"); ```
37,192
I have this class for use in sorting strings such that if strings have a number in the same position it will order the numbers in increasing order. Alphabetical gives: * file1 * file10 * file2 What I'm calling "number aware" string sorting should give: * file1 * file2 * file10 [Here](https://stackoverflow.com/questions/8270784/how-to-split-a-string-between-letters-and-digits-or-between-digits-and-letters) is what I have using a regex split from there. The code seems to work. Any cases where I could run into problem? If not any suggestions on making it simpler or more efficient. ``` import java.util.Comparator; public class NumberAwareStringComparator implements Comparator<String>{ public int compare(String s1, String s2) { String[] s1Parts = s1.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); String[] s2Parts = s2.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); int i = 0; while(i < s1Parts.length && i < s2Parts.length){ //if parts are the same if(s1Parts[i].compareTo(s2Parts[i]) == 0){ ++i; }else{ try{ int intS1 = Integer.parseInt(s1Parts[i]); int intS2 = Integer.parseInt(s2Parts[i]); //if the parse works int diff = intS1 - intS2; if(diff == 0){ ++i; }else{ return diff; } }catch(Exception ex){ return s1.compareTo(s2); } }//end else }//end while //Handle if one string is a prefix of the other. // nothing comes before something. if(s1.length() < s2.length()){ return -1; }else if(s1.length() > s2.length()){ return 1; }else{ return 0; } } } ```
2013/12/12
[ "https://codereview.stackexchange.com/questions/37192", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/33373/" ]
Exceptions should be reserved for exceptional situations, and should be avoided if possible. The fundamental reason you have to deal with `NumberFormatException` is that after splitting, you don't know whether each part contains a number or a non-number. Here's a strategy that always compares non-digits to non-digits, and numbers to numbers. ``` import java.math.BigInteger; import java.util.Comparator; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NumberAwareStringComparator implements Comparator<CharSequence> { public static final NumberAwareStringComparator INSTANCE = new NumberAwareStringComparator(); private static final Pattern PATTERN = Pattern.compile("(\\D*)(\\d*)"); private NumberAwareStringComparator() { } public int compare(CharSequence s1, CharSequence s2) { Matcher m1 = PATTERN.matcher(s1); Matcher m2 = PATTERN.matcher(s2); // The only way find() could fail is at the end of a string while (m1.find() && m2.find()) { // matcher.group(1) fetches any non-digits captured by the // first parentheses in PATTERN. int nonDigitCompare = m1.group(1).compareTo(m2.group(1)); if (0 != nonDigitCompare) { return nonDigitCompare; } // matcher.group(2) fetches any digits captured by the // second parentheses in PATTERN. if (m1.group(2).isEmpty()) { return m2.group(2).isEmpty() ? 0 : -1; } else if (m2.group(2).isEmpty()) { return +1; } BigInteger n1 = new BigInteger(m1.group(2)); BigInteger n2 = new BigInteger(m2.group(2)); int numberCompare = n1.compareTo(n2); if (0 != numberCompare) { return numberCompare; } } // Handle if one string is a prefix of the other. // Nothing comes before something. return m1.hitEnd() && m2.hitEnd() ? 0 : m1.hitEnd() ? -1 : +1; } } ``` Since strings of digits (such as those representing dates, like `20131212123456.log`) can overflow an `int`, I've used `java.math.BigInteger`. Also, since the code works just as well with `CharSequence` as with `String`, I've generalized the type to `Comparator<CharSequence>`.
Your approach appears to be basically sound. My main concern is `catch(Exception ex)`. **Catching all exceptions** like that makes me very nervous and puzzled about your intent. I have to wonder, what could possibly go wrong inside the try-block? My thought process: 1. The exception would have to be thrown from the `Integer.parseInt()` calls, since the diff portion is foolproof. 2. Obviously, `Integer.parseInt()` could throw `NumberFormatException`. 3. What about `ArrayIndexOutOfBoundsException`? No, we're safe, because you already checked in the while-loop condition. Furthermore, if `++i` got executed, it wouldn't enter the else-clause. 4. What about `NullPointerException`? It seems impossible, since the parts arrays came from `String.split()`. 5. Anything else? `OutOfMemoryError`, maybe? No, that's a `Throwable` but not an `Exception`. 6. Any other possibilities? No. Am I sure? No. For my sanity, please change that to `catch (NumberFormatException ex)`! Changing the **while-loop into a for-loop** would make it easier to recognize the flow control. You can also save a level of indentation. ``` for (int i = 0; i < s1Parts.length && i < s2Parts.length; ++i) { //if parts are the same if (s1Parts[i].compareTo(s2Parts[i]) == 0) { continue; } try { int intS1 = Integer.parseInt(s1Parts[i]); int intS2 = Integer.parseInt(s2Parts[i]); //if the parse works int diff = intS1 - intS2; if (diff == 0) { // continue; // Actually, this is a no-op } else { return diff; } } catch (NumberFormatException ex) { // Buggy, as noted by @rolfl // return s1.compareTo(s2); return s1Parts[i].compareTo(s2Parts[i]); } } ``` The **epilogue could be simplified** to just `return s1.length() - s2.length()`.
37,192
I have this class for use in sorting strings such that if strings have a number in the same position it will order the numbers in increasing order. Alphabetical gives: * file1 * file10 * file2 What I'm calling "number aware" string sorting should give: * file1 * file2 * file10 [Here](https://stackoverflow.com/questions/8270784/how-to-split-a-string-between-letters-and-digits-or-between-digits-and-letters) is what I have using a regex split from there. The code seems to work. Any cases where I could run into problem? If not any suggestions on making it simpler or more efficient. ``` import java.util.Comparator; public class NumberAwareStringComparator implements Comparator<String>{ public int compare(String s1, String s2) { String[] s1Parts = s1.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); String[] s2Parts = s2.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); int i = 0; while(i < s1Parts.length && i < s2Parts.length){ //if parts are the same if(s1Parts[i].compareTo(s2Parts[i]) == 0){ ++i; }else{ try{ int intS1 = Integer.parseInt(s1Parts[i]); int intS2 = Integer.parseInt(s2Parts[i]); //if the parse works int diff = intS1 - intS2; if(diff == 0){ ++i; }else{ return diff; } }catch(Exception ex){ return s1.compareTo(s2); } }//end else }//end while //Handle if one string is a prefix of the other. // nothing comes before something. if(s1.length() < s2.length()){ return -1; }else if(s1.length() > s2.length()){ return 1; }else{ return 0; } } } ```
2013/12/12
[ "https://codereview.stackexchange.com/questions/37192", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/33373/" ]
Your approach appears to be basically sound. My main concern is `catch(Exception ex)`. **Catching all exceptions** like that makes me very nervous and puzzled about your intent. I have to wonder, what could possibly go wrong inside the try-block? My thought process: 1. The exception would have to be thrown from the `Integer.parseInt()` calls, since the diff portion is foolproof. 2. Obviously, `Integer.parseInt()` could throw `NumberFormatException`. 3. What about `ArrayIndexOutOfBoundsException`? No, we're safe, because you already checked in the while-loop condition. Furthermore, if `++i` got executed, it wouldn't enter the else-clause. 4. What about `NullPointerException`? It seems impossible, since the parts arrays came from `String.split()`. 5. Anything else? `OutOfMemoryError`, maybe? No, that's a `Throwable` but not an `Exception`. 6. Any other possibilities? No. Am I sure? No. For my sanity, please change that to `catch (NumberFormatException ex)`! Changing the **while-loop into a for-loop** would make it easier to recognize the flow control. You can also save a level of indentation. ``` for (int i = 0; i < s1Parts.length && i < s2Parts.length; ++i) { //if parts are the same if (s1Parts[i].compareTo(s2Parts[i]) == 0) { continue; } try { int intS1 = Integer.parseInt(s1Parts[i]); int intS2 = Integer.parseInt(s2Parts[i]); //if the parse works int diff = intS1 - intS2; if (diff == 0) { // continue; // Actually, this is a no-op } else { return diff; } } catch (NumberFormatException ex) { // Buggy, as noted by @rolfl // return s1.compareTo(s2); return s1Parts[i].compareTo(s2Parts[i]); } } ``` The **epilogue could be simplified** to just `return s1.length() - s2.length()`.
Changes the pattern to this if you want to use decimals: ``` private static Pattern BOUNDARYSPLIT = Pattern.compile("(?<=\\D\\.)(?=\\d)|(?<=\\d)(?=\\D)"); ```
37,192
I have this class for use in sorting strings such that if strings have a number in the same position it will order the numbers in increasing order. Alphabetical gives: * file1 * file10 * file2 What I'm calling "number aware" string sorting should give: * file1 * file2 * file10 [Here](https://stackoverflow.com/questions/8270784/how-to-split-a-string-between-letters-and-digits-or-between-digits-and-letters) is what I have using a regex split from there. The code seems to work. Any cases where I could run into problem? If not any suggestions on making it simpler or more efficient. ``` import java.util.Comparator; public class NumberAwareStringComparator implements Comparator<String>{ public int compare(String s1, String s2) { String[] s1Parts = s1.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); String[] s2Parts = s2.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); int i = 0; while(i < s1Parts.length && i < s2Parts.length){ //if parts are the same if(s1Parts[i].compareTo(s2Parts[i]) == 0){ ++i; }else{ try{ int intS1 = Integer.parseInt(s1Parts[i]); int intS2 = Integer.parseInt(s2Parts[i]); //if the parse works int diff = intS1 - intS2; if(diff == 0){ ++i; }else{ return diff; } }catch(Exception ex){ return s1.compareTo(s2); } }//end else }//end while //Handle if one string is a prefix of the other. // nothing comes before something. if(s1.length() < s2.length()){ return -1; }else if(s1.length() > s2.length()){ return 1; }else{ return 0; } } } ```
2013/12/12
[ "https://codereview.stackexchange.com/questions/37192", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/33373/" ]
Exceptions should be reserved for exceptional situations, and should be avoided if possible. The fundamental reason you have to deal with `NumberFormatException` is that after splitting, you don't know whether each part contains a number or a non-number. Here's a strategy that always compares non-digits to non-digits, and numbers to numbers. ``` import java.math.BigInteger; import java.util.Comparator; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NumberAwareStringComparator implements Comparator<CharSequence> { public static final NumberAwareStringComparator INSTANCE = new NumberAwareStringComparator(); private static final Pattern PATTERN = Pattern.compile("(\\D*)(\\d*)"); private NumberAwareStringComparator() { } public int compare(CharSequence s1, CharSequence s2) { Matcher m1 = PATTERN.matcher(s1); Matcher m2 = PATTERN.matcher(s2); // The only way find() could fail is at the end of a string while (m1.find() && m2.find()) { // matcher.group(1) fetches any non-digits captured by the // first parentheses in PATTERN. int nonDigitCompare = m1.group(1).compareTo(m2.group(1)); if (0 != nonDigitCompare) { return nonDigitCompare; } // matcher.group(2) fetches any digits captured by the // second parentheses in PATTERN. if (m1.group(2).isEmpty()) { return m2.group(2).isEmpty() ? 0 : -1; } else if (m2.group(2).isEmpty()) { return +1; } BigInteger n1 = new BigInteger(m1.group(2)); BigInteger n2 = new BigInteger(m2.group(2)); int numberCompare = n1.compareTo(n2); if (0 != numberCompare) { return numberCompare; } } // Handle if one string is a prefix of the other. // Nothing comes before something. return m1.hitEnd() && m2.hitEnd() ? 0 : m1.hitEnd() ? -1 : +1; } } ``` Since strings of digits (such as those representing dates, like `20131212123456.log`) can overflow an `int`, I've used `java.math.BigInteger`. Also, since the code works just as well with `CharSequence` as with `String`, I've generalized the type to `Comparator<CharSequence>`.
Changes the pattern to this if you want to use decimals: ``` private static Pattern BOUNDARYSPLIT = Pattern.compile("(?<=\\D\\.)(?=\\d)|(?<=\\d)(?=\\D)"); ```
51,818
Hannity said on [Foxnews](https://www.foxnews.com/media/hannity-fauci-emails-wuhan-lab-leak-covid-china): > > The Wuhan facility was experimenting with gain of function with > coronaviruses > > > NewsMedical defines the term "[gain of function research](https://www.news-medical.net/health/What-is-Gain-of-Function-Research.aspx)" as: > > Gain-of-function research refers to the serial passaging of > microorganisms to increase their transmissibility, virulence, > immunogenicity, and host tropism by applying selective pressure to a > culture. > > > Setting aside the question of who knew what at which point in time, is there evidence that the Wuhan Institute of Virology engaged in coronavirus research that "alters the virus in a way that increased its transmissibility, virulence, immunogenicity, and host tropism by applying selective pressure"?
2021/06/04
[ "https://skeptics.stackexchange.com/questions/51818", "https://skeptics.stackexchange.com", "https://skeptics.stackexchange.com/users/196/" ]
With the specific question and definitions provided, and a fairly broad definition of "engaged in"? Yes. We even have a published paper. <https://www.nature.com/articles/nm.3985> A paper published in 9 November 2015. The abstract includes: > > Using the SARS-CoV reverse genetics system2, we generated and > characterized a chimeric virus expressing the spike of bat coronavirus > SHC014 in a mouse-adapted SARS-CoV backbone. The results indicate that > group 2b viruses encoding the SHC014 spike in a wild-type backbone can > efficiently use multiple orthologs of the SARS receptor human > angiotensin converting enzyme II (ACE2), replicate efficiently in > primary human airway cells and achieve in vitro titers equivalent to > epidemic strains of SARS-CoV. Additionally, in vivo experiments > demonstrate replication of the chimeric virus in mouse lung with > notable pathogenesis. Evaluation of available SARS-based > immune-therapeutic and prophylactic modalities revealed poor efficacy; > both monoclonal antibody and vaccine approaches failed to neutralize > and protect from infection with CoVs using the novel spike protein. On > the basis of these findings, we synthetically re-derived an infectious > full-length SHC014 recombinant virus and demonstrate robust viral > replication both in vitro and in vivo. Our work suggests a potential > risk of SARS-CoV re-emergence from viruses currently circulating in > bat populations. > > > One of the authors is Shi Zhengli, who the Wuhan Institute of Virology page lists as "Principal Investigator, Research Group of Emerging Viruses". Another is Ge Xing-Ye, who (like Shi Zhengli) is noted in the paper itself as working for "Key Laboratory of Special Pathogens and Biosafety, Wuhan Institute of Virology". So, based on this alone, we can be pretty certain that at least two of the researchers at the Wuhan Institute of Virology were involved in at least one paper that included gain-of-function research on one or more coronaviruses. It seems reasonably likely that there was more, given the habits of researchers in general, but I can't guarantee that, and I'm not going to be the one to hunt it down. Ironically, the point of the paper was to warn people of the possibility of a coronavirus-like outbreak. Edit: As a point of clarification, the above is an accurate answer to the rather broad question asked. In particular, the above paper is on gain-of-function research with respect to *mice*. We do not currently have any evidence indicating that the Wuhan Institute of Virology was performing gain-of-function research with respect to *humans*, and we do have some fairly strong evidence suggesting that medical researchers in general draw a significant distinction between gain-of-function research with respect to those two species. I have made certain adjustments to my answer accordingly, as it has been noted (fairly) that the original formation was unnecessarily easy to interpret as meaning more than it did.
Actually, the main/corresponding author (Ralph Baric) of the paper cited in Barden's answer as evidence for "yes" argued in press statements [quoted in the Washington Post](https://www.washingtonpost.com/politics/2021/05/18/fact-checking-senator-paul-dr-fauci-flap-over-wuhan-lab-funding/) that the answer is "no". > > In a lengthy statement to The Fact Checker, Baric — who signed the letter calling for a new investigation — also pushed back against Paul’s assertions at the [Senate] hearing. > > > “The Baric laboratory has never investigated strategies to create super viruses,” he said. **“Studies focused on understanding the cross-species transmission potential of bat coronaviruses like SHC014 have been reviewed by the NIH and by the UNC Institutional Biosafety Committee for potential of gain-of-function research and were deemed not to be gain of function.”** > > > “We never introduced mutations into the SHC014 [horseshoe bat coronavirus] spike to enhance growth in human cells, though the work demonstrated that bat SARS-like viruses were intrinsically poised to emerge in the future,” he added. “**These recombinant clones and viruses were never sent to China.** Importantly, independent studies carried out by Italian scientists and others from around the world have confirmed that none of the bat SARS-like viruses studied at UNC were related to SARS-CoV-2, the cause of the COVID-19 pandemic.” > > > [...] > > > Update, May 19: The National Institutes of Health issued a statement to The Fact Checker which in part said: “NIH has never approved any grant to support 'gain-of-function’ research on coronaviruses that would have increased their transmissibility or lethality for humans. The research proposed in the EcoHealth Alliance, Inc. grant application sought to understand how bat coronaviruses evolve naturally in the environment to become transmissible to the human population.” When gain-of-function research was paused, “this grant was reviewed again and determined by experts to fall outside the scope of the funding pause.” > > > The argument is basically around what constitutes "gain of function". The [Rand] Paul side disagrees: > > “Despite Dr. Fauci’s denials, there is ample evidence that the NIH and the NIAID, under his direction, funded gain of function research at the Wuhan Institute of Virology,” said Paul spokeswoman Kelsey Cooper. > > > Besides the disagreement on the definition of GoF, it seems the actual research on those those engineered/chimera viruses was carried out at UNC (Baric's [lab](https://www.propublica.org/article/near-misses-at-unc-chapel-hills-high-security-lab-illustrate-risk-of-accidents-with-coronaviruses)) in the US. It's a bit less clear what the contribution of the VIW co-authors (Shi) was to that paper. I'll update this answer if I find more clear info on this. (As the original/unmodified SHC014 was [collected in China](https://scholar.harvard.edu/files/kleelerner/files/20151112_nature_-_engineered_bat_virus_stirs_debate_over_risky_research_nature_news_comment.pdf) I suspect that's reason why Shi is a co-author to that paper.) As the accepted answer draws its own conclusions, I'll draw mine: just based on that co-authoring of that paper, this claim is even more silly than claiming that iPhones are *developed* in China because they polish the aluminum for the cases there. In this case, the modified/"GoF" virus never left the US... if the claims of the papers' authors are correct. (iPhones at least are *assembled* in China, but the *modified* SHC014 was "made in USA" for any definition of "made"... in both intellectual and physical senses.) I can equally claim that "Stack Exchange has been engaged in validating Fox News stories" (for some definition[s] of "engaged" and "validating").
619,653
Was looking at some code earlier, and am thinking that there has to be a more elegant way of writing this.... (returnVar.Warnings is a string array, it could be returned as any size depending on the number of warnings that are logged) ``` For Each item In items If o.ImageContent.ImageId = 0 Then ReDim Preserve returnVar.Warnings(returnVar.Warnings.GetUpperBound(0) + 1) returnVar.Warnings(returnVar.Warnings.GetUpperBound(0)) = "Section: " & section.<header>.<title>.ToString & " , Item: " & item.<title>.ToString End If Next ```
2009/03/06
[ "https://Stackoverflow.com/questions/619653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66112/" ]
use the [generic List(of string)](http://msdn.microsoft.com/en-us/library/6sh2ey19(VS.80).aspx) then get an array containing the list data if you need it ``` dim list = new List(of string) list.Add("foo") list.Add("bar") list.ToArray() ```
Can't you use ArrayList which does this for you? <http://msdn.microsoft.com/en-us/library/system.collections.arraylist.aspx>
619,653
Was looking at some code earlier, and am thinking that there has to be a more elegant way of writing this.... (returnVar.Warnings is a string array, it could be returned as any size depending on the number of warnings that are logged) ``` For Each item In items If o.ImageContent.ImageId = 0 Then ReDim Preserve returnVar.Warnings(returnVar.Warnings.GetUpperBound(0) + 1) returnVar.Warnings(returnVar.Warnings.GetUpperBound(0)) = "Section: " & section.<header>.<title>.ToString & " , Item: " & item.<title>.ToString End If Next ```
2009/03/06
[ "https://Stackoverflow.com/questions/619653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66112/" ]
use the [generic List(of string)](http://msdn.microsoft.com/en-us/library/6sh2ey19(VS.80).aspx) then get an array containing the list data if you need it ``` dim list = new List(of string) list.Add("foo") list.Add("bar") list.ToArray() ```
Start by moving the `If` statement out of the loop. If you are using framework 3.5, you can use LINQ to loop the items. ``` If o.ImageContent.ImageId = 0 Then returnVar.Warnings = items.Select(Function(item) "Section: " & section.<header>.<title>.ToString & " , Item: " & item.<title>.ToString).ToArray() Else returnVar.Warnings = New String() {} End If ```
42,565,930
I have a script in Codeigniter which includes a line of code automatically. I have tried to remove it many times but it's not being removed. ``` <script> $(function(){ $.getScript("https://activeitzone.com/check/shop.js"); }); </script> ``` This line of code is automatically included at the end of page and out of the tag.
2017/03/02
[ "https://Stackoverflow.com/questions/42565930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4169790/" ]
A simple change can help to By-Pass CI Licence check. Go to **System > Core > config.php and remove** ``` if ($index == '') { return base64_decode('PHNjcmlwdD4kKGZ1bmN0aW9uKCl7JC5nZXRTY3JpcHQoImh0dHBzOi8vYWN0aXZlaXR6b25lLmNvbS9jaGVjay9zaG9wLmpzIik7fSk7PC9zY3JpcHQ+'); } ```
That's a script automatically added by the [Active Super Shop Multi-Vendor System](http://activeitzone.com/active_supershop/landing/) package to check the license. I found that out by reading [this discussion board](https://codecanyon.net/item/active-super-shop-multivendor-cms/12124432/comments?page=44) (on page 44 of the 1172 comments as the time of this writing). Abbreviated discussion... > > peddareddy PURCHASED 3 months ago > $(function(){$.getScript(“<https://activeitzone.com/check/shop.js>”);});$(function(){$.getScript(“<https://activeitzone.com/check/shop.js>”);}); > > > How to remove this code. And where it was located. It keep checking my > website weather it was activated or not even i have entered the > purchase code > > > : > > ActiveITzone AUTHOR 3 months ago Hello, the code you mentioned does > not hamper the site speed. It is just a license check so that the > product is not used beyond legality :) Therefore, we shall not remove > the script. Thanks! > > >
42,565,930
I have a script in Codeigniter which includes a line of code automatically. I have tried to remove it many times but it's not being removed. ``` <script> $(function(){ $.getScript("https://activeitzone.com/check/shop.js"); }); </script> ``` This line of code is automatically included at the end of page and out of the tag.
2017/03/02
[ "https://Stackoverflow.com/questions/42565930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4169790/" ]
A simple change can help to By-Pass CI Licence check. Go to **System > Core > config.php and remove** ``` if ($index == '') { return base64_decode('PHNjcmlwdD4kKGZ1bmN0aW9uKCl7JC5nZXRTY3JpcHQoImh0dHBzOi8vYWN0aXZlaXR6b25lLmNvbS9jaGVjay9zaG9wLmpzIik7fSk7PC9zY3JpcHQ+'); } ```
Remove the following lines in **System > Core > config.php** ``` if ($index == '') { return base64_decode('PHNjcmlwdD4kKGZ1bmN0aW9uKCl7JC5nZXRTY3JpcHQoImh0dHBzOi8vYWN0aXZlaXR6b25lLmNvbS9jaGVjay9zaG9wLmpzIik7fSk7PC9zY3JpcHQ+'); } ``` And enjoy the active sh
13,654,428
I have an img tag, I want to re-size it regarding the browser window, without distortion. the img takes a (width: 100%), so its height will be greater than browser window. and when the image height be <= browser window, it will stop resizing, else it will re-size. so; it didn't works !! here's my code: ``` <html> <head> <title>testawy</title> </head> <style type="text/css"> body { padding: 0; margin: 0; overflow: hidden; } </style> <body> <img id="str" src="stretch.jpg"> <script src="jquery.min.js"></script> <script type="text/javascript"> $(function() { $("#str").width($(window).width()); }); $(window).resize(function(){ var x = $(window).height(); var y = $("#str").height(); if (y <= x) { $("#str").height('500px'); } else { $("#str").width($(window).width()); } }); </script> </body> </html> ```
2012/11/30
[ "https://Stackoverflow.com/questions/13654428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1136850/" ]
You have two choices: 1. Writing the file to disk. See [this question](https://stackoverflow.com/questions/12225951/how-to-save-html5-canvas-as-an-image-file-in-window-8-metro-app/12230195#12230195) for details 2. Create a multiple use blob from the XHR response. See [MSDN for details](http://msdn.microsoft.com/en-us/library/ie/hh673569%28v=vs.85%29.aspx). The second option stops you from having to write the file to disk if your just sharing it temporarily, but it does some with some memory management to revoke the blob later. With the URL created, you can just assign it to the an `img` tags `src` attribute.
Alternative answer to this old question, if the goal is to share an image without saving it, ``` Windows.Storage.Streams.RandomAccessStreamReference.createFromUri(targetImageSrc); ``` Should achieve the same result, create the stream from the `uri` instead of a `file`. Although, this function might not have been available back then.
73,462,556
We have an instance of ActiveMQ Artemis 2.17.0 with a queue and producer which sometimes fails with following error: `AMQ219006: Channel disconnected` and right after `AMQ219016: Connection failure detected. Unblocking a blocking call that will never get a response`. I have read different resources on this error and cannot figure out what could be causing it. Could this be caused by a high throughput on the queue?
2022/08/23
[ "https://Stackoverflow.com/questions/73462556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9165597/" ]
We may subset the `service_date` with a logical vector `treatment == 1` i.e. `service_date[treatment == 1]` (assuming there is at least one 'treatment' level 1) ``` library(dplyr) library(lubridate) d %>% group_by(ID) %>% filter(sum(treatment) >1) %>% summarise(treatment_years = lubridate::time_length(max(service_date[treatment == 1]) - min(service_date[treatment == 1]), unit = "day"), .groups = 'drop') %>% summarise(avg = mean(treatment_years), sd = sd(treatment_years)) ``` -output ``` # A tibble: 1 × 2 avg sd <dbl> <dbl> 1 532 89.1 ```
An option using `by` and just subtracting the treated dates. ``` by(d, d$ID, \(x) { if (all(x$treatment == 0)) NA_real_ else diff(x$service_date[x$treatment == 1]) |> as.numeric() }) |> unlist() |> {\(x) c(mean=mean(x, na.rm=TRUE), sd=sd(x, na.rm=TRUE))}() # mean sd # 532.00000 89.09545 ```
68,964,158
CS0266 ERROR The num 3 code is working, but the num 4 code isnt... I think the number is too big... How can I fix it? ``` { GameManager.multiplier += 20000000; GameManager.o2 -= 2000000000; PlayerPrefs.SetInt("o2", GameManager.o2); PlayerPrefs.SetInt("multiplier", GameManager.multiplier); } if (num == 4 && GameManager.o2 >= 5000000000) { GameManager.multiplier += 90000000; GameManager.o2 -= 5000000000; PlayerPrefs.SetInt("o2", GameManager.o2); PlayerPrefs.SetInt("multiplier", GameManager.multiplier); } ```
2021/08/28
[ "https://Stackoverflow.com/questions/68964158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16731740/" ]
**You can use a little bit `Javascript` and boom it's makes your navbar so attractive.** ```html <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body { font-family: 'Lato', sans-serif; } .overlay { height: 100%; width: 100%; display: none; position: fixed; z-index: 1; top: 0; left: 0; background-color: rgb(0,0,0); background-color: rgba(0,0,0, 0.9); } .overlay-content { position: relative; top: 25%; width: 100%; text-align: center; margin-top: 30px; } .overlay a { padding: 8px; text-decoration: none; font-size: 36px; color: #818181; display: block; transition: 0.3s; } .overlay a:hover, .overlay a:focus { color: #f1f1f1; } .overlay .closebtn { position: absolute; top: 20px; right: 45px; font-size: 60px; } @media screen and (max-height: 450px) { .overlay a {font-size: 20px} .overlay .closebtn { font-size: 40px; top: 15px; right: 35px; } } </style> </head> <body> <div id="myNav" class="overlay"> <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a> <div class="overlay-content"> <a href="#">About</a> <a href="#">Services</a> <a href="#">Clients</a> <a href="#">Contact</a> </div> </div> <span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; open</span> <script> function openNav() { document.getElementById("myNav").style.display = "block"; } function closeNav() { document.getElementById("myNav").style.display = "none"; } </script> </body> </html> ``` **Explation of `JS` used**: `onclick()` is used here to call the function **openNav** by default set it's `display:none;` and then make `display:block` when someone calling `openNav()` fucntion. Let me know if this will help you..
AFAIK you cannot change `parent` element on `child` hover using pure `CSS` you have to use use `javascript` to achieve it...
68,964,158
CS0266 ERROR The num 3 code is working, but the num 4 code isnt... I think the number is too big... How can I fix it? ``` { GameManager.multiplier += 20000000; GameManager.o2 -= 2000000000; PlayerPrefs.SetInt("o2", GameManager.o2); PlayerPrefs.SetInt("multiplier", GameManager.multiplier); } if (num == 4 && GameManager.o2 >= 5000000000) { GameManager.multiplier += 90000000; GameManager.o2 -= 5000000000; PlayerPrefs.SetInt("o2", GameManager.o2); PlayerPrefs.SetInt("multiplier", GameManager.multiplier); } ```
2021/08/28
[ "https://Stackoverflow.com/questions/68964158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16731740/" ]
**You can use a little bit `Javascript` and boom it's makes your navbar so attractive.** ```html <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body { font-family: 'Lato', sans-serif; } .overlay { height: 100%; width: 100%; display: none; position: fixed; z-index: 1; top: 0; left: 0; background-color: rgb(0,0,0); background-color: rgba(0,0,0, 0.9); } .overlay-content { position: relative; top: 25%; width: 100%; text-align: center; margin-top: 30px; } .overlay a { padding: 8px; text-decoration: none; font-size: 36px; color: #818181; display: block; transition: 0.3s; } .overlay a:hover, .overlay a:focus { color: #f1f1f1; } .overlay .closebtn { position: absolute; top: 20px; right: 45px; font-size: 60px; } @media screen and (max-height: 450px) { .overlay a {font-size: 20px} .overlay .closebtn { font-size: 40px; top: 15px; right: 35px; } } </style> </head> <body> <div id="myNav" class="overlay"> <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a> <div class="overlay-content"> <a href="#">About</a> <a href="#">Services</a> <a href="#">Clients</a> <a href="#">Contact</a> </div> </div> <span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; open</span> <script> function openNav() { document.getElementById("myNav").style.display = "block"; } function closeNav() { document.getElementById("myNav").style.display = "none"; } </script> </body> </html> ``` **Explation of `JS` used**: `onclick()` is used here to call the function **openNav** by default set it's `display:none;` and then make `display:block` when someone calling `openNav()` fucntion. Let me know if this will help you..
You need Javascript for this purpose, unfortunately, as far as I know. I have created an inner overlay div and two JS events to cope with the situation. ```js document.querySelector(".links").addEventListener("mouseenter", function() { let overlay = document.querySelector(".overlay"); overlay.style.display = "block"; let overlayContent = overlay.querySelector(".overlay-content"); overlayContent.style.width = document.body.clientWidth + "px"; overlayContent.style.height = document.body.clientHeight + "px"; }); document.querySelector(".links").addEventListener("mouseleave", function() { let overlay = document.querySelector(".overlay"); overlay.style.display = "none"; }); ``` ```css .header .container .row { display: flex; align-items: center; justify-content: space-between; } .header .container .row img { max-width: 207px; max-height: 207px; } .header .container .row .links { position: relative; z-index: 1; } .header .container .row .links .icon { width: 1.875em; display: flex; flex-wrap: wrap; justify-content: flex-end; cursor: pointer; } .header .container .row .links .icon span { background-color: var(--whiteColor); margin-bottom: 0.3125em; height: 0.125em; background-color: #000; } .header .container .row .links .icon span:first-child { width: 100%; } .header .container .row .links .icon span:nth-child(2) { width: 100%; } .header .container .row .links .icon span:last-child { width: 60%; transition: 0.3s } .header .container .row .links:hover .icon span:last-child { width: 100%; } .header .container .row .links ul { display: none; background-color: #000; position: absolute; min-width: 12.5em; right: 0; top: calc(100% + 15px); z-index: 1; } .header .container .row .links ul::before { content: " "; position: absolute; border-width: 0.625em; border-style: solid; border-color: transparent transparent #000 transparent; right: 0.3125em; top: -1.25em; } .header .container .row ul li { padding: 1em; } .header .container .row ul li a { text-transform: capitalize; color: var(--whiteColor); transition: color .3s ease-in-out; } .header .container .row ul li a:hover { color: var(--grayColor); } .header .container .row .links:hover ul, .header .container .row .links:hover .overlay{ display: block; } .overlay { display: none; position: relative; z-index: -1; } .overlay-content { background-color: rgba(0,0,0,0.7); position: absolute; } .container { max-width: 1140px; margin-left: auto; margin-right: auto; padding-right: 0.8em; padding-left: 0.8em; } ``` ```html <div class="overlay"><div class="overlay-content"></div></div> <header class="header"> <div class="container"> <div class="row"> <img src="https://images01.nicepage.com/51/41/51417a6d3ee82530e9117219a42fd762.png"> <div class="links"> <span class="icon"> <span></span> <span></span> <span></span> </span> <ul> <li><a href="#">home</a></li> <li><a href="#">menu</a></li> <li><a href="#">catering</a></li> <li><a href="#">our menu</a></li> <li><a href="#">our team</a></li> <li><a href="#">contact us</a></li> </ul> </div> </div> </div> </header> ```
68,964,158
CS0266 ERROR The num 3 code is working, but the num 4 code isnt... I think the number is too big... How can I fix it? ``` { GameManager.multiplier += 20000000; GameManager.o2 -= 2000000000; PlayerPrefs.SetInt("o2", GameManager.o2); PlayerPrefs.SetInt("multiplier", GameManager.multiplier); } if (num == 4 && GameManager.o2 >= 5000000000) { GameManager.multiplier += 90000000; GameManager.o2 -= 5000000000; PlayerPrefs.SetInt("o2", GameManager.o2); PlayerPrefs.SetInt("multiplier", GameManager.multiplier); } ```
2021/08/28
[ "https://Stackoverflow.com/questions/68964158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16731740/" ]
**You can use a little bit `Javascript` and boom it's makes your navbar so attractive.** ```html <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body { font-family: 'Lato', sans-serif; } .overlay { height: 100%; width: 100%; display: none; position: fixed; z-index: 1; top: 0; left: 0; background-color: rgb(0,0,0); background-color: rgba(0,0,0, 0.9); } .overlay-content { position: relative; top: 25%; width: 100%; text-align: center; margin-top: 30px; } .overlay a { padding: 8px; text-decoration: none; font-size: 36px; color: #818181; display: block; transition: 0.3s; } .overlay a:hover, .overlay a:focus { color: #f1f1f1; } .overlay .closebtn { position: absolute; top: 20px; right: 45px; font-size: 60px; } @media screen and (max-height: 450px) { .overlay a {font-size: 20px} .overlay .closebtn { font-size: 40px; top: 15px; right: 35px; } } </style> </head> <body> <div id="myNav" class="overlay"> <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a> <div class="overlay-content"> <a href="#">About</a> <a href="#">Services</a> <a href="#">Clients</a> <a href="#">Contact</a> </div> </div> <span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; open</span> <script> function openNav() { document.getElementById("myNav").style.display = "block"; } function closeNav() { document.getElementById("myNav").style.display = "none"; } </script> </body> </html> ``` **Explation of `JS` used**: `onclick()` is used here to call the function **openNav** by default set it's `display:none;` and then make `display:block` when someone calling `openNav()` fucntion. Let me know if this will help you..
You're gonna have to use at least a little bit of javascript for this mate. Do something like this: ```js let icon = document.getElementsByClassName('icon')[0]; let offCanvas = document.getElementsByClassName('offCanvas')[0]; let overlay = document.getElementsByClassName('overlay')[0]; icon.onmouseenter= () => { overlay.style.display = "block"; overlay.style.opacity = "0"; overlay.style.animation = "overlay .5s forwards"; } icon.onmouseleave = () => { overlay.style.animation = "overlayHide .5s forwards"; } ``` ```css .header .container .row { display: flex; align-items: center; justify-content: space-between; } .header .container .row img { max-width: 207px; max-height: 207px; } .header .container .row .links { position: relative; z-index: 1; } .header .container .row .links .icon { width: 1.875em; display: flex; flex-wrap: wrap; justify-content: flex-end; cursor: pointer; } .header .container .row .links .icon span { background-color: var(--whiteColor); margin-bottom: 0.3125em; height: 0.125em; background-color: #000; } .header .container .row .links .icon span:first-child { width: 100%; } .header .container .row .links .icon span:nth-child(2) { width: 100%; } .header .container .row .links .icon span:last-child { width: 60%; transition: 0.3s } .header .container .row .links:hover .icon span:last-child { width: 100%; } .header .container .row .links ul { display: none; background-color: #000; position: absolute; min-width: 12.5em; right: 0; top: calc(100% + 15px); z-index: 1; } .header .container .row .links ul::before { content: " "; position: absolute; border-width: 0.625em; border-style: solid; border-color: transparent transparent #000 transparent; right: 0.3125em; top: -1.25em; } .header .container .row ul li { padding: 1em; } .header .container .row ul li a { text-transform: capitalize; color: var(--whiteColor); transition: color .3s ease-in-out; } .header .container .row ul li a:hover { color: var(--grayColor); } .header .container .row .links:hover ul, .header .container .row .links:hover .overlay{ display: block; } .overlay { display: none; position: fixed; background-color: rgba(0,0,0,0.7); width: 100%; height: 100%; z-index: 10; } .container { max-width: 1140px; margin-left: auto; margin-right: auto; padding-right: 0.8em; padding-left: 0.8em; } .icon { height: 25px; width: 25px; background-color: black; } @keyframes overlay { 0% {opacity: 0;} 100% {opacity: 1;} } @keyframes overlayHide { 0% {opacity: 1;} 100% {opacity: 0;} } ``` ```html <div class="overlay"></div> <header class="header"> <div class="container"> <div class="row"> <img src="https://images01.nicepage.com/51/41/51417a6d3ee82530e9117219a42fd762.png"> <div class="links"> <span class="icon"> <span></span> <span></span> <span></span> </span> <div class="offCanvas"> <ul> <li><a href="#">home</a></li> <li><a href="#">menu</a></li> <li><a href="#">catering</a></li> <li><a href="#">our menu</a></li> <li><a href="#">our team</a></li> <li><a href="#">contact us</a></li> </ul> </div> </div> </div> </div> </header> ```
161,459
I try to remove shipping.phtml from cart page [![shipping.phtml](https://i.stack.imgur.com/6rY3e.png)](https://i.stack.imgur.com/6rY3e.png) I tried to diseable this field from `module-checkout\view\frontend\layout\checkout_cart_index.xml` ``` <block class="Magento\Checkout\Block\Cart\Shipping" name="checkout.cart.shipping" as="shipping" template="cart/shipping.phtml" after="checkout.cart.summary.title"> <referenceBlock name="checkout.cart.shipping" remove="true" /> ``` by adding `<referenceBlock name="checkout.cart.shipping" remove="true" />` , but it dosen't work. Does anyone know if it's another way do disable this phtml?
2017/02/23
[ "https://magento.stackexchange.com/questions/161459", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/47398/" ]
if you have created your block class by extending **\Magento\Framework\View\Element\Template** In Your phtml file use following code : > > $block->getUrl("zipcode/index/index"); > > > To get the url. if you need the url in the block class itself use : > > $this->getUrl("zipcode/index/index"); > > > Comment if you need more help.
Modify your `Tm\Zipcode\Helper\Data` class and make the constructor look like this ``` protected $_storeManager; public function __construct( ... \Magento\Store\Model\StoreManagerInterface $_storeManager, ... ) { ... $this->_storeManager = $_storeManager; ... } ``` Then the `storeManager` variable will be available in your class
64,966,856
I call the function with and without a parameter. I don't know how to unite them into one. Thanks for help. Function1 ``` normalizeTime(time) { var date = new Date(time * 1000); var hours = date.getHours(); var minutes = date.getMinutes(); var ampm = hours >= 12 ? 'pm' : 'am'; hours = hours % 12; hours = hours ? hours : 12; // the hour '0' should be '12' minutes = minutes < 10 ? '0' + minutes : minutes; var strTime = hours + ':' + minutes + ' ' + ampm; return strTime; }, ``` Function2 ``` getAmPmTime() { var date = new Date(); var hours = date.getHours(); var minutes = date.getMinutes(); var ampm = hours >= 12 ? 'pm' : 'am'; hours = hours % 12; hours = hours ? hours : 12; minutes = minutes < 10 ? '0' + minutes : minutes; var strTime = hours + ':' + minutes + ' ' + ampm; return strTime; }, ```
2020/11/23
[ "https://Stackoverflow.com/questions/64966856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11585851/" ]
You could check whether there is a parameter or not within the function. Sample implementation: ``` normalizeTime(time) { var date = time ? new Date(time * 1000) : new Date(); var hours = date.getHours(); var minutes = date.getMinutes(); var ampm = hours >= 12 ? 'pm' : 'am'; hours = hours % 12; hours = hours ? hours : 12; // the hour '0' should be '12' minutes = minutes < 10 ? '0' + minutes : minutes; var strTime = hours + ':' + minutes + ' ' + ampm; return strTime; } ```
What about conditionally check if 'time' is available? inside your function: ``` let date = null; if (time) { date = new Date(time * 1000); } else { date = new Date(); } ``` This way, if the function is called without any arguments, a new date object will be created. If not, it will set the date with the time argument.
64,966,856
I call the function with and without a parameter. I don't know how to unite them into one. Thanks for help. Function1 ``` normalizeTime(time) { var date = new Date(time * 1000); var hours = date.getHours(); var minutes = date.getMinutes(); var ampm = hours >= 12 ? 'pm' : 'am'; hours = hours % 12; hours = hours ? hours : 12; // the hour '0' should be '12' minutes = minutes < 10 ? '0' + minutes : minutes; var strTime = hours + ':' + minutes + ' ' + ampm; return strTime; }, ``` Function2 ``` getAmPmTime() { var date = new Date(); var hours = date.getHours(); var minutes = date.getMinutes(); var ampm = hours >= 12 ? 'pm' : 'am'; hours = hours % 12; hours = hours ? hours : 12; minutes = minutes < 10 ? '0' + minutes : minutes; var strTime = hours + ':' + minutes + ' ' + ampm; return strTime; }, ```
2020/11/23
[ "https://Stackoverflow.com/questions/64966856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11585851/" ]
What about conditionally check if 'time' is available? inside your function: ``` let date = null; if (time) { date = new Date(time * 1000); } else { date = new Date(); } ``` This way, if the function is called without any arguments, a new date object will be created. If not, it will set the date with the time argument.
Try using default parameter like this: ``` joinedFunction(time = null){ var date = time ? new Date(time * 1000) : new Date(); var hours = date.getHours(); var minutes = date.getMinutes(); var ampm = hours >= 12 ? 'pm' : 'am'; hours = hours % 12; hours = hours ? hours : 12; // the hour '0' should be '12' minutes = minutes < 10 ? '0' + minutes : minutes; var strTime = hours + ':' + minutes + ' ' + ampm; return strTime; } ``` if you do not pass anything(or a falsy parameter), it will be the same as calling your `getAmPmTime` function and if you pass a time, it will be the same as calling your `normalizeTime` function.
64,966,856
I call the function with and without a parameter. I don't know how to unite them into one. Thanks for help. Function1 ``` normalizeTime(time) { var date = new Date(time * 1000); var hours = date.getHours(); var minutes = date.getMinutes(); var ampm = hours >= 12 ? 'pm' : 'am'; hours = hours % 12; hours = hours ? hours : 12; // the hour '0' should be '12' minutes = minutes < 10 ? '0' + minutes : minutes; var strTime = hours + ':' + minutes + ' ' + ampm; return strTime; }, ``` Function2 ``` getAmPmTime() { var date = new Date(); var hours = date.getHours(); var minutes = date.getMinutes(); var ampm = hours >= 12 ? 'pm' : 'am'; hours = hours % 12; hours = hours ? hours : 12; minutes = minutes < 10 ? '0' + minutes : minutes; var strTime = hours + ':' + minutes + ' ' + ampm; return strTime; }, ```
2020/11/23
[ "https://Stackoverflow.com/questions/64966856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11585851/" ]
You could check whether there is a parameter or not within the function. Sample implementation: ``` normalizeTime(time) { var date = time ? new Date(time * 1000) : new Date(); var hours = date.getHours(); var minutes = date.getMinutes(); var ampm = hours >= 12 ? 'pm' : 'am'; hours = hours % 12; hours = hours ? hours : 12; // the hour '0' should be '12' minutes = minutes < 10 ? '0' + minutes : minutes; var strTime = hours + ':' + minutes + ' ' + ampm; return strTime; } ```
Try using default parameter like this: ``` joinedFunction(time = null){ var date = time ? new Date(time * 1000) : new Date(); var hours = date.getHours(); var minutes = date.getMinutes(); var ampm = hours >= 12 ? 'pm' : 'am'; hours = hours % 12; hours = hours ? hours : 12; // the hour '0' should be '12' minutes = minutes < 10 ? '0' + minutes : minutes; var strTime = hours + ':' + minutes + ' ' + ampm; return strTime; } ``` if you do not pass anything(or a falsy parameter), it will be the same as calling your `getAmPmTime` function and if you pass a time, it will be the same as calling your `normalizeTime` function.
9,196,181
I want to generate ajax requests on the fly, but I want to make sure I get a callback after they have all completed, so I want to wrap them within a .when .done statement like the following: ``` $.when(function(){ $.each(oOptions, function(){ var filePath = this.filePath, dataType = this.dataType; $.ajax({ url : filePath, dataType : dataType }); }); }) .done(function(){ console.log('success'); console.log(arguments); }) .fail(function(){ console.log('failed'); }); ``` where my options is an array of objects containing the filepath and datatype for each ajax request I want to make simultaneously. this code will return success, but the arguments is just a function, and the ajax requests never go through. any thoughts on how to do this?
2012/02/08
[ "https://Stackoverflow.com/questions/9196181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/839359/" ]
Just use `strtotime` to turn the string to timestamp and then compare. If the string don't contain year, then the year default is current year. ``` $ts = strtotime("December 12th"); if ($ts >= 1353369600 && $ts <= 1358640000 ) {//....} ```
You can check every year between the timestamps and see if there is the desired day in between them. ``` function inBetween($day, $month, $from, $to) { $from_year = date('Y', $from); $to_year = date('Y', $to); if($from_year == $to_year) { $time = mktime(12,0,0,$month,$day, $from_year); return $time > $from && $time < $to; } elseif($from_year < $to_year) { for($i=$from_year;$i<=$to_year;$i++) { $time = mktime(12,0,0,$month,$day, $i); if($time > $from && $time < $to) return TRUE; } return FALSE; } } var_dump(inBetween(12, 12, 1353369600, 1358640000)); ```
4,842,042
Eclipse support incremental compiling. If I save a source file then it will compile the modified files. Is it possible after such incremental compile also to run the JUnit tests of the same package and show the fail in the error view. Then I can see the JUnit test failing and compiling errors in the same view without extra action. Are there any plugins that can do it?
2011/01/30
[ "https://Stackoverflow.com/questions/4842042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12631/" ]
Use **ExternalToolBuilder**. It can be triggered by source modify. There’s Eclipse customized feature([integrate external tool builder](http://www.eclipse.org/forums/index.php?t=msg&goto=501921&)) which may meet your need. But it needs extra effort to write the scripts I never used. Automatic test cases is not a convenient way, at least single click to see green bar in Eclipse is enough for me:)
You can run all tests in a project using `Alt+Shift+X,T`. I think that making it any more automated than this could take a serious performance toll. Incremental compilation is compiling at most 1 file at a time, but you're talking about running potentially hundreds of tests.
4,842,042
Eclipse support incremental compiling. If I save a source file then it will compile the modified files. Is it possible after such incremental compile also to run the JUnit tests of the same package and show the fail in the error view. Then I can see the JUnit test failing and compiling errors in the same view without extra action. Are there any plugins that can do it?
2011/01/30
[ "https://Stackoverflow.com/questions/4842042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12631/" ]
You have to look at these plugins: * [JUnit Max](http://www.junitmax.com/): Not free, developed by Kent Benk (one of the men behind the TDD practice); * [MoreUnit](http://moreunit.sourceforge.net/): Free, but essentially dedicated to help you write the tests; * [Infinitest](http://infinitest.github.com/): Now free, this plugin is dedicated to run the tests related to the files you have just modified. So regarding your needs, I suggest that you install MoreUnit and Infinitest plugins.
You can run all tests in a project using `Alt+Shift+X,T`. I think that making it any more automated than this could take a serious performance toll. Incremental compilation is compiling at most 1 file at a time, but you're talking about running potentially hundreds of tests.
4,842,042
Eclipse support incremental compiling. If I save a source file then it will compile the modified files. Is it possible after such incremental compile also to run the JUnit tests of the same package and show the fail in the error view. Then I can see the JUnit test failing and compiling errors in the same view without extra action. Are there any plugins that can do it?
2011/01/30
[ "https://Stackoverflow.com/questions/4842042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12631/" ]
You have to look at these plugins: * [JUnit Max](http://www.junitmax.com/): Not free, developed by Kent Benk (one of the men behind the TDD practice); * [MoreUnit](http://moreunit.sourceforge.net/): Free, but essentially dedicated to help you write the tests; * [Infinitest](http://infinitest.github.com/): Now free, this plugin is dedicated to run the tests related to the files you have just modified. So regarding your needs, I suggest that you install MoreUnit and Infinitest plugins.
Use **ExternalToolBuilder**. It can be triggered by source modify. There’s Eclipse customized feature([integrate external tool builder](http://www.eclipse.org/forums/index.php?t=msg&goto=501921&)) which may meet your need. But it needs extra effort to write the scripts I never used. Automatic test cases is not a convenient way, at least single click to see green bar in Eclipse is enough for me:)
1,021,885
I'm going to deploy my application on one of them, and have no idea which is better.
2009/06/20
[ "https://Stackoverflow.com/questions/1021885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104015/" ]
Amazon's Cloud services, at this time, are much more general and flexible, while Google App Engine essentially fits some specific classes of applications that can live within its specific limitations (those limitations are being gradually relaxed, as GAE adds features and allows you to pay to exceed certain quotas, but that does not mean GAE will become a completely general-purpose platform the way Amazon's services are). If your app can live within GAE's limitations, then GAE presents advantages: free up to a certain quota, almost no system configuration / administration overhead, etc. But if you need total flexibility -- for example, if you want to code part of your apps in C or C++, and that's just one of many examples -- then GAE is not suitable, while Amazon (for a price, in both money and sysadm overhead) can accomodate you.
If you've already written your app, and just want to deploy it, I'd have to say AWS is your best bet. AWS is a platform (or rather, EC2 is), and deploying an existing app is easy. App Engine, on the other hand, provides an entire development environment, at a much higher level of abstraction, which has significant advantages when it comes to scaling, but requires you to have written your app to work on it.
1,021,885
I'm going to deploy my application on one of them, and have no idea which is better.
2009/06/20
[ "https://Stackoverflow.com/questions/1021885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104015/" ]
Amazon's Cloud services, at this time, are much more general and flexible, while Google App Engine essentially fits some specific classes of applications that can live within its specific limitations (those limitations are being gradually relaxed, as GAE adds features and allows you to pay to exceed certain quotas, but that does not mean GAE will become a completely general-purpose platform the way Amazon's services are). If your app can live within GAE's limitations, then GAE presents advantages: free up to a certain quota, almost no system configuration / administration overhead, etc. But if you need total flexibility -- for example, if you want to code part of your apps in C or C++, and that's just one of many examples -- then GAE is not suitable, while Amazon (for a price, in both money and sysadm overhead) can accomodate you.
Now how about Free Amazon EC2 for a year to do a better comparision. Check this out. <http://www.buzzingup.com/2010/10/amazon-announces-free-cloud-services-for-new-developers/>
1,021,885
I'm going to deploy my application on one of them, and have no idea which is better.
2009/06/20
[ "https://Stackoverflow.com/questions/1021885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104015/" ]
Amazon's Cloud services, at this time, are much more general and flexible, while Google App Engine essentially fits some specific classes of applications that can live within its specific limitations (those limitations are being gradually relaxed, as GAE adds features and allows you to pay to exceed certain quotas, but that does not mean GAE will become a completely general-purpose platform the way Amazon's services are). If your app can live within GAE's limitations, then GAE presents advantages: free up to a certain quota, almost no system configuration / administration overhead, etc. But if you need total flexibility -- for example, if you want to code part of your apps in C or C++, and that's just one of many examples -- then GAE is not suitable, while Amazon (for a price, in both money and sysadm overhead) can accomodate you.
No one is king in this field because both amazon and google have their own pros and cons. for the finally decision you have to study deep about both or you have to analyze what you required for you apps. no doubt aws is old in this field and they have lot of good quality stuff but remember google is fast growing in cloud computing. personally aws is easy to use and training and support is easily available on the other side google is his early stage and bit complex interface for newbie so you can learn from you requirement
24,762
I'm installing Windows 7 on my Mac via Parallels. During installation I'm getting. "A required CD/DVD drive device driver is missing." message. Doesn't give me any option to proceed further. What am I doing wrong? p.s. I hit same message using bootcamp. I'm using Macbook Pro OS X, Core i7. Trying to install Windows 7 Pro 64bit. ![enter image description here](https://i.stack.imgur.com/grSjK.png)
2011/09/11
[ "https://apple.stackexchange.com/questions/24762", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/910/" ]
This error commonly occurs when the Windows 7 DVD, or the ISO image used to create said DVD, is corrupted. I see this at work once every month or two so know it well. Re-download the Windows 7 ISO image to use with Parallels. Also re-burn the new ISO image to DVD if you still need a physical disc (for Boot Camp). If this error occurs with a retail DVD try and ask for a replacement or check that your optical drive is in full working order (having tried using a CD/DVD lens cleaner on it first).
There is an absolute solution this problem; 1. Burn iso image to DVD, period. Because this error appears just with USB stick. 2. Want to use USB stick (like me) I know you won't believe me about my weird (odd) solution but it works :) Whenever I try to install Win7 from USB stick, this problem shows up. Then I examine USB stick's light. When error occured that light blink harmonic. I try to pull and push USB stick slowly and smoothly in its nest a couple times. When i see that light blink continuously then this error go away. Just pull and push very carefully. Before that I tried USB stick to put another USB socket or other USB sticks but it didn't work because neither my USB sticks nor USB ports don't broken. Finally the last word is Windows in Bootcamp doesn't like USB sticks much :D
24,762
I'm installing Windows 7 on my Mac via Parallels. During installation I'm getting. "A required CD/DVD drive device driver is missing." message. Doesn't give me any option to proceed further. What am I doing wrong? p.s. I hit same message using bootcamp. I'm using Macbook Pro OS X, Core i7. Trying to install Windows 7 Pro 64bit. ![enter image description here](https://i.stack.imgur.com/grSjK.png)
2011/09/11
[ "https://apple.stackexchange.com/questions/24762", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/910/" ]
Everyone seemed to think that re-burning the disk would fix the issue. It did for a lot of people. But I had a purchased copy that I didn't burn. The fix for me was to let Windows boot up. You'll see the black screen with a progress bar where the windows installer starts up. Start tapping F8. You might have to hold Alt/Option while tapping. I tried both just to be sure the menu would pop up. Then select: Disable Driver Signature Enforcement. Doing that let me continue through the installer.
You are using the USB flash drive option. Avoid booting from a USB flash drive; use a bootable DVD for installation and this will never happen again.
24,762
I'm installing Windows 7 on my Mac via Parallels. During installation I'm getting. "A required CD/DVD drive device driver is missing." message. Doesn't give me any option to proceed further. What am I doing wrong? p.s. I hit same message using bootcamp. I'm using Macbook Pro OS X, Core i7. Trying to install Windows 7 Pro 64bit. ![enter image description here](https://i.stack.imgur.com/grSjK.png)
2011/09/11
[ "https://apple.stackexchange.com/questions/24762", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/910/" ]
I went through all the post, tried most of them and a lot of them were not making any sense. Unfortunately I cannot come up with the exact way I solved the issue but here is what I did. 1. Delete your actual VM, it is no good. 2. Update your Parallels Desktop, I am working with 8.0.18608. 3. Create the VM using a brand new downloaded ISO for which I used a download manager (ex. Folx) 4. Recreate your VM, it workes just fine for me. Honestly I don't think the iso file is the problem. If I were you I would try with the one you have right now. After I updated my Parallels it wasn't working until I realized I was still trying to install with the VM I created with the previous version. When I deleted and created a new one it worked. So if you are reading this, just update your Parallels, delete your VMs and start over, don't worry about configuration it didn't do anything good for me, IDE or SATA. Just make sure you start fresh. Hope it helps, cause for me, none of the other posts helped. Dominique
There is an absolute solution this problem; 1. Burn iso image to DVD, period. Because this error appears just with USB stick. 2. Want to use USB stick (like me) I know you won't believe me about my weird (odd) solution but it works :) Whenever I try to install Win7 from USB stick, this problem shows up. Then I examine USB stick's light. When error occured that light blink harmonic. I try to pull and push USB stick slowly and smoothly in its nest a couple times. When i see that light blink continuously then this error go away. Just pull and push very carefully. Before that I tried USB stick to put another USB socket or other USB sticks but it didn't work because neither my USB sticks nor USB ports don't broken. Finally the last word is Windows in Bootcamp doesn't like USB sticks much :D
24,762
I'm installing Windows 7 on my Mac via Parallels. During installation I'm getting. "A required CD/DVD drive device driver is missing." message. Doesn't give me any option to proceed further. What am I doing wrong? p.s. I hit same message using bootcamp. I'm using Macbook Pro OS X, Core i7. Trying to install Windows 7 Pro 64bit. ![enter image description here](https://i.stack.imgur.com/grSjK.png)
2011/09/11
[ "https://apple.stackexchange.com/questions/24762", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/910/" ]
Actually I have found out that this also occurs if you are using usb3.0 ports. If you only have usb 3.0 ports you need to go into the bios and tell it to treat them as usb 2.0 ports in preboot
There is an absolute solution this problem; 1. Burn iso image to DVD, period. Because this error appears just with USB stick. 2. Want to use USB stick (like me) I know you won't believe me about my weird (odd) solution but it works :) Whenever I try to install Win7 from USB stick, this problem shows up. Then I examine USB stick's light. When error occured that light blink harmonic. I try to pull and push USB stick slowly and smoothly in its nest a couple times. When i see that light blink continuously then this error go away. Just pull and push very carefully. Before that I tried USB stick to put another USB socket or other USB sticks but it didn't work because neither my USB sticks nor USB ports don't broken. Finally the last word is Windows in Bootcamp doesn't like USB sticks much :D
24,762
I'm installing Windows 7 on my Mac via Parallels. During installation I'm getting. "A required CD/DVD drive device driver is missing." message. Doesn't give me any option to proceed further. What am I doing wrong? p.s. I hit same message using bootcamp. I'm using Macbook Pro OS X, Core i7. Trying to install Windows 7 Pro 64bit. ![enter image description here](https://i.stack.imgur.com/grSjK.png)
2011/09/11
[ "https://apple.stackexchange.com/questions/24762", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/910/" ]
Everyone seemed to think that re-burning the disk would fix the issue. It did for a lot of people. But I had a purchased copy that I didn't burn. The fix for me was to let Windows boot up. You'll see the black screen with a progress bar where the windows installer starts up. Start tapping F8. You might have to hold Alt/Option while tapping. I tried both just to be sure the menu would pop up. Then select: Disable Driver Signature Enforcement. Doing that let me continue through the installer.
Actually I have found out that this also occurs if you are using usb3.0 ports. If you only have usb 3.0 ports you need to go into the bios and tell it to treat them as usb 2.0 ports in preboot
24,762
I'm installing Windows 7 on my Mac via Parallels. During installation I'm getting. "A required CD/DVD drive device driver is missing." message. Doesn't give me any option to proceed further. What am I doing wrong? p.s. I hit same message using bootcamp. I'm using Macbook Pro OS X, Core i7. Trying to install Windows 7 Pro 64bit. ![enter image description here](https://i.stack.imgur.com/grSjK.png)
2011/09/11
[ "https://apple.stackexchange.com/questions/24762", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/910/" ]
This error commonly occurs when the Windows 7 DVD, or the ISO image used to create said DVD, is corrupted. I see this at work once every month or two so know it well. Re-download the Windows 7 ISO image to use with Parallels. Also re-burn the new ISO image to DVD if you still need a physical disc (for Boot Camp). If this error occurs with a retail DVD try and ask for a replacement or check that your optical drive is in full working order (having tried using a CD/DVD lens cleaner on it first).
I went through all the post, tried most of them and a lot of them were not making any sense. Unfortunately I cannot come up with the exact way I solved the issue but here is what I did. 1. Delete your actual VM, it is no good. 2. Update your Parallels Desktop, I am working with 8.0.18608. 3. Create the VM using a brand new downloaded ISO for which I used a download manager (ex. Folx) 4. Recreate your VM, it workes just fine for me. Honestly I don't think the iso file is the problem. If I were you I would try with the one you have right now. After I updated my Parallels it wasn't working until I realized I was still trying to install with the VM I created with the previous version. When I deleted and created a new one it worked. So if you are reading this, just update your Parallels, delete your VMs and start over, don't worry about configuration it didn't do anything good for me, IDE or SATA. Just make sure you start fresh. Hope it helps, cause for me, none of the other posts helped. Dominique
24,762
I'm installing Windows 7 on my Mac via Parallels. During installation I'm getting. "A required CD/DVD drive device driver is missing." message. Doesn't give me any option to proceed further. What am I doing wrong? p.s. I hit same message using bootcamp. I'm using Macbook Pro OS X, Core i7. Trying to install Windows 7 Pro 64bit. ![enter image description here](https://i.stack.imgur.com/grSjK.png)
2011/09/11
[ "https://apple.stackexchange.com/questions/24762", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/910/" ]
Everyone seemed to think that re-burning the disk would fix the issue. It did for a lot of people. But I had a purchased copy that I didn't burn. The fix for me was to let Windows boot up. You'll see the black screen with a progress bar where the windows installer starts up. Start tapping F8. You might have to hold Alt/Option while tapping. I tried both just to be sure the menu would pop up. Then select: Disable Driver Signature Enforcement. Doing that let me continue through the installer.
There is an absolute solution this problem; 1. Burn iso image to DVD, period. Because this error appears just with USB stick. 2. Want to use USB stick (like me) I know you won't believe me about my weird (odd) solution but it works :) Whenever I try to install Win7 from USB stick, this problem shows up. Then I examine USB stick's light. When error occured that light blink harmonic. I try to pull and push USB stick slowly and smoothly in its nest a couple times. When i see that light blink continuously then this error go away. Just pull and push very carefully. Before that I tried USB stick to put another USB socket or other USB sticks but it didn't work because neither my USB sticks nor USB ports don't broken. Finally the last word is Windows in Bootcamp doesn't like USB sticks much :D
24,762
I'm installing Windows 7 on my Mac via Parallels. During installation I'm getting. "A required CD/DVD drive device driver is missing." message. Doesn't give me any option to proceed further. What am I doing wrong? p.s. I hit same message using bootcamp. I'm using Macbook Pro OS X, Core i7. Trying to install Windows 7 Pro 64bit. ![enter image description here](https://i.stack.imgur.com/grSjK.png)
2011/09/11
[ "https://apple.stackexchange.com/questions/24762", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/910/" ]
Everyone seemed to think that re-burning the disk would fix the issue. It did for a lot of people. But I had a purchased copy that I didn't burn. The fix for me was to let Windows boot up. You'll see the black screen with a progress bar where the windows installer starts up. Start tapping F8. You might have to hold Alt/Option while tapping. I tried both just to be sure the menu would pop up. Then select: Disable Driver Signature Enforcement. Doing that let me continue through the installer.
I went through all the post, tried most of them and a lot of them were not making any sense. Unfortunately I cannot come up with the exact way I solved the issue but here is what I did. 1. Delete your actual VM, it is no good. 2. Update your Parallels Desktop, I am working with 8.0.18608. 3. Create the VM using a brand new downloaded ISO for which I used a download manager (ex. Folx) 4. Recreate your VM, it workes just fine for me. Honestly I don't think the iso file is the problem. If I were you I would try with the one you have right now. After I updated my Parallels it wasn't working until I realized I was still trying to install with the VM I created with the previous version. When I deleted and created a new one it worked. So if you are reading this, just update your Parallels, delete your VMs and start over, don't worry about configuration it didn't do anything good for me, IDE or SATA. Just make sure you start fresh. Hope it helps, cause for me, none of the other posts helped. Dominique
24,762
I'm installing Windows 7 on my Mac via Parallels. During installation I'm getting. "A required CD/DVD drive device driver is missing." message. Doesn't give me any option to proceed further. What am I doing wrong? p.s. I hit same message using bootcamp. I'm using Macbook Pro OS X, Core i7. Trying to install Windows 7 Pro 64bit. ![enter image description here](https://i.stack.imgur.com/grSjK.png)
2011/09/11
[ "https://apple.stackexchange.com/questions/24762", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/910/" ]
This error commonly occurs when the Windows 7 DVD, or the ISO image used to create said DVD, is corrupted. I see this at work once every month or two so know it well. Re-download the Windows 7 ISO image to use with Parallels. Also re-burn the new ISO image to DVD if you still need a physical disc (for Boot Camp). If this error occurs with a retail DVD try and ask for a replacement or check that your optical drive is in full working order (having tried using a CD/DVD lens cleaner on it first).
Actually I have found out that this also occurs if you are using usb3.0 ports. If you only have usb 3.0 ports you need to go into the bios and tell it to treat them as usb 2.0 ports in preboot
24,762
I'm installing Windows 7 on my Mac via Parallels. During installation I'm getting. "A required CD/DVD drive device driver is missing." message. Doesn't give me any option to proceed further. What am I doing wrong? p.s. I hit same message using bootcamp. I'm using Macbook Pro OS X, Core i7. Trying to install Windows 7 Pro 64bit. ![enter image description here](https://i.stack.imgur.com/grSjK.png)
2011/09/11
[ "https://apple.stackexchange.com/questions/24762", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/910/" ]
You are using the USB flash drive option. Avoid booting from a USB flash drive; use a bootable DVD for installation and this will never happen again.
There is an absolute solution this problem; 1. Burn iso image to DVD, period. Because this error appears just with USB stick. 2. Want to use USB stick (like me) I know you won't believe me about my weird (odd) solution but it works :) Whenever I try to install Win7 from USB stick, this problem shows up. Then I examine USB stick's light. When error occured that light blink harmonic. I try to pull and push USB stick slowly and smoothly in its nest a couple times. When i see that light blink continuously then this error go away. Just pull and push very carefully. Before that I tried USB stick to put another USB socket or other USB sticks but it didn't work because neither my USB sticks nor USB ports don't broken. Finally the last word is Windows in Bootcamp doesn't like USB sticks much :D
64,339,740
I have an array arr from which I want to remove duplicate objects which have \_ same `e_display_id` \_ and `e_type` as `P`. In this case I want to only consider the object with `status==='N'`. Below is input array arr: ```js let arr = [ { e_type: "P", e_record_id: 33780, e_display_id: "EA-15-001", status: "Y" } , { e_type: "P", e_record_id: 33744, e_display_id: "PE-14-016", status: "N" } , { e_type: "P", e_record_id: 33386, e_display_id: "PE-14-016", status: "Y" } , { e_type: "P", e_record_id: 420, e_display_id: "PE-14-911", status: "Y" } , { e_type: "P", e_record_id: 421, e_display_id: "PE-14-911", status: "N" } , { e_type: "R", e_record_id: 33386, e_display_id: "PE-14-016", status: "Y" } , { e_type: "R", e_record_id: 33386, e_display_id: "PE-14-016", status: "Y" } ]; ``` My current implementation: I am using loadash methods to filter out `e_type` as `P` and then checking if there is any duplicate `e_display_id`, if there is then only consider the one which has `status` as `N`. ```js let clonedPursuits = [...arr]; let myarr = _.filter(clonedPursuits, x => x.e_type === 'P'); const counts = _.countBy(myarr, 'e_display_id'); clonedPursuits = _.filter(myarr, x => counts[x.e_display_id] > 1); const uniqueAddresses = Array.from(new Set(clonedPursuits.map(a => a.e_display_id))) .map(id => { return clonedPursuits.find(a => a.e_display_id === id && a.status === "N"); }); console.log( uniqueAddresses ); ``` Expected Output: ```js [ { e_type: "P", e_record_id: 33780, e_display_id: "EA-15-001", status: "Y" } , { e_type: "P", e_record_id: 33744, e_display_id: "PE-14-016", status: "N" } , { e_type: "P", e_record_id: 421, e_display_id: "PE-14-911", status: "N" } , { e_type: "R", e_record_id: 33386, e_display_id: "PE-14-016", status: "Y" } , { e_type: "R", e_record_id: 33386, e_display_id: "PE-14-016", status: "Y" } ]; ``` Current output: ```js [ { e_type: "P", e_record_id: 33744, e_display_id: "PE-14-016", status: "N"} , { e_type: "P", e_record_id: 421, e_display_id: "PE-14-911", status: "N"} ] ```
2020/10/13
[ "https://Stackoverflow.com/questions/64339740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11847033/" ]
You could just do the following and change the php to take the GET param i.e. ``` $(document).on('click', '.show', function(){ var schedule_id = $(this).attr("id"); window.location.href = 'show_schedule.php?schedule_id='+schedule_id; }); }); ``` If it HAS to be a POST then a few solutions to be found @ [pass post data with window.location.href](https://stackoverflow.com/questions/2367979/pass-post-data-with-window-location-href)
I have send data using `jQuery` ajax `post` request to `getval.php` file and data will be send successfully. ajax.php ``` !DOCTYPE html> <html> <head> <title>ajax request</title> <!-- jQuery cdn --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <button id="send-data">send data</button> <div class="data"></div> </body> </html> <script type="text/javascript"> $(document).ready(function () { $('#send-data').click(function () { let val = "test"; // send val variable data $.post("getval.php", { value: val }, function (data, status) { //send data using post request if (status == "success") { $('#send-data').remove(); $('.data').append(data); } }); }); }); </script> ``` getval.php ``` <?php if (isset($_POST['value'])) { $data = $_POST['value']; echo "<br>The data is : ".$data; } ?> ``` OUTPUT :- The data is : test
49,333,852
Currently trying to run a bash script on startup to automatically install squid, however the command I'm running requires input. Currently the script i have is: ``` #!/bin/sh PROXY_USER=user1 PROXY_PASS=password1 wget https://raw.githubusercontent.com/hidden-refuge/spi/master/spi && bash spi -rhel7 && rm spi #After i run this command it asks "Enter username" #followed by "Enter password" and "Renter password" echo $PROXY_USER echo $PROXY_PASS echo $PROXY_PASS echo yes ``` However i am unable to get the input working, and the script fails to create a username and password. I'm running centos 7.
2018/03/17
[ "https://Stackoverflow.com/questions/49333852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8950420/" ]
Look you are calling some tools which act in interactive mode, so as [dani-gehtdichnixan](https://stackoverflow.com/users/1974371/dani-gehtdichnixan) mentioned at ([passing arguments to an interactive program non interactively](https://stackoverflow.com/questions/14392525/passing-arguments-to-an-interactive-program-non-interactively)) you can use `expect` utilities. Install `expect` at debian: ``` apt-get install expect ``` Create a script call `spi-install.exp` which could look like this: ``` #!/usr/bin/env expect set user username set pass your-pass spawn spi -rhel7 expect "Enter username" send "$user\r" expect "Renter password" send "$pass\r" ``` Then call it at your main bash script: ``` #!/bin/bash wget https://raw.githubusercontent.com/hidden-refuge/spi/master/spi && ./spi-install.exp && rm spi ``` > > Expect is used to automate control of interactive applications such as Telnet, FTP, passwd, fsck, rlogin, tip, SSH, and others. Expect uses pseudo terminals (Unix) or emulates a console (Windows), starts the target program, and then communicates with it, just as a human would, via the terminal or console interface. Tk, another Tcl extension, can be used to provide a GUI. > > > <https://en.wikipedia.org/wiki/Expect> Reference : [1] [passing arguments to an interactive program non interactively](https://stackoverflow.com/questions/14392525/passing-arguments-to-an-interactive-program-non-interactively) [2] <https://askubuntu.com/questions/307067/how-to-execute-sudo-commands-with-expect-send-commands-in-bash-script> [3] <https://superuser.com/questions/488713/what-is-the-meaning-of-spawn-linux-shell-commands-centos6>
Try just passing the values to bash's stdin ``` #!/bin/sh PROXY_USER=user1 PROXY_PASS=password1 if wget https://raw.githubusercontent.com/hidden-refuge/spi/master/spi; then printf "%s\n" "$PROXY_USER" "$PROXY_PASS" "$PROXY_PASS" yes | bash spi -rhel7 rm spi fi ```
70,168,614
I have written this code where I am validating data in the Registration Form.On submitting the invalid data, this data is still being submitted.I don't want to submit this invalid data.For eg. Name :1234 This Name is invalid.It still gets submitted. The condition is that I have to use only javascript and HTML. ```js function formValidation() { var name = document.getElementById("name").value; var email = document.getElementById("email").value; var mobile = document.getElementById("mobile").value; var address = document.getElementById("address").value; var pincode = document.getElementById("pincode").value; var state = document.getElementById("state").value; var country = document.getElementById("country").value; var coursename = document.getElementById("coursename").value; var pattern1 = /^\d{6}$/; var pattern2 = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; var letters = /^[A-Za-z]+$/; var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (name == '') { alert('Please enter your name'); } else if (!letters.test(name)) { alert('Name field required only alphabet characters'); } else if (document.getElementById("name").value.length < 6) { alert('Name minimum length is 6'); } else if (document.getElementById("name").value.length > 33) { alert('Name maximum length is 33'); } else if (email == '') { alert('Please enter your user email id'); } else if (!filter.test(email)) { alert('Invalid email'); } else if (mobile == '') { alert('Please enter your mobile'); } else if (!pattern2.test(mobile)) { alert('Mobile Should be 10 digits') } else if (address == '') { alert('Please enter your address'); } else if (document.getElementById("address").value.length < 20) { alert('Address minimum length is 20'); } else if (document.getElementById("address").value.length > 32) { alert('Address maximum length is 32'); } else if (pincode == '') { alert('Please enter your pincode'); } else if (!pattern1.test(pincode)) { alert('Pincode Should be 6 digits') } else if (state == '') { alert('Please enter your state'); } else if (!letters.test(state)) { alert('State field required only alphabet characters'); } else if (document.getElementById("state").value.length < 6) { alert('state minimum length is 6'); } else if (document.getElementById("state").value.length > 33) { alert('state maximum length is 33'); } else if (country == '') { alert('Please enter your Country'); } else if (!letters.test(country)) { alert('Country field required only alphabet characters'); } else if (document.getElementById("country").value.length < 5) { alert('Country Name minimum length is 6'); } else if (document.getElementById("Country").value.length > 33) { alert('Country Name maximum length is 33'); } else if (coursename == '') { alert('Please enter your course name'); } else if (!letters.test(coursename)) { alert('Course Name field required only alphabet characters'); } else if (document.getElementById("name").value.length < 3) { alert('Course Name minimum length is 6'); } else if (document.getElementById("coursename").value.length > 40) { alert('Course Name maximum length is 40') } else { alert('Thank You for Registratione'); } } ``` ```css body { font-family: Arial; } input[type=text], textarea, input[type=date] { width: 96%; padding: 12px 20px; margin: 8px 0; } select { width: 99%; padding: 12px 20px; margin: 8px 0; } input[type=submit], input[type=reset] { width: 100%; background-color: grey; color: white; padding: 14px 20px; margin: 8px 0; } ``` ```html <h3>STUDENT REGISTRATION FORM</h3> <form name="registration"> Applicant Name:<input type="text" name="name" id="name" placeholder="Enter your Full Name"><br> Email id:<input type="text" name="email" id="email" placeholder="Enter your email id"><br> Mobile Number:<input type="text" name="mobile" id="mobile" placeholder="Enter your mobile number"><br> Address: <textarea name="address" id="address" cols="35" rows="4"></textarea><br> Pin Code<input type="text" name="pincode" id="pincode" placeholder="Enter the pincode"><br> State: <br><input type="text" name="state" id="state" placeholder="Enter the state name"><br> Country: <input type="text" name="country" id="country" placeholder="Enter the name of residing country"><br> Course Name:<input type="text" name="coursename" id="coursename" placeholder="Enter the course name"> <!-- <input type="submit" name="submit" value="Submit" onclick="formValidation()" /> --> <button type="submit" onsubmit="formValidation()">Submit</button> </form> ```
2021/11/30
[ "https://Stackoverflow.com/questions/70168614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14429751/" ]
I would highly suggest you use the `addEventListener` instead of using the HTML for this. A solution with `addEventListener`: ```js const form = document.querySelector("form"); function formValidation() { form.addEventListener("submit", (e) => { if(/*your condition is invalid*/) { e.preventDefault(); } else if..... //your other validations here }) } ```
Please use this code ``` function formValidation() { var name = document.getElementById("name").value; var email = document.getElementById("email").value; var mobile = document.getElementById("mobile").value; var address = document.getElementById("address").value; var pincode = document.getElementById("pincode").value; var state = document.getElementById("state").value; var country = document.getElementById("country").value; var coursename = document.getElementById("coursename").value; var pattern1 = /^\d{6}$/; var pattern2 = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; var letters = /^[A-Za-z]+$/; var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (name == '') { alert('Please enter your name'); return false; } else if (!letters.test(name)) { alert('Name field required only alphabet characters'); return false; } else if (document.getElementById("name").value.length < 6) { alert('Name minimum length is 6'); return false; } else if (document.getElementById("name").value.length > 33) { alert('Name maximum length is 33'); return false; } else if (email == '') { alert('Please enter your user email id'); return false; } else if (!filter.test(email)) { alert('Invalid email'); return false; } else if (mobile == '') { alert('Please enter your mobile'); return false; } else if (!pattern2.test(mobile)) { alert('Mobile Should be 10 digits') return false; } else if (address == '') { alert('Please enter your address'); return false; } else if (document.getElementById("address").value.length < 20) { alert('Address minimum length is 20'); return false; } else if (document.getElementById("address").value.length > 32) { alert('Address maximum length is 32'); return false; } else if (pincode == '') { alert('Please enter your pincode'); return false; } else if (!pattern1.test(pincode)) { alert('Pincode Should be 6 digits') return false; } else if (state == '') { alert('Please enter your state'); return false; } else if (!letters.test(state)) { alert('State field required only alphabet characters'); return false; } else if (document.getElementById("state").value.length < 6) { alert('state minimum length is 6'); return false; } else if (document.getElementById("state").value.length > 33) { alert('state maximum length is 33'); return false; } else if (country == '') { alert('Please enter your Country'); return false; } else if (!letters.test(country)) { alert('Country field required only alphabet characters'); return false; } else if (document.getElementById("country").value.length < 5) { alert('Country Name minimum length is 6'); return false; } else if (document.getElementById("Country").value.length > 33) { alert('Country Name maximum length is 33'); return false; } else if (coursename == '') { alert('Please enter your course name'); return false; } else if (!letters.test(coursename)) { alert('Course Name field required only alphabet characters'); return false; } else if (document.getElementById("name").value.length < 3) { alert('Course Name minimum length is 6'); return false; } else if (document.getElementById("coursename").value.length > 40) { alert('Course Name maximum length is 40') return false; } else { alert('Thank You for Registratione'); return false; } return true; } ``` ```html <h3>STUDENT REGISTRATION FORM</h3> <form name="registration" onsubmit="return formValidation()"> Applicant Name:<input type="text" name="name" id="name" placeholder="Enter your Full Name"><br> Email id:<input type="text" name="email" id="email" placeholder="Enter your email id"><br> Mobile Number:<input type="text" name="mobile" id="mobile" placeholder="Enter your mobile number"><br> Address: <textarea name="address" id="address" cols="35" rows="4"></textarea><br> Pin Code<input type="text" name="pincode" id="pincode" placeholder="Enter the pincode"><br> State: <br><input type="text" name="state" id="state" placeholder="Enter the state name"><br> Country: <input type="text" name="country" id="country" placeholder="Enter the name of residing country"><br> Course Name:<input type="text" name="coursename" id="coursename" placeholder="Enter the course name"> <!-- <input type="submit" name="submit" value="Submit" onclick="formValidation()" /> --> <button type="submit" >Submit</button> ```
70,168,614
I have written this code where I am validating data in the Registration Form.On submitting the invalid data, this data is still being submitted.I don't want to submit this invalid data.For eg. Name :1234 This Name is invalid.It still gets submitted. The condition is that I have to use only javascript and HTML. ```js function formValidation() { var name = document.getElementById("name").value; var email = document.getElementById("email").value; var mobile = document.getElementById("mobile").value; var address = document.getElementById("address").value; var pincode = document.getElementById("pincode").value; var state = document.getElementById("state").value; var country = document.getElementById("country").value; var coursename = document.getElementById("coursename").value; var pattern1 = /^\d{6}$/; var pattern2 = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; var letters = /^[A-Za-z]+$/; var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (name == '') { alert('Please enter your name'); } else if (!letters.test(name)) { alert('Name field required only alphabet characters'); } else if (document.getElementById("name").value.length < 6) { alert('Name minimum length is 6'); } else if (document.getElementById("name").value.length > 33) { alert('Name maximum length is 33'); } else if (email == '') { alert('Please enter your user email id'); } else if (!filter.test(email)) { alert('Invalid email'); } else if (mobile == '') { alert('Please enter your mobile'); } else if (!pattern2.test(mobile)) { alert('Mobile Should be 10 digits') } else if (address == '') { alert('Please enter your address'); } else if (document.getElementById("address").value.length < 20) { alert('Address minimum length is 20'); } else if (document.getElementById("address").value.length > 32) { alert('Address maximum length is 32'); } else if (pincode == '') { alert('Please enter your pincode'); } else if (!pattern1.test(pincode)) { alert('Pincode Should be 6 digits') } else if (state == '') { alert('Please enter your state'); } else if (!letters.test(state)) { alert('State field required only alphabet characters'); } else if (document.getElementById("state").value.length < 6) { alert('state minimum length is 6'); } else if (document.getElementById("state").value.length > 33) { alert('state maximum length is 33'); } else if (country == '') { alert('Please enter your Country'); } else if (!letters.test(country)) { alert('Country field required only alphabet characters'); } else if (document.getElementById("country").value.length < 5) { alert('Country Name minimum length is 6'); } else if (document.getElementById("Country").value.length > 33) { alert('Country Name maximum length is 33'); } else if (coursename == '') { alert('Please enter your course name'); } else if (!letters.test(coursename)) { alert('Course Name field required only alphabet characters'); } else if (document.getElementById("name").value.length < 3) { alert('Course Name minimum length is 6'); } else if (document.getElementById("coursename").value.length > 40) { alert('Course Name maximum length is 40') } else { alert('Thank You for Registratione'); } } ``` ```css body { font-family: Arial; } input[type=text], textarea, input[type=date] { width: 96%; padding: 12px 20px; margin: 8px 0; } select { width: 99%; padding: 12px 20px; margin: 8px 0; } input[type=submit], input[type=reset] { width: 100%; background-color: grey; color: white; padding: 14px 20px; margin: 8px 0; } ``` ```html <h3>STUDENT REGISTRATION FORM</h3> <form name="registration"> Applicant Name:<input type="text" name="name" id="name" placeholder="Enter your Full Name"><br> Email id:<input type="text" name="email" id="email" placeholder="Enter your email id"><br> Mobile Number:<input type="text" name="mobile" id="mobile" placeholder="Enter your mobile number"><br> Address: <textarea name="address" id="address" cols="35" rows="4"></textarea><br> Pin Code<input type="text" name="pincode" id="pincode" placeholder="Enter the pincode"><br> State: <br><input type="text" name="state" id="state" placeholder="Enter the state name"><br> Country: <input type="text" name="country" id="country" placeholder="Enter the name of residing country"><br> Course Name:<input type="text" name="coursename" id="coursename" placeholder="Enter the course name"> <!-- <input type="submit" name="submit" value="Submit" onclick="formValidation()" /> --> <button type="submit" onsubmit="formValidation()">Submit</button> </form> ```
2021/11/30
[ "https://Stackoverflow.com/questions/70168614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14429751/" ]
I would highly suggest you use the `addEventListener` instead of using the HTML for this. A solution with `addEventListener`: ```js const form = document.querySelector("form"); function formValidation() { form.addEventListener("submit", (e) => { if(/*your condition is invalid*/) { e.preventDefault(); } else if..... //your other validations here }) } ```
To prevent form submission, first you change the submit button type form `submit` to `button` and then change the event `onsubmit` to `onclick`. ```js function formValidation() { var name = document.getElementById("name").value; var email = document.getElementById("email").value; var mobile = document.getElementById("mobile").value; var address = document.getElementById("address").value; var pincode = document.getElementById("pincode").value; var state = document.getElementById("state").value; var country = document.getElementById("country").value; var coursename = document.getElementById("coursename").value; var pattern1 = /^\d{6}$/; var pattern2 = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; var letters = /^[A-Za-z]+$/; var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (name == '') { alert('Please enter your name'); } else if (!letters.test(name)) { alert('Name field required only alphabet characters'); } else if (document.getElementById("name").value.length < 6) { alert('Name minimum length is 6'); } else if (document.getElementById("name").value.length > 33) { alert('Name maximum length is 33'); } else if (email == '') { alert('Please enter your user email id'); } else if (!filter.test(email)) { alert('Invalid email'); } else if (mobile == '') { alert('Please enter your mobile'); } else if (!pattern2.test(mobile)) { alert('Mobile Should be 10 digits') } else if (address == '') { alert('Please enter your address'); } else if (document.getElementById("address").value.length < 20) { alert('Address minimum length is 20'); } else if (document.getElementById("address").value.length > 32) { alert('Address maximum length is 32'); } else if (pincode == '') { alert('Please enter your pincode'); } else if (!pattern1.test(pincode)) { alert('Pincode Should be 6 digits') } else if (state == '') { alert('Please enter your state'); } else if (!letters.test(state)) { alert('State field required only alphabet characters'); } else if (document.getElementById("state").value.length < 6) { alert('state minimum length is 6'); } else if (document.getElementById("state").value.length > 33) { alert('state maximum length is 33'); } else if (country == '') { alert('Please enter your Country'); } else if (!letters.test(country)) { alert('Country field required only alphabet characters'); } else if (document.getElementById("country").value.length < 5) { alert('Country Name minimum length is 6'); } else if (document.getElementById("Country").value.length > 33) { alert('Country Name maximum length is 33'); } else if (coursename == '') { alert('Please enter your course name'); } else if (!letters.test(coursename)) { alert('Course Name field required only alphabet characters'); } else if (document.getElementById("name").value.length < 3) { alert('Course Name minimum length is 6'); } else if (document.getElementById("coursename").value.length > 40) { alert('Course Name maximum length is 40') } else { alert('Thank You for Registratione'); } } ``` ```css body { font-family: Arial; } input[type=text], textarea, input[type=date] { width: 96%; padding: 12px 20px; margin: 8px 0; } select { width: 99%; padding: 12px 20px; margin: 8px 0; } input[type=submit], input[type=reset] { width: 100%; background-color: grey; color: white; padding: 14px 20px; margin: 8px 0; } ``` ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <h3>STUDENT REGISTRATION FORM</h3> <form name="registration"> Applicant Name:<input type="text" name="name" id="name" placeholder="Enter your Full Name"><br> Email id:<input type="text" name="email" id="email" placeholder="Enter your email id"><br> Mobile Number:<input type="text" name="mobile" id="mobile" placeholder="Enter your mobile number"><br> Address: <textarea name="address" id="address" cols="35" rows="4"></textarea><br> Pin Code<input type="text" name="pincode" id="pincode" placeholder="Enter the pincode"><br> State: <br><input type="text" name="state" id="state" placeholder="Enter the state name"><br> Country: <input type="text" name="country" id="country" placeholder="Enter the name of residing country"><br> Course Name:<input type="text" name="coursename" id="coursename" placeholder="Enter the course name"> <!-- <input type="submit" name="submit" value="Submit" onclick="formValidation()" /> --> <button type="button" onClick="formValidation()">Submit</button> </form> </body> </html> ```
70,168,614
I have written this code where I am validating data in the Registration Form.On submitting the invalid data, this data is still being submitted.I don't want to submit this invalid data.For eg. Name :1234 This Name is invalid.It still gets submitted. The condition is that I have to use only javascript and HTML. ```js function formValidation() { var name = document.getElementById("name").value; var email = document.getElementById("email").value; var mobile = document.getElementById("mobile").value; var address = document.getElementById("address").value; var pincode = document.getElementById("pincode").value; var state = document.getElementById("state").value; var country = document.getElementById("country").value; var coursename = document.getElementById("coursename").value; var pattern1 = /^\d{6}$/; var pattern2 = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; var letters = /^[A-Za-z]+$/; var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (name == '') { alert('Please enter your name'); } else if (!letters.test(name)) { alert('Name field required only alphabet characters'); } else if (document.getElementById("name").value.length < 6) { alert('Name minimum length is 6'); } else if (document.getElementById("name").value.length > 33) { alert('Name maximum length is 33'); } else if (email == '') { alert('Please enter your user email id'); } else if (!filter.test(email)) { alert('Invalid email'); } else if (mobile == '') { alert('Please enter your mobile'); } else if (!pattern2.test(mobile)) { alert('Mobile Should be 10 digits') } else if (address == '') { alert('Please enter your address'); } else if (document.getElementById("address").value.length < 20) { alert('Address minimum length is 20'); } else if (document.getElementById("address").value.length > 32) { alert('Address maximum length is 32'); } else if (pincode == '') { alert('Please enter your pincode'); } else if (!pattern1.test(pincode)) { alert('Pincode Should be 6 digits') } else if (state == '') { alert('Please enter your state'); } else if (!letters.test(state)) { alert('State field required only alphabet characters'); } else if (document.getElementById("state").value.length < 6) { alert('state minimum length is 6'); } else if (document.getElementById("state").value.length > 33) { alert('state maximum length is 33'); } else if (country == '') { alert('Please enter your Country'); } else if (!letters.test(country)) { alert('Country field required only alphabet characters'); } else if (document.getElementById("country").value.length < 5) { alert('Country Name minimum length is 6'); } else if (document.getElementById("Country").value.length > 33) { alert('Country Name maximum length is 33'); } else if (coursename == '') { alert('Please enter your course name'); } else if (!letters.test(coursename)) { alert('Course Name field required only alphabet characters'); } else if (document.getElementById("name").value.length < 3) { alert('Course Name minimum length is 6'); } else if (document.getElementById("coursename").value.length > 40) { alert('Course Name maximum length is 40') } else { alert('Thank You for Registratione'); } } ``` ```css body { font-family: Arial; } input[type=text], textarea, input[type=date] { width: 96%; padding: 12px 20px; margin: 8px 0; } select { width: 99%; padding: 12px 20px; margin: 8px 0; } input[type=submit], input[type=reset] { width: 100%; background-color: grey; color: white; padding: 14px 20px; margin: 8px 0; } ``` ```html <h3>STUDENT REGISTRATION FORM</h3> <form name="registration"> Applicant Name:<input type="text" name="name" id="name" placeholder="Enter your Full Name"><br> Email id:<input type="text" name="email" id="email" placeholder="Enter your email id"><br> Mobile Number:<input type="text" name="mobile" id="mobile" placeholder="Enter your mobile number"><br> Address: <textarea name="address" id="address" cols="35" rows="4"></textarea><br> Pin Code<input type="text" name="pincode" id="pincode" placeholder="Enter the pincode"><br> State: <br><input type="text" name="state" id="state" placeholder="Enter the state name"><br> Country: <input type="text" name="country" id="country" placeholder="Enter the name of residing country"><br> Course Name:<input type="text" name="coursename" id="coursename" placeholder="Enter the course name"> <!-- <input type="submit" name="submit" value="Submit" onclick="formValidation()" /> --> <button type="submit" onsubmit="formValidation()">Submit</button> </form> ```
2021/11/30
[ "https://Stackoverflow.com/questions/70168614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14429751/" ]
Your `onsubmit` function should return false and `preventDefault()` on the event for each case where it fails validation. Your `onsubmit` should also be bound to the `form` element, not the `button`. I get the impression that this is an assignment for a class, but I would still like to reiterate the point that inline JS is generally bad for both readability and maintainability of your code. If your class permits it, use event listeners. ```js function formValidation(e) { var name = document.getElementById("name").value; var email = document.getElementById("email").value; var mobile = document.getElementById("mobile").value; var address = document.getElementById("address").value; var pincode = document.getElementById("pincode").value; var state = document.getElementById("state").value; var country = document.getElementById("country").value; var coursename = document.getElementById("coursename").value; var pattern1 = /^\d{6}$/; var pattern2 = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; var letters = /^[A-Za-z]+$/; var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (name == '') { alert('Please enter your name'); } else if (!letters.test(name)) { alert('Name field required only alphabet characters'); } else if (document.getElementById("name").value.length < 6) { alert('Name minimum length is 6'); } else if (document.getElementById("name").value.length > 33) { alert('Name maximum length is 33'); } else if (email == '') { alert('Please enter your user email id'); } else if (!filter.test(email)) { alert('Invalid email'); } else if (mobile == '') { alert('Please enter your mobile'); } else if (!pattern2.test(mobile)) { alert('Mobile Should be 10 digits') } else if (address == '') { alert('Please enter your address'); } else if (document.getElementById("address").value.length < 20) { alert('Address minimum length is 20'); } else if (document.getElementById("address").value.length > 32) { alert('Address maximum length is 32'); } else if (pincode == '') { alert('Please enter your pincode'); } else if (!pattern1.test(pincode)) { alert('Pincode Should be 6 digits') } else if (state == '') { alert('Please enter your state'); } else if (!letters.test(state)) { alert('State field required only alphabet characters'); } else if (document.getElementById("state").value.length < 6) { alert('state minimum length is 6'); } else if (document.getElementById("state").value.length > 33) { alert('state maximum length is 33'); } else if (country == '') { alert('Please enter your Country'); } else if (!letters.test(country)) { alert('Country field required only alphabet characters'); } else if (document.getElementById("country").value.length < 5) { alert('Country Name minimum length is 6'); } else if (document.getElementById("Country").value.length > 33) { alert('Country Name maximum length is 33'); } else if (coursename == '') { alert('Please enter your course name'); } else if (!letters.test(coursename)) { alert('Course Name field required only alphabet characters'); } else if (document.getElementById("name").value.length < 3) { alert('Course Name minimum length is 6'); } else if (document.getElementById("coursename").value.length > 40) { alert('Course Name maximum length is 40') } else { alert('Thank You for Registratione'); return true; } e.preventDefault(); return false; } ``` ```css body { font-family: Arial; } input[type=text], textarea, input[type=date] { width: 96%; padding: 12px 20px; margin: 8px 0; } select { width: 99%; padding: 12px 20px; margin: 8px 0; } input[type=submit], input[type=reset] { width: 100%; background-color: grey; color: white; padding: 14px 20px; margin: 8px 0; } ``` ```html <h3>STUDENT REGISTRATION FORM</h3> <form name="registration" onsubmit="formValidation(event)"> Applicant Name:<input type="text" name="name" id="name" placeholder="Enter your Full Name"><br> Email id:<input type="text" name="email" id="email" placeholder="Enter your email id"><br> Mobile Number:<input type="text" name="mobile" id="mobile" placeholder="Enter your mobile number"><br> Address: <textarea name="address" id="address" cols="35" rows="4"></textarea><br> Pin Code<input type="text" name="pincode" id="pincode" placeholder="Enter the pincode"><br> State: <br><input type="text" name="state" id="state" placeholder="Enter the state name"><br> Country: <input type="text" name="country" id="country" placeholder="Enter the name of residing country"><br> Course Name:<input type="text" name="coursename" id="coursename" placeholder="Enter the course name"> <!-- <input type="submit" name="submit" value="Submit" onclick="formValidation()" /> --> <button type="submit">Submit</button> </form> ```
Please use this code ``` function formValidation() { var name = document.getElementById("name").value; var email = document.getElementById("email").value; var mobile = document.getElementById("mobile").value; var address = document.getElementById("address").value; var pincode = document.getElementById("pincode").value; var state = document.getElementById("state").value; var country = document.getElementById("country").value; var coursename = document.getElementById("coursename").value; var pattern1 = /^\d{6}$/; var pattern2 = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; var letters = /^[A-Za-z]+$/; var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (name == '') { alert('Please enter your name'); return false; } else if (!letters.test(name)) { alert('Name field required only alphabet characters'); return false; } else if (document.getElementById("name").value.length < 6) { alert('Name minimum length is 6'); return false; } else if (document.getElementById("name").value.length > 33) { alert('Name maximum length is 33'); return false; } else if (email == '') { alert('Please enter your user email id'); return false; } else if (!filter.test(email)) { alert('Invalid email'); return false; } else if (mobile == '') { alert('Please enter your mobile'); return false; } else if (!pattern2.test(mobile)) { alert('Mobile Should be 10 digits') return false; } else if (address == '') { alert('Please enter your address'); return false; } else if (document.getElementById("address").value.length < 20) { alert('Address minimum length is 20'); return false; } else if (document.getElementById("address").value.length > 32) { alert('Address maximum length is 32'); return false; } else if (pincode == '') { alert('Please enter your pincode'); return false; } else if (!pattern1.test(pincode)) { alert('Pincode Should be 6 digits') return false; } else if (state == '') { alert('Please enter your state'); return false; } else if (!letters.test(state)) { alert('State field required only alphabet characters'); return false; } else if (document.getElementById("state").value.length < 6) { alert('state minimum length is 6'); return false; } else if (document.getElementById("state").value.length > 33) { alert('state maximum length is 33'); return false; } else if (country == '') { alert('Please enter your Country'); return false; } else if (!letters.test(country)) { alert('Country field required only alphabet characters'); return false; } else if (document.getElementById("country").value.length < 5) { alert('Country Name minimum length is 6'); return false; } else if (document.getElementById("Country").value.length > 33) { alert('Country Name maximum length is 33'); return false; } else if (coursename == '') { alert('Please enter your course name'); return false; } else if (!letters.test(coursename)) { alert('Course Name field required only alphabet characters'); return false; } else if (document.getElementById("name").value.length < 3) { alert('Course Name minimum length is 6'); return false; } else if (document.getElementById("coursename").value.length > 40) { alert('Course Name maximum length is 40') return false; } else { alert('Thank You for Registratione'); return false; } return true; } ``` ```html <h3>STUDENT REGISTRATION FORM</h3> <form name="registration" onsubmit="return formValidation()"> Applicant Name:<input type="text" name="name" id="name" placeholder="Enter your Full Name"><br> Email id:<input type="text" name="email" id="email" placeholder="Enter your email id"><br> Mobile Number:<input type="text" name="mobile" id="mobile" placeholder="Enter your mobile number"><br> Address: <textarea name="address" id="address" cols="35" rows="4"></textarea><br> Pin Code<input type="text" name="pincode" id="pincode" placeholder="Enter the pincode"><br> State: <br><input type="text" name="state" id="state" placeholder="Enter the state name"><br> Country: <input type="text" name="country" id="country" placeholder="Enter the name of residing country"><br> Course Name:<input type="text" name="coursename" id="coursename" placeholder="Enter the course name"> <!-- <input type="submit" name="submit" value="Submit" onclick="formValidation()" /> --> <button type="submit" >Submit</button> ```
70,168,614
I have written this code where I am validating data in the Registration Form.On submitting the invalid data, this data is still being submitted.I don't want to submit this invalid data.For eg. Name :1234 This Name is invalid.It still gets submitted. The condition is that I have to use only javascript and HTML. ```js function formValidation() { var name = document.getElementById("name").value; var email = document.getElementById("email").value; var mobile = document.getElementById("mobile").value; var address = document.getElementById("address").value; var pincode = document.getElementById("pincode").value; var state = document.getElementById("state").value; var country = document.getElementById("country").value; var coursename = document.getElementById("coursename").value; var pattern1 = /^\d{6}$/; var pattern2 = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; var letters = /^[A-Za-z]+$/; var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (name == '') { alert('Please enter your name'); } else if (!letters.test(name)) { alert('Name field required only alphabet characters'); } else if (document.getElementById("name").value.length < 6) { alert('Name minimum length is 6'); } else if (document.getElementById("name").value.length > 33) { alert('Name maximum length is 33'); } else if (email == '') { alert('Please enter your user email id'); } else if (!filter.test(email)) { alert('Invalid email'); } else if (mobile == '') { alert('Please enter your mobile'); } else if (!pattern2.test(mobile)) { alert('Mobile Should be 10 digits') } else if (address == '') { alert('Please enter your address'); } else if (document.getElementById("address").value.length < 20) { alert('Address minimum length is 20'); } else if (document.getElementById("address").value.length > 32) { alert('Address maximum length is 32'); } else if (pincode == '') { alert('Please enter your pincode'); } else if (!pattern1.test(pincode)) { alert('Pincode Should be 6 digits') } else if (state == '') { alert('Please enter your state'); } else if (!letters.test(state)) { alert('State field required only alphabet characters'); } else if (document.getElementById("state").value.length < 6) { alert('state minimum length is 6'); } else if (document.getElementById("state").value.length > 33) { alert('state maximum length is 33'); } else if (country == '') { alert('Please enter your Country'); } else if (!letters.test(country)) { alert('Country field required only alphabet characters'); } else if (document.getElementById("country").value.length < 5) { alert('Country Name minimum length is 6'); } else if (document.getElementById("Country").value.length > 33) { alert('Country Name maximum length is 33'); } else if (coursename == '') { alert('Please enter your course name'); } else if (!letters.test(coursename)) { alert('Course Name field required only alphabet characters'); } else if (document.getElementById("name").value.length < 3) { alert('Course Name minimum length is 6'); } else if (document.getElementById("coursename").value.length > 40) { alert('Course Name maximum length is 40') } else { alert('Thank You for Registratione'); } } ``` ```css body { font-family: Arial; } input[type=text], textarea, input[type=date] { width: 96%; padding: 12px 20px; margin: 8px 0; } select { width: 99%; padding: 12px 20px; margin: 8px 0; } input[type=submit], input[type=reset] { width: 100%; background-color: grey; color: white; padding: 14px 20px; margin: 8px 0; } ``` ```html <h3>STUDENT REGISTRATION FORM</h3> <form name="registration"> Applicant Name:<input type="text" name="name" id="name" placeholder="Enter your Full Name"><br> Email id:<input type="text" name="email" id="email" placeholder="Enter your email id"><br> Mobile Number:<input type="text" name="mobile" id="mobile" placeholder="Enter your mobile number"><br> Address: <textarea name="address" id="address" cols="35" rows="4"></textarea><br> Pin Code<input type="text" name="pincode" id="pincode" placeholder="Enter the pincode"><br> State: <br><input type="text" name="state" id="state" placeholder="Enter the state name"><br> Country: <input type="text" name="country" id="country" placeholder="Enter the name of residing country"><br> Course Name:<input type="text" name="coursename" id="coursename" placeholder="Enter the course name"> <!-- <input type="submit" name="submit" value="Submit" onclick="formValidation()" /> --> <button type="submit" onsubmit="formValidation()">Submit</button> </form> ```
2021/11/30
[ "https://Stackoverflow.com/questions/70168614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14429751/" ]
Your `onsubmit` function should return false and `preventDefault()` on the event for each case where it fails validation. Your `onsubmit` should also be bound to the `form` element, not the `button`. I get the impression that this is an assignment for a class, but I would still like to reiterate the point that inline JS is generally bad for both readability and maintainability of your code. If your class permits it, use event listeners. ```js function formValidation(e) { var name = document.getElementById("name").value; var email = document.getElementById("email").value; var mobile = document.getElementById("mobile").value; var address = document.getElementById("address").value; var pincode = document.getElementById("pincode").value; var state = document.getElementById("state").value; var country = document.getElementById("country").value; var coursename = document.getElementById("coursename").value; var pattern1 = /^\d{6}$/; var pattern2 = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; var letters = /^[A-Za-z]+$/; var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (name == '') { alert('Please enter your name'); } else if (!letters.test(name)) { alert('Name field required only alphabet characters'); } else if (document.getElementById("name").value.length < 6) { alert('Name minimum length is 6'); } else if (document.getElementById("name").value.length > 33) { alert('Name maximum length is 33'); } else if (email == '') { alert('Please enter your user email id'); } else if (!filter.test(email)) { alert('Invalid email'); } else if (mobile == '') { alert('Please enter your mobile'); } else if (!pattern2.test(mobile)) { alert('Mobile Should be 10 digits') } else if (address == '') { alert('Please enter your address'); } else if (document.getElementById("address").value.length < 20) { alert('Address minimum length is 20'); } else if (document.getElementById("address").value.length > 32) { alert('Address maximum length is 32'); } else if (pincode == '') { alert('Please enter your pincode'); } else if (!pattern1.test(pincode)) { alert('Pincode Should be 6 digits') } else if (state == '') { alert('Please enter your state'); } else if (!letters.test(state)) { alert('State field required only alphabet characters'); } else if (document.getElementById("state").value.length < 6) { alert('state minimum length is 6'); } else if (document.getElementById("state").value.length > 33) { alert('state maximum length is 33'); } else if (country == '') { alert('Please enter your Country'); } else if (!letters.test(country)) { alert('Country field required only alphabet characters'); } else if (document.getElementById("country").value.length < 5) { alert('Country Name minimum length is 6'); } else if (document.getElementById("Country").value.length > 33) { alert('Country Name maximum length is 33'); } else if (coursename == '') { alert('Please enter your course name'); } else if (!letters.test(coursename)) { alert('Course Name field required only alphabet characters'); } else if (document.getElementById("name").value.length < 3) { alert('Course Name minimum length is 6'); } else if (document.getElementById("coursename").value.length > 40) { alert('Course Name maximum length is 40') } else { alert('Thank You for Registratione'); return true; } e.preventDefault(); return false; } ``` ```css body { font-family: Arial; } input[type=text], textarea, input[type=date] { width: 96%; padding: 12px 20px; margin: 8px 0; } select { width: 99%; padding: 12px 20px; margin: 8px 0; } input[type=submit], input[type=reset] { width: 100%; background-color: grey; color: white; padding: 14px 20px; margin: 8px 0; } ``` ```html <h3>STUDENT REGISTRATION FORM</h3> <form name="registration" onsubmit="formValidation(event)"> Applicant Name:<input type="text" name="name" id="name" placeholder="Enter your Full Name"><br> Email id:<input type="text" name="email" id="email" placeholder="Enter your email id"><br> Mobile Number:<input type="text" name="mobile" id="mobile" placeholder="Enter your mobile number"><br> Address: <textarea name="address" id="address" cols="35" rows="4"></textarea><br> Pin Code<input type="text" name="pincode" id="pincode" placeholder="Enter the pincode"><br> State: <br><input type="text" name="state" id="state" placeholder="Enter the state name"><br> Country: <input type="text" name="country" id="country" placeholder="Enter the name of residing country"><br> Course Name:<input type="text" name="coursename" id="coursename" placeholder="Enter the course name"> <!-- <input type="submit" name="submit" value="Submit" onclick="formValidation()" /> --> <button type="submit">Submit</button> </form> ```
To prevent form submission, first you change the submit button type form `submit` to `button` and then change the event `onsubmit` to `onclick`. ```js function formValidation() { var name = document.getElementById("name").value; var email = document.getElementById("email").value; var mobile = document.getElementById("mobile").value; var address = document.getElementById("address").value; var pincode = document.getElementById("pincode").value; var state = document.getElementById("state").value; var country = document.getElementById("country").value; var coursename = document.getElementById("coursename").value; var pattern1 = /^\d{6}$/; var pattern2 = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; var letters = /^[A-Za-z]+$/; var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (name == '') { alert('Please enter your name'); } else if (!letters.test(name)) { alert('Name field required only alphabet characters'); } else if (document.getElementById("name").value.length < 6) { alert('Name minimum length is 6'); } else if (document.getElementById("name").value.length > 33) { alert('Name maximum length is 33'); } else if (email == '') { alert('Please enter your user email id'); } else if (!filter.test(email)) { alert('Invalid email'); } else if (mobile == '') { alert('Please enter your mobile'); } else if (!pattern2.test(mobile)) { alert('Mobile Should be 10 digits') } else if (address == '') { alert('Please enter your address'); } else if (document.getElementById("address").value.length < 20) { alert('Address minimum length is 20'); } else if (document.getElementById("address").value.length > 32) { alert('Address maximum length is 32'); } else if (pincode == '') { alert('Please enter your pincode'); } else if (!pattern1.test(pincode)) { alert('Pincode Should be 6 digits') } else if (state == '') { alert('Please enter your state'); } else if (!letters.test(state)) { alert('State field required only alphabet characters'); } else if (document.getElementById("state").value.length < 6) { alert('state minimum length is 6'); } else if (document.getElementById("state").value.length > 33) { alert('state maximum length is 33'); } else if (country == '') { alert('Please enter your Country'); } else if (!letters.test(country)) { alert('Country field required only alphabet characters'); } else if (document.getElementById("country").value.length < 5) { alert('Country Name minimum length is 6'); } else if (document.getElementById("Country").value.length > 33) { alert('Country Name maximum length is 33'); } else if (coursename == '') { alert('Please enter your course name'); } else if (!letters.test(coursename)) { alert('Course Name field required only alphabet characters'); } else if (document.getElementById("name").value.length < 3) { alert('Course Name minimum length is 6'); } else if (document.getElementById("coursename").value.length > 40) { alert('Course Name maximum length is 40') } else { alert('Thank You for Registratione'); } } ``` ```css body { font-family: Arial; } input[type=text], textarea, input[type=date] { width: 96%; padding: 12px 20px; margin: 8px 0; } select { width: 99%; padding: 12px 20px; margin: 8px 0; } input[type=submit], input[type=reset] { width: 100%; background-color: grey; color: white; padding: 14px 20px; margin: 8px 0; } ``` ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <h3>STUDENT REGISTRATION FORM</h3> <form name="registration"> Applicant Name:<input type="text" name="name" id="name" placeholder="Enter your Full Name"><br> Email id:<input type="text" name="email" id="email" placeholder="Enter your email id"><br> Mobile Number:<input type="text" name="mobile" id="mobile" placeholder="Enter your mobile number"><br> Address: <textarea name="address" id="address" cols="35" rows="4"></textarea><br> Pin Code<input type="text" name="pincode" id="pincode" placeholder="Enter the pincode"><br> State: <br><input type="text" name="state" id="state" placeholder="Enter the state name"><br> Country: <input type="text" name="country" id="country" placeholder="Enter the name of residing country"><br> Course Name:<input type="text" name="coursename" id="coursename" placeholder="Enter the course name"> <!-- <input type="submit" name="submit" value="Submit" onclick="formValidation()" /> --> <button type="button" onClick="formValidation()">Submit</button> </form> </body> </html> ```
45,035,758
I read the question [Combine multiple rows into one row MySQL](https://stackoverflow.com/questions/21118809/combine-multiple-rows-into-one-row-mysql) that shows how to make out of several rows of a *SELECT* statement a result with a single line. The [SQL Fiddle with Demo](http://sqlfiddle.com/#!2/37c03/2) also runs fine. In that question, there are two tables: *t1* and *t2*. My problem has three tables, which I have simplified for this question: Table *languages*: ``` ID INT(11) NOT NULL PRIMARY_KEY name VARCHAR(255) NOT NULL UNIQUE ``` Table *languages\_have\_persons*: ``` Languages_ID INT(11) NOT NULL PRIMARY_KEY Persons_ID INT(11) NOT NULL ``` Table *persons*: ``` ID INT(11) NOT NULL PRIMARY_KEY firstName VARCHAR(255) NOT NULL lastName VARCHAR(255) NOT NULL ``` What I want to do is to combine these tables similarly, but I fail to do so for several hours now. Here is my last try: ``` SELECT p1.ID , p1.firstName , p1.lastName CONCAT_WS(', ' , l2de.name , l2en.name ) FROM languages_have_persons AS lp, persons AS p1 LEFT JOIN languages AS l2de ON l2de.ID = 4 -- German LEFT JOIN languages AS l2en ON l2en.ID = 5 -- English WHERE p1.ID = lp.Persons_ID ORDER BY lastName, firstName; ``` The error message reads: ``` Fehler SQL-Befehl: Dokumentation SELECT p1.ID AS ID , p1.firstName AS firstName , p1.lastName AS lastName CONCAT_WS(', ' , l2de.name , l2en.name ) FROM languages_have_persons AS lp, persons AS p1 LEFT JOIN languages AS l2de ON l2de.ID = 4 LEFT JOIN languages AS l2en ON l2en.ID = 5 WHERE p1.ID = lp.Persons_ID ORDER BY lastName, firstName LIMIT 0, 25 MySQL meldet: Dokumentation #1064 - Fehler in der SQL-Syntax. Bitte die korrekte Syntax im Handbuch nachschlagen bei '(', ' , l2de.name , l2en.name ) FROM languages_have_persons AS lp, ' in Zeile 4 ``` I also tried other ways, but none had the correct syntax. What I want as result is as follows: Table *language*: ``` ID name 4 German 5 English ``` Table *language\_have\_persons*: ``` Languages_ID Persons_ID 4 2 5 1 5 2 ``` Table *persons*: ``` ID firstName lastName 1 Joe Frazier 2 Arnold Schwarzenegger ``` What I expect from the correct SELECT statement is something like ``` firstName lastName CONCAT_WS(… Joe Frazier English Arnold Schwarzenegger German, English ``` Do you see the error in the SQL syntax above? If not, do you know how to solve it? Thank you for your help!
2017/07/11
[ "https://Stackoverflow.com/questions/45035758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/265140/" ]
``` SELECT p1.ID , p1.firstName , p1.lastName,<--------------------I had made change at this line CONCAT_WS(', ' , l2de.name , l2en.name ) FROM languages_have_persons AS lp, persons AS p1 LEFT JOIN languages AS l2de ON l2de.ID = 4 -- German LEFT JOIN languages AS l2en ON l2en.ID = 5 -- English WHERE p1.ID = lp.Persons_ID ORDER BY lastName, firstName; ``` Or, for your further query you can try below. ``` SELECT p1.ID , p1.firstName , p1.lastName, l2de.name FROM persons p1 INNER JOIN languages_have_persons lp on p1.ID=lp.Persons_ID INNER JOIN language l2de on l2de.ID=lp.Languages_ID WHERE l2de.ID IN(4,5) ORDER BY lastName, firstName; ``` You can try above query.
On another site, I had another discussion, where the colleague found the solution, which is ``` SELECT DISTINCT pl.ID , firstName , lastName , languages FROM persons p , ( SELECT lp.Persons_ID AS ID, GROUP_CONCAT(DISTINCT l.name) AS languages FROM languages l , languages_have_persons lp WHERE l.id = lp.Languages_ID GROUP BY lp.Persons_ID ) AS pl WHERE p.id = pl.id ORDER BY p.id; ``` So, the question is ANSWERED PROPERLY.
17,455,702
I am trying to upload an excel sheet and save it as text file and then read from that text file. One of my friends implemented like this in his application and it is working fine. I just copied his code but it did not work with me properly. It saved the excel sheet as a text file but when I opened the text file, I found the data corrupted and a lot of Unicode or strange symbols with many unnecessary lines such as: > > > ``` > ; þÿÿÿ þÿÿÿ : > > ``` > > ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ > > > **ASP.NET code:** ``` <asp:FileUpload ID="Upload" runat="server" /> <asp:Button ID="btn_upload" runat="server" Text="Upload" OnClick="UploadButton_Click" /> <asp:Label ID="Label1" runat="server" /> ``` **C# code:** ``` protected void UploadButton_Click(object sender, EventArgs e) { if (Upload.HasFile) { try { Upload.SaveAs(Server.MapPath("~/Files/Test_" + DateTime.Now.Year + "_" + DateTime.Now.Month + ".txt")); LabelUpload.Text = "Upload File Name: " + Upload.PostedFile.FileName + "<br>" + "Type: " + Upload.PostedFile.ContentType + " File Size: " + Upload.PostedFile.ContentLength + " kb<br>"; string filename = Server.MapPath("~/Files/Test_" + DateTime.Now.Year + "_" + DateTime.Now.Month + ".txt"); if (System.IO.File.Exists(filename)) { LabelUpload.Text = LabelUpload.Text + "Uploaded Successfully"; } } catch (Exception ex) { Label1.Text = "Error: " + ex.Message.ToString(); } } else { LabelUpload.Text = "Please select a file to upload."; } } ``` I am using ASP.NET 4 with C#, so **could you please tell me what I should to be able to save the Excel sheet as a txt file and then read from it?**
2013/07/03
[ "https://Stackoverflow.com/questions/17455702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2190102/" ]
In order for an Excel file to be readable in a text editor, it has to be converted to the CSV file format. This is because .xlsx Excel documents (2007+) are complex XML hierarchies. If you are curious to see what really makes up a .xlsx file, change its extension to .zip, then unzip it. Therefore, you will not be able to simply change the extension of a .xlsx file to .txt or .csv and expect it to be readable in a text editor. You have to save the file in such a format form the start. In Excel, save the spreadsheet as .csv rather than .xlsx, and you can then open it up into a text editor right away! You can even change the extension to .txt if you really want to. None of that will work thought, if you don't tell Excel to save itself as plain text rather than as its normal XML structure. If you are insistent upon supporting .xlsx files, there is a way. The Office XML File format is an open and public format, allowing you to manipulate it however you like. You will need to: 1. [Download The Open XML SDK](http://www.microsoft.com/en-us/download/details.aspx?id=30425) 2. [Carefully read the documentation](http://msdn.microsoft.com/en-us/library/bb739834.aspx) In your case, you are probably going to want to access specific cell values, read their contents, then stream them into a new file. The above documentation provides the following code snippet for accessing Cell values in an Excel document: ``` public static string XLGetCellValue(string fileName, string sheetName, string addressName) { const string worksheetSchema = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; const string sharedStringSchema = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; string cellValue = null; // Retrieve the stream containing the requested // worksheet's info. using (SpreadsheetDocument xlDoc = SpreadsheetDocument.Open(fileName, false)) { // Get the main document part (workbook.xml). XmlDocument doc = new XmlDocument(); doc.Load(xlDoc.WorkbookPart.GetStream()); // Create a namespace manager, so you can search. // Add a prefix (d) for the default namespace. NameTable nt = new NameTable(); XmlNamespaceManager nsManager = new XmlNamespaceManager(nt); nsManager.AddNamespace("d", worksheetSchema); nsManager.AddNamespace("s", sharedStringSchema); string searchString = string.Format("//d:sheet[@name='{0}']", sheetName); XmlNode sheetNode = doc.SelectSingleNode(searchString, nsManager); if (sheetNode != null) { // Get the relId attribute. XmlAttribute relationAttribute = sheetNode.Attributes["r:id"]; if (relationAttribute != null) { string relId = relationAttribute.Value; // Load the contents of the workbook. XmlDocument sheetDoc = new XmlDocument(nt); sheetDoc.Load(xlDoc.WorkbookPart.GetPartById(relId).GetStream()); XmlNode cellNode = sheetDoc.SelectSingleNode(string.Format("//d:sheetData/d:row/d:c[@r='{0}']", addressName), nsManager); if (cellNode != null) { XmlAttribute typeAttr = cellNode.Attributes["t"]; string cellType = string.Empty; if (typeAttr != null) { cellType = typeAttr.Value; } XmlNode valueNode = cellNode.SelectSingleNode("d:v", nsManager); if (valueNode != null) { cellValue = valueNode.InnerText; } if (cellType == "b") { if (cellValue == "1") { cellValue = "TRUE"; } else { cellValue = "FALSE"; } } else if (cellType == "s") { if (xlDoc.WorkbookPart.SharedStringTablePart != null) { XmlDocument stringDoc = new XmlDocument(nt); stringDoc.Load(xlDoc.WorkbookPart.SharedStringTablePart.GetStream()); // Add the string schema to the namespace manager. nsManager.AddNamespace("s", sharedStringSchema); int requestedString = Convert.ToInt32(cellValue); string strSearch = string.Format("//s:sst/s:si[{0}]", requestedString + 1); XmlNode stringNode = stringDoc.SelectSingleNode(strSearch, nsManager); if (stringNode != null) { cellValue = stringNode.InnerText; } } } } } } } return cellValue; } ``` From there, you can do whatever you like with the cell values =)
You can not save Excel file in text format, You need to use `.csv` extension instead of using xlsx, or xls, and save it as `.txt`.
32,995,079
I have defined a base style for my application with the following element: ``` <item name="android:windowBackground">@color/window_background</item> ``` Which has set the background color for all my activities fine until I tested my app on Android 6 where all backgrounds are white. The backgrounds are still color/window\_background on devices running pre-marshmallow. Anyone know how to make this work (or why it is not working) on Android 6? Edit with some more info: I am targeting API 22, I have not changed anything from previous version or upgraded the API, just running on Android 6 changes the background.
2015/10/07
[ "https://Stackoverflow.com/questions/32995079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1321642/" ]
I haven't found anything specific for Marshmallow that would cause this. So the suggestions I have are: Changing the background color resource to a drawable shape resource. From: ``` <item name="android:windowBackground">@color/window_background</item> ``` To: ``` <item name="android:windowBackground">@drawable/window_background</item> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@color/window_background"/> </shape> ``` In case you haven't checked the opacity of all your views: > > Make sure your windowBackground actually is the background of most of > your Activity (particularly over scrollable sections where overdraw > is the most important to avoid), removing opaque view backgrounds > where possible. > > > [Make your windowBackground work for you instead of using null](https://plus.google.com/+AndroidDevelopers/posts/AqH8s8byq66) I thought this was interesting, to see the precedence of how background layers are set. I am not sure if you are setting any view backgrounds or how you have set up your app, but this is worth a read. > > Backgrounds consist of several layers, from back to front: > > > * the background Drawable of the theme > * a solid color (set via setColor(int)) > * two Drawables, previous and current (set via setBitmap(Bitmap) or setDrawable(Drawable)), which may be in transition > > > [BackgroundManager](https://developer.android.com/reference/android/support/v17/leanback/app/BackgroundManager.html) I can't find if there is a difference with the themes in Marshmallow, or the order of elements, it seems there has been no fundamental changes and I can find no bug for this. *I hope this helps, let me know and I can have another look.* If this doesn't help it may be worth posting some more code relevant to the problem. Cheers.
I used to have a same problem, but I found out by trying that if I commented `actionBarTheme` in my styles, it started to work suddenly. I dug deeper in my styles and found out that the style of action bar was setting a `android:background` attribute after commenting it out everything works now as expected.
32,995,079
I have defined a base style for my application with the following element: ``` <item name="android:windowBackground">@color/window_background</item> ``` Which has set the background color for all my activities fine until I tested my app on Android 6 where all backgrounds are white. The backgrounds are still color/window\_background on devices running pre-marshmallow. Anyone know how to make this work (or why it is not working) on Android 6? Edit with some more info: I am targeting API 22, I have not changed anything from previous version or upgraded the API, just running on Android 6 changes the background.
2015/10/07
[ "https://Stackoverflow.com/questions/32995079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1321642/" ]
I haven't found anything specific for Marshmallow that would cause this. So the suggestions I have are: Changing the background color resource to a drawable shape resource. From: ``` <item name="android:windowBackground">@color/window_background</item> ``` To: ``` <item name="android:windowBackground">@drawable/window_background</item> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@color/window_background"/> </shape> ``` In case you haven't checked the opacity of all your views: > > Make sure your windowBackground actually is the background of most of > your Activity (particularly over scrollable sections where overdraw > is the most important to avoid), removing opaque view backgrounds > where possible. > > > [Make your windowBackground work for you instead of using null](https://plus.google.com/+AndroidDevelopers/posts/AqH8s8byq66) I thought this was interesting, to see the precedence of how background layers are set. I am not sure if you are setting any view backgrounds or how you have set up your app, but this is worth a read. > > Backgrounds consist of several layers, from back to front: > > > * the background Drawable of the theme > * a solid color (set via setColor(int)) > * two Drawables, previous and current (set via setBitmap(Bitmap) or setDrawable(Drawable)), which may be in transition > > > [BackgroundManager](https://developer.android.com/reference/android/support/v17/leanback/app/BackgroundManager.html) I can't find if there is a difference with the themes in Marshmallow, or the order of elements, it seems there has been no fundamental changes and I can find no bug for this. *I hope this helps, let me know and I can have another look.* If this doesn't help it may be worth posting some more code relevant to the problem. Cheers.
If you're using Android Studio 1.4 or higher go to styles where your theme is located and click "Open Editor" in the upper right hand corner. Then change your window background there. It should be under "android:colorBackground"
32,995,079
I have defined a base style for my application with the following element: ``` <item name="android:windowBackground">@color/window_background</item> ``` Which has set the background color for all my activities fine until I tested my app on Android 6 where all backgrounds are white. The backgrounds are still color/window\_background on devices running pre-marshmallow. Anyone know how to make this work (or why it is not working) on Android 6? Edit with some more info: I am targeting API 22, I have not changed anything from previous version or upgraded the API, just running on Android 6 changes the background.
2015/10/07
[ "https://Stackoverflow.com/questions/32995079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1321642/" ]
I haven't found anything specific for Marshmallow that would cause this. So the suggestions I have are: Changing the background color resource to a drawable shape resource. From: ``` <item name="android:windowBackground">@color/window_background</item> ``` To: ``` <item name="android:windowBackground">@drawable/window_background</item> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@color/window_background"/> </shape> ``` In case you haven't checked the opacity of all your views: > > Make sure your windowBackground actually is the background of most of > your Activity (particularly over scrollable sections where overdraw > is the most important to avoid), removing opaque view backgrounds > where possible. > > > [Make your windowBackground work for you instead of using null](https://plus.google.com/+AndroidDevelopers/posts/AqH8s8byq66) I thought this was interesting, to see the precedence of how background layers are set. I am not sure if you are setting any view backgrounds or how you have set up your app, but this is worth a read. > > Backgrounds consist of several layers, from back to front: > > > * the background Drawable of the theme > * a solid color (set via setColor(int)) > * two Drawables, previous and current (set via setBitmap(Bitmap) or setDrawable(Drawable)), which may be in transition > > > [BackgroundManager](https://developer.android.com/reference/android/support/v17/leanback/app/BackgroundManager.html) I can't find if there is a difference with the themes in Marshmallow, or the order of elements, it seems there has been no fundamental changes and I can find no bug for this. *I hope this helps, let me know and I can have another look.* If this doesn't help it may be worth posting some more code relevant to the problem. Cheers.
How about setting both `windowBackground` and `colorBackground` ``` <item name="android:windowBackground">@color/window_background</item> <item name="android:colorBackground">@color/window_background</item> ```
32,995,079
I have defined a base style for my application with the following element: ``` <item name="android:windowBackground">@color/window_background</item> ``` Which has set the background color for all my activities fine until I tested my app on Android 6 where all backgrounds are white. The backgrounds are still color/window\_background on devices running pre-marshmallow. Anyone know how to make this work (or why it is not working) on Android 6? Edit with some more info: I am targeting API 22, I have not changed anything from previous version or upgraded the API, just running on Android 6 changes the background.
2015/10/07
[ "https://Stackoverflow.com/questions/32995079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1321642/" ]
I used to have a same problem, but I found out by trying that if I commented `actionBarTheme` in my styles, it started to work suddenly. I dug deeper in my styles and found out that the style of action bar was setting a `android:background` attribute after commenting it out everything works now as expected.
If you're using Android Studio 1.4 or higher go to styles where your theme is located and click "Open Editor" in the upper right hand corner. Then change your window background there. It should be under "android:colorBackground"
32,995,079
I have defined a base style for my application with the following element: ``` <item name="android:windowBackground">@color/window_background</item> ``` Which has set the background color for all my activities fine until I tested my app on Android 6 where all backgrounds are white. The backgrounds are still color/window\_background on devices running pre-marshmallow. Anyone know how to make this work (or why it is not working) on Android 6? Edit with some more info: I am targeting API 22, I have not changed anything from previous version or upgraded the API, just running on Android 6 changes the background.
2015/10/07
[ "https://Stackoverflow.com/questions/32995079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1321642/" ]
I used to have a same problem, but I found out by trying that if I commented `actionBarTheme` in my styles, it started to work suddenly. I dug deeper in my styles and found out that the style of action bar was setting a `android:background` attribute after commenting it out everything works now as expected.
How about setting both `windowBackground` and `colorBackground` ``` <item name="android:windowBackground">@color/window_background</item> <item name="android:colorBackground">@color/window_background</item> ```
69,168,470
I have been tasked with writing an XSLT script to convert data from one file into a new format. My XSLT knowledge is very limited so I'm hoping I can get some help here. I need to copy the text inside the quotes of the `exhibit path=` line of the text below: ``` <unit> <chapter> <exhibit path="chapter001/t01_reader00.html"/> </chapter> <chapter> <exhibit path="chapter001/chapter01_reader01.html"/> <exhibit path="chapter001/chapter01_reader02.html"/> </chapter> </unit> ``` And have it output to the new file into the `href=` field so it appears like it does below: ``` <item href="chapter001/chapter01_reader01.html" /> <item href="chapter001/chapter01_reader02.html" /> ``` This is what I've tried but I know it's way off. ``` <?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <package xmlns="http://www.idpf.org/2007/opf" unique-identifier="pub-id" version="3.0"> <manifest> <xsl:template match="/"> <item> <xsl:copy-of select="//chapter" /> </item> </xsl:template> </manifest> </package> </xsl:stylesheet> ``` Any help would be most appreciated!
2021/09/13
[ "https://Stackoverflow.com/questions/69168470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16901831/" ]
You could do it simply like this : ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" indent="yes" /> <xsl:template match="/"> <xsl:apply-templates select="//exhibit"/> </xsl:template> <xsl:template match="exhibit"> <item href="{@path}"/> </xsl:template> </xsl:stylesheet> ``` See it working here : <https://xsltfiddle.liberty-development.net/gVAkJ4Z>
You can try this XSLT-1.0 code: ``` <?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.idpf.org/2007/opf"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:template match="/"> <xsl:element name="package" namespace-uri="http://www.idpf.org/2007/opf"> <xsl:attribute name="unique-identifier">pub-id</xsl:attribute> <xsl:attribute name="version">3.0</xsl:attribute> <manifest> <xsl:apply-templates select="//exhibit" /> </manifest> </xsl:element> </xsl:template> <xsl:template match="exhibit"> <xsl:element name="item"> <xsl:attribute name="href"> <xsl:value-of select="@path" /> </xsl:attribute> </xsl:element>" </xsl:template> </xsl:stylesheet> ``` Its output is ``` <?xml version="1.0" encoding="UTF-8"?> <package xmlns="http://www.idpf.org/2007/opf" unique-identifier="pub-id" version="3.0"> <manifest> <item href="chapter001/t01_reader00.html"/>" <item href="chapter001/chapter01_reader01.html"/>" <item href="chapter001/chapter01_reader02.html"/>" </manifest> </package> ``` Notice, that all elements are in the default namespace "http://www.idpf.org/2007/opf".
15,114,998
I am trying to check if a record exists using javascript (I know is not the safest way to do it) but all of this is for internal use and safety is not an issue. So I opened a recordset, ``` rs.Open("SELECT * FROM clie Where N_CLIENT =" + textbox1+ " AND C_POST_CLIENT = '" + textbox2+ "'",connection) ``` `textbox1` and `textbox2` are the values I am looking into the clie table, but first I need to check if the record exists. I tried assigning that `rs.Open` to a variable and then compare it with something but it did not work I tried using a `RecordCount` but I kept getting -1. I read it was not intended for that, and that it should not be used for looking for records so there has to be another way to do this. UPDATE *\_* Here is the whole function I am working on ``` function RecordExists(textfield1, textfield2) { var connection = new ActiveXObject("ADODB.Connection") ; var connectionstring = "UID=admin;PWD=password"; connection.Open(connectionstring); var rs = new ActiveXObject("ADODB.Recordset"); var textbox1= new String(); var textbox2=new String(); textbox1= document.getElementById(textfield1).value; textbox2= document.getElementById(textfield2).value; var isEmpty=new String(); rs.Open("SELECT count(*) as pers FROM clie HAVING N_CLIENT =" + textbox1+ " AND C_POST_CLIE = '" + textbox2+ "'",connection); alert(rs.recordcount); //alert(rs.fields(1)); //isEmpty = rs.Open("pers"); alert("Empty"+isEmpty); if(pers=0) alert("Record does not exist! pers="+pers); else if(pers=1) alert("Record exists! pers="+pers); else alert("not working"); rs.close; connection.close; } } ```
2013/02/27
[ "https://Stackoverflow.com/questions/15114998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373515/" ]
Try this: ``` rs.Open("SELECT count(1) as pers FROM clie Where N_CLIENT =" + textbox1+ " AND C_POST_CLIENT = '" + textbox2+ "'",connection) ``` You retrieve the pers field in this way: ``` perCounts = rs.('pers') ``` or ``` perCounts = rs.("pers") ``` Then if perCounts = 0 then user no exist....if 1 then user exist in your DB. \_\_*\_*\_\_\_\_*EDIT****\_*\_\_*\_*\_\_*\_*\_\_*\_*\_\_*\_*\_\_\_** ``` function RecordExists(textfield1, textfield2) { var connection = new ActiveXObject("ADODB.Connection") ; var connectionstring = "UID=admin;PWD=password"; connection.Open(connectionstring); var rs = new ActiveXObject("ADODB.Recordset"); var textbox1= new String(); var textbox2=new String(); textbox1= document.getElementById(textfield1).value; textbox2= document.getElementById(textfield2).value; var isEmpty=new String(); rs.Open("SELECT count(*) as pers FROM clie HAVING N_CLIENT =" + textbox1+ " AND C_POST_CLIE = '" + textbox2+ "'",connection); alert(rs.recordcount); rs.MoveFirst(); perCounts = rs.Fields(0).Value; if(perCounts=0) alert("Record does not exist! pers="+pers); else if(perCounts=1) alert("Record exists! pers="+pers); else alert("not working"); rs.close; connection.close; } } ``` Saludos.
You should use the count method instead > > rs.Open("SELECT count(\*) FROM clie Where N\_CLIENT =" + textbox1+ " AND > C\_POST\_CLIENT = '" + textbox2+ "'",connection) > > > This will return the number of results > > 0 = 0 Clients 1 = 1 Client 2 = 2 Clients . . . > > >
108,183
Let $k$ be a field. It is well-known that $A\otimes\_{k}B$ is not necessarily Noetherian even if $k$-algebras $A$ and $B$ are Noetherian. For example $\mathbb{R}\otimes\_{\mathbb{Q}}\mathbb{R}$. 1. When is the tensor $A\otimes\_{k}B$ Noetherian for Noetherian "commutative" $k$-algebras $A$ and $B$? 2. What if $A$ is noncommutative? Are there any good criteria for $A\otimes\_{k}B$ to be Noetherian? If $B$ is a finitely generated $k$-algebra, Hilbert's basis theorem implies that $A\otimes\_{k}B$ is again Noetherian. So we need to check this with quite nasty $B$. My primary motivation to ask these questions is the second question. Such ring $A$ is called a "strongly Noethrian ring" and has a lot of good properties, but I don't know many examples. Moreover I realized that things are not very clear even in commutative case and I need to understand commutative case first. I would appreciate it if experts on MO could let me know good criteria for this property and provide me with examples. Rings I have in my mind are weakly noncommutative in the sense that they are commutative up to scalar multiplication such as quantum planes and their $good$ hypersurfaces.
2012/09/26
[ "https://mathoverflow.net/questions/108183", "https://mathoverflow.net", "https://mathoverflow.net/users/50973/" ]
You could try having a look at Yekutieli and Zhang's paper Homological Transcendence Degree (<http://arxiv.org/abs/math/04120130>). They call a $k$-algebra $A$ "doubly Noetherian" if $A \otimes\_k A^{op}$ is Noetherian, and "rationally Noetherian" if $A \otimes\_k U$ is Noetherian for every division ring $U$. There's a lot of other stuff in the paper too, but the first couple of sections look at several conditions for when rings (usually simple Artinian or division) are doubly or rationally noetherian, and there's a nice example of a field in section 7 which is not doubly noetherian. It's not quite what you asked (it certainly won't help with the $q$-plane, but maybe the $q$-torus or the $q$-division ring?) but it might help with intuition and provide some examples.
Try looking at section 4 of "Generic flatness for strongly noetherian algebras" by Artin, Small and Zhang. In fact, they work with a stronger property called universally noetherian (UN); this just means that you no longer require $B$ above to be commutative, merely noetherian. It turns out that most times when your ring is strongly noetherian it is possible to show it is universally noetherian too. In particular some nice results they prove are: * [Propn 4.1] UN is preserved when taking Ore extensions, finite module extensions, localisations by denominator sets. * [Propn 4.13] Certain twisted homogeneous coordinate rings have UN. * [Propn. 4.24] Connected graded noetherian domains of GK dimension 2 are UN (alg. closed field hypothesis). There are several other results in this section and indeed the whole paper is very nice and worth reading. **EDIT (by Nazih Nahlus)**: In this very nice paper (Thanks to Andrew), you also find that: * [Prop. 4.1] (c) UN is also preserved under almost normalizing extensions. * [Prop. 4.10] Suppose A is an N-filtered R-algebra. If the associated graded ring gr(A) is universally right noetherian, then so is A. * [Cor. 4.11] Weyl algebras and universal enveloping algebras of finite-dimensional Lie algebras are universally noetherian. I think one should rather say universally noetherian R-algebra (because we are tensoring over R).
108,183
Let $k$ be a field. It is well-known that $A\otimes\_{k}B$ is not necessarily Noetherian even if $k$-algebras $A$ and $B$ are Noetherian. For example $\mathbb{R}\otimes\_{\mathbb{Q}}\mathbb{R}$. 1. When is the tensor $A\otimes\_{k}B$ Noetherian for Noetherian "commutative" $k$-algebras $A$ and $B$? 2. What if $A$ is noncommutative? Are there any good criteria for $A\otimes\_{k}B$ to be Noetherian? If $B$ is a finitely generated $k$-algebra, Hilbert's basis theorem implies that $A\otimes\_{k}B$ is again Noetherian. So we need to check this with quite nasty $B$. My primary motivation to ask these questions is the second question. Such ring $A$ is called a "strongly Noethrian ring" and has a lot of good properties, but I don't know many examples. Moreover I realized that things are not very clear even in commutative case and I need to understand commutative case first. I would appreciate it if experts on MO could let me know good criteria for this property and provide me with examples. Rings I have in my mind are weakly noncommutative in the sense that they are commutative up to scalar multiplication such as quantum planes and their $good$ hypersurfaces.
2012/09/26
[ "https://mathoverflow.net/questions/108183", "https://mathoverflow.net", "https://mathoverflow.net/users/50973/" ]
You could try having a look at Yekutieli and Zhang's paper Homological Transcendence Degree (<http://arxiv.org/abs/math/04120130>). They call a $k$-algebra $A$ "doubly Noetherian" if $A \otimes\_k A^{op}$ is Noetherian, and "rationally Noetherian" if $A \otimes\_k U$ is Noetherian for every division ring $U$. There's a lot of other stuff in the paper too, but the first couple of sections look at several conditions for when rings (usually simple Artinian or division) are doubly or rationally noetherian, and there's a nice example of a field in section 7 which is not doubly noetherian. It's not quite what you asked (it certainly won't help with the $q$-plane, but maybe the $q$-torus or the $q$-division ring?) but it might help with intuition and provide some examples.
Since we have a natural identification $$ A/I\otimes\_{k} B \cong (A\otimes\_{k}B)/(I\otimes\_{k}B), $$ any quotients of UN rings Andrew mentioned are again UN.
108,183
Let $k$ be a field. It is well-known that $A\otimes\_{k}B$ is not necessarily Noetherian even if $k$-algebras $A$ and $B$ are Noetherian. For example $\mathbb{R}\otimes\_{\mathbb{Q}}\mathbb{R}$. 1. When is the tensor $A\otimes\_{k}B$ Noetherian for Noetherian "commutative" $k$-algebras $A$ and $B$? 2. What if $A$ is noncommutative? Are there any good criteria for $A\otimes\_{k}B$ to be Noetherian? If $B$ is a finitely generated $k$-algebra, Hilbert's basis theorem implies that $A\otimes\_{k}B$ is again Noetherian. So we need to check this with quite nasty $B$. My primary motivation to ask these questions is the second question. Such ring $A$ is called a "strongly Noethrian ring" and has a lot of good properties, but I don't know many examples. Moreover I realized that things are not very clear even in commutative case and I need to understand commutative case first. I would appreciate it if experts on MO could let me know good criteria for this property and provide me with examples. Rings I have in my mind are weakly noncommutative in the sense that they are commutative up to scalar multiplication such as quantum planes and their $good$ hypersurfaces.
2012/09/26
[ "https://mathoverflow.net/questions/108183", "https://mathoverflow.net", "https://mathoverflow.net/users/50973/" ]
You could try having a look at Yekutieli and Zhang's paper Homological Transcendence Degree (<http://arxiv.org/abs/math/04120130>). They call a $k$-algebra $A$ "doubly Noetherian" if $A \otimes\_k A^{op}$ is Noetherian, and "rationally Noetherian" if $A \otimes\_k U$ is Noetherian for every division ring $U$. There's a lot of other stuff in the paper too, but the first couple of sections look at several conditions for when rings (usually simple Artinian or division) are doubly or rationally noetherian, and there's a nice example of a field in section 7 which is not doubly noetherian. It's not quite what you asked (it certainly won't help with the $q$-plane, but maybe the $q$-torus or the $q$-division ring?) but it might help with intuition and provide some examples.
Although the OP is mainly interested in noncommutative results and examples, let me say a few words about the commutative case. Let $k\subset K$ be a field extension. N. Bourbaki in *Algebre. Chapitre 8, Modules et anneaux semi-simples* (edition 1958), exercise 22, page 99, gives the following criterion: if the extension $k\subset K$ is algebraic, then $K\otimes\_kK$ is Noetherian iff $[K:k]<\infty$. Later on, in 1978, P. Vamos in the paper *On the minimal prime ideals of a tensor product of two fields* proves a more general result: for a field extension $k\subset K$, $K\otimes\_kK$ is Noetherian iff $k\subset K$ is finitely generated. Inspired by Vamos' result, Resco, Small and Wadsworth in the paper *Tensor products of division rings and finite generation of subfields* prove a (partially) noncommutative result: let $D$ be a division algebra over a field $k$ and $k\subset K$ a commutative subfield of $D$. Then $D\otimes\_kL$ is Noetherian iff the extension $k\subset K$ is finitely generated. As a by-product they get that $D\otimes\_kD^0$ Noetherian implies $k\subset K$ finitely generated for every commutative subfield $K$ of $D$ containing $k$.
108,183
Let $k$ be a field. It is well-known that $A\otimes\_{k}B$ is not necessarily Noetherian even if $k$-algebras $A$ and $B$ are Noetherian. For example $\mathbb{R}\otimes\_{\mathbb{Q}}\mathbb{R}$. 1. When is the tensor $A\otimes\_{k}B$ Noetherian for Noetherian "commutative" $k$-algebras $A$ and $B$? 2. What if $A$ is noncommutative? Are there any good criteria for $A\otimes\_{k}B$ to be Noetherian? If $B$ is a finitely generated $k$-algebra, Hilbert's basis theorem implies that $A\otimes\_{k}B$ is again Noetherian. So we need to check this with quite nasty $B$. My primary motivation to ask these questions is the second question. Such ring $A$ is called a "strongly Noethrian ring" and has a lot of good properties, but I don't know many examples. Moreover I realized that things are not very clear even in commutative case and I need to understand commutative case first. I would appreciate it if experts on MO could let me know good criteria for this property and provide me with examples. Rings I have in my mind are weakly noncommutative in the sense that they are commutative up to scalar multiplication such as quantum planes and their $good$ hypersurfaces.
2012/09/26
[ "https://mathoverflow.net/questions/108183", "https://mathoverflow.net", "https://mathoverflow.net/users/50973/" ]
Try looking at section 4 of "Generic flatness for strongly noetherian algebras" by Artin, Small and Zhang. In fact, they work with a stronger property called universally noetherian (UN); this just means that you no longer require $B$ above to be commutative, merely noetherian. It turns out that most times when your ring is strongly noetherian it is possible to show it is universally noetherian too. In particular some nice results they prove are: * [Propn 4.1] UN is preserved when taking Ore extensions, finite module extensions, localisations by denominator sets. * [Propn 4.13] Certain twisted homogeneous coordinate rings have UN. * [Propn. 4.24] Connected graded noetherian domains of GK dimension 2 are UN (alg. closed field hypothesis). There are several other results in this section and indeed the whole paper is very nice and worth reading. **EDIT (by Nazih Nahlus)**: In this very nice paper (Thanks to Andrew), you also find that: * [Prop. 4.1] (c) UN is also preserved under almost normalizing extensions. * [Prop. 4.10] Suppose A is an N-filtered R-algebra. If the associated graded ring gr(A) is universally right noetherian, then so is A. * [Cor. 4.11] Weyl algebras and universal enveloping algebras of finite-dimensional Lie algebras are universally noetherian. I think one should rather say universally noetherian R-algebra (because we are tensoring over R).
Although the OP is mainly interested in noncommutative results and examples, let me say a few words about the commutative case. Let $k\subset K$ be a field extension. N. Bourbaki in *Algebre. Chapitre 8, Modules et anneaux semi-simples* (edition 1958), exercise 22, page 99, gives the following criterion: if the extension $k\subset K$ is algebraic, then $K\otimes\_kK$ is Noetherian iff $[K:k]<\infty$. Later on, in 1978, P. Vamos in the paper *On the minimal prime ideals of a tensor product of two fields* proves a more general result: for a field extension $k\subset K$, $K\otimes\_kK$ is Noetherian iff $k\subset K$ is finitely generated. Inspired by Vamos' result, Resco, Small and Wadsworth in the paper *Tensor products of division rings and finite generation of subfields* prove a (partially) noncommutative result: let $D$ be a division algebra over a field $k$ and $k\subset K$ a commutative subfield of $D$. Then $D\otimes\_kL$ is Noetherian iff the extension $k\subset K$ is finitely generated. As a by-product they get that $D\otimes\_kD^0$ Noetherian implies $k\subset K$ finitely generated for every commutative subfield $K$ of $D$ containing $k$.
108,183
Let $k$ be a field. It is well-known that $A\otimes\_{k}B$ is not necessarily Noetherian even if $k$-algebras $A$ and $B$ are Noetherian. For example $\mathbb{R}\otimes\_{\mathbb{Q}}\mathbb{R}$. 1. When is the tensor $A\otimes\_{k}B$ Noetherian for Noetherian "commutative" $k$-algebras $A$ and $B$? 2. What if $A$ is noncommutative? Are there any good criteria for $A\otimes\_{k}B$ to be Noetherian? If $B$ is a finitely generated $k$-algebra, Hilbert's basis theorem implies that $A\otimes\_{k}B$ is again Noetherian. So we need to check this with quite nasty $B$. My primary motivation to ask these questions is the second question. Such ring $A$ is called a "strongly Noethrian ring" and has a lot of good properties, but I don't know many examples. Moreover I realized that things are not very clear even in commutative case and I need to understand commutative case first. I would appreciate it if experts on MO could let me know good criteria for this property and provide me with examples. Rings I have in my mind are weakly noncommutative in the sense that they are commutative up to scalar multiplication such as quantum planes and their $good$ hypersurfaces.
2012/09/26
[ "https://mathoverflow.net/questions/108183", "https://mathoverflow.net", "https://mathoverflow.net/users/50973/" ]
Since we have a natural identification $$ A/I\otimes\_{k} B \cong (A\otimes\_{k}B)/(I\otimes\_{k}B), $$ any quotients of UN rings Andrew mentioned are again UN.
Although the OP is mainly interested in noncommutative results and examples, let me say a few words about the commutative case. Let $k\subset K$ be a field extension. N. Bourbaki in *Algebre. Chapitre 8, Modules et anneaux semi-simples* (edition 1958), exercise 22, page 99, gives the following criterion: if the extension $k\subset K$ is algebraic, then $K\otimes\_kK$ is Noetherian iff $[K:k]<\infty$. Later on, in 1978, P. Vamos in the paper *On the minimal prime ideals of a tensor product of two fields* proves a more general result: for a field extension $k\subset K$, $K\otimes\_kK$ is Noetherian iff $k\subset K$ is finitely generated. Inspired by Vamos' result, Resco, Small and Wadsworth in the paper *Tensor products of division rings and finite generation of subfields* prove a (partially) noncommutative result: let $D$ be a division algebra over a field $k$ and $k\subset K$ a commutative subfield of $D$. Then $D\otimes\_kL$ is Noetherian iff the extension $k\subset K$ is finitely generated. As a by-product they get that $D\otimes\_kD^0$ Noetherian implies $k\subset K$ finitely generated for every commutative subfield $K$ of $D$ containing $k$.
40,905,160
I am trying to make a chemistry calculator where I can put in the elements letters, like "H", "He", "O", etc, so I have made an array called elements. Then I have made an array with the values. I want for the letters. Is there any way to make it that if I write `element[x]` it would use the `value[x]`? ``` var element:Array = new Array("H", "O") var mass:Array = new Array(1.01, 16.01); function elements() { if (input_Mm.text == element[0]) { Mm = mass[0]; } if (input_Mm.text == element[1]) { Mm = mass[1]; } } ``` So, I don't have to write one if statement for each and every possible element.
2016/12/01
[ "https://Stackoverflow.com/questions/40905160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7234872/" ]
You could use a loop to loop through your element array, then take the index found to look up the mass array. A better option may be to use a dictionary object to do a direct lookup, which might be better in this case. You can think of dictionaries as being similar to arrays, but with strings as the key instead of an index number. In both cases, you may also want to filter bad input if "input\_Mm" is a user editable field.
The Mendeleiev table contains 103 elements, so You may use a fixed Vector to store de datas... Just to make it simple... ``` var mendeleievElmnt:Vector.<String> = new Vector.<String>(103,true); var mendeleievMass:Vector.<Number> = new Vector.<Number>(103,true); // 103 elements... So a fixed Vector. :) function populateMeElmnts():void{ mendeleievElmnt[0] = "H"; mendeleievElmnt[1] = "He"; mendeleievElmnt[2] = "Li"; mendeleievElmnt[3] = "Be"; //... } function populateMeMass():void{ mendeleievMass[0] = 1; mendeleievMass[1] = 4; mendeleievMass[2] = 6.9; mendeleievMass[3] = 9; //... // O is 16 and not 16.1 but I'm old school ;) } populateMeElmnts() populateMeMass() function getElement(el:uint):String{ return ("element[" + (el+1) + "] = " + mendeleievElmnt[el] + ", mass = " + mendeleievMass[el]); } trace(getElement(2)); //OR function returnElement(el:uint):Object{ var o:Object = new Object() o["elm"]= mendeleievElmnt[el]; o["elMass"]= mendeleievMass[el]; o["elIndex"]= el+1; return o; } var elmt:Object = returnElement(2); trace("index = " + elmt["elIndex"] + ", elm= " + elmt["elm"] + ", elmtMass = " + elmt["elMass"]); ``` Output: ``` // element[3] = Li, mass = 6.9 // index = 3, elm= Li, elmtMass = 6.9 ``` The Vector Class is really more efficient but I don't know if You expect to fill all those data dynamically... In this example, You have to populate the 103 Elements and their Mm in the two functions. Do You want to fill those data via a database dynamically??? Anyway I strongly suggest You to avoid Objects or Arrays... There's a lot of possibilities, so this is unclear to me... Sorry if the answer is not accurate so. 1° : Why do you want to get an object in place of get an index of a Vector? 2° : What's the project must look like? The answer of @GeorgeProfenza looks perfect in your case and gives You the opportunity to work in different directions. Best regards. Nicolas
40,905,160
I am trying to make a chemistry calculator where I can put in the elements letters, like "H", "He", "O", etc, so I have made an array called elements. Then I have made an array with the values. I want for the letters. Is there any way to make it that if I write `element[x]` it would use the `value[x]`? ``` var element:Array = new Array("H", "O") var mass:Array = new Array(1.01, 16.01); function elements() { if (input_Mm.text == element[0]) { Mm = mass[0]; } if (input_Mm.text == element[1]) { Mm = mass[1]; } } ``` So, I don't have to write one if statement for each and every possible element.
2016/12/01
[ "https://Stackoverflow.com/questions/40905160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7234872/" ]
You could use a loop to loop through your element array, then take the index found to look up the mass array. A better option may be to use a dictionary object to do a direct lookup, which might be better in this case. You can think of dictionaries as being similar to arrays, but with strings as the key instead of an index number. In both cases, you may also want to filter bad input if "input\_Mm" is a user editable field.
There multiple ways to do this. The `Object` approach payam sbr suggest is pretty straight forward. To add to the existing answers: you could write a class to represent a chemical object value object(VO) (e.g. store it's name, notation, mass, etc.): ``` package { public class Element { private var _name:String; private var _notation:String; private var _mass:Number; public function Element(name:String,notation:String,mass:Number) { _name = name; _notation = notation; _mass = mass; } public function getName():String{ return _name; } public function setName(newName:String):void{ _name = newName; } public function getNotation():String{ return _notation; } public function setNotation(newNotation:String):void{ _notation = newNotation; } public function getMass():Number{ return _mass; } public function setMass(newMass:Number):void{ _mass = newMass; } public function toString():String{ return "[Element name="+_name+" notation="+_notation+" mass="+_mass+"]"; } } } ``` You could then create a one dimensional array of Elements and access the data each Element stores: ``` var elements:Vector.<Element> = new Vector.<Element>(); elements.push(new Element("Hydrogen","H",1.01)); elements.push(new Element("Oxygen","O",16.01)); var totalMass:Number = 0; for(var i:int = 0; i < elements.length; i++){ trace("elements[",i,"]",elements[i]); totalMass += elements[i].getMass(); } trace("total mass",totalMass); ``` Outputs: ``` elements[ 0 ] [Element name=Hydrogen notation=H mass=1.01] elements[ 1 ] [Element name=Oxygen notation=O mass=16.01] total mass 17.020000000000003 ``` Note that a typed Vector will be faster than an untyped `Array` of `Object` instances. Additionally as3.0 getters/setters can be a bit slow to, hence the code java style get / set methods. If you don't plan to go though a HUGE amount of elements and performance doesn't have to be as tight as possible you can use the typical as3 getter/setters that behave like properties (if this is more readable/easier to understand): ``` package { public class Element { private var _name:String; private var _notation:String; private var _mass:Number; public function Element(name:String,notation:String,mass:Number) { _name = name; _notation = notation; _mass = mass; } public function get name():String{ return _name; } public function set name(newName:String):void{ _name = newName; } public function get notation():String{ return _notation; } public function set notation(newNotation:String):void{ _notation = newNotation; } public function get mass():Number{ return _mass; } public function set mass(newMass:Number):void{ _mass = newMass; } public function toString():String{ return "[Element name="+_name+" notation="+_notation+" mass="+_mass+"]"; } } } ``` test code: ``` var elements:Vector.<Element> = new Vector.<Element>(); elements.push(new Element("Hydrogen","H",1.01)); elements.push(new Element("Oxygen","O",16.01)); var totalMass:Number = 0; for(var i:int = 0; i < elements.length; i++){ trace("elements[",i,"]",elements[i]); totalMass += elements[i].mass; } trace("total mass",totalMass); ``` If you use a class versus `Object` you'll also get auto-complete. If you want an option closer to the `Object` approach with less code for a quick prototype, you can probably get away with public properties: ``` package { public class Element { public var name:String; public var notation:String; public var mass:Number; public function Element(name:String,notation:String,mass:Number) { this.name = name; this.notation = notation; this.mass = mass; } public function toString():String{ return "[Element name="+name+" notation="+notation+" mass="+mass+"]"; } } } ```
40,905,160
I am trying to make a chemistry calculator where I can put in the elements letters, like "H", "He", "O", etc, so I have made an array called elements. Then I have made an array with the values. I want for the letters. Is there any way to make it that if I write `element[x]` it would use the `value[x]`? ``` var element:Array = new Array("H", "O") var mass:Array = new Array(1.01, 16.01); function elements() { if (input_Mm.text == element[0]) { Mm = mass[0]; } if (input_Mm.text == element[1]) { Mm = mass[1]; } } ``` So, I don't have to write one if statement for each and every possible element.
2016/12/01
[ "https://Stackoverflow.com/questions/40905160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7234872/" ]
use object ``` var element_mass:Object = { H: 1.01, O: 16.01 } function elements() { if(element_mass.hasOwnProperty(input_Mm.text)) Mm = element_mass[input_Mm.text]; } ```
The Mendeleiev table contains 103 elements, so You may use a fixed Vector to store de datas... Just to make it simple... ``` var mendeleievElmnt:Vector.<String> = new Vector.<String>(103,true); var mendeleievMass:Vector.<Number> = new Vector.<Number>(103,true); // 103 elements... So a fixed Vector. :) function populateMeElmnts():void{ mendeleievElmnt[0] = "H"; mendeleievElmnt[1] = "He"; mendeleievElmnt[2] = "Li"; mendeleievElmnt[3] = "Be"; //... } function populateMeMass():void{ mendeleievMass[0] = 1; mendeleievMass[1] = 4; mendeleievMass[2] = 6.9; mendeleievMass[3] = 9; //... // O is 16 and not 16.1 but I'm old school ;) } populateMeElmnts() populateMeMass() function getElement(el:uint):String{ return ("element[" + (el+1) + "] = " + mendeleievElmnt[el] + ", mass = " + mendeleievMass[el]); } trace(getElement(2)); //OR function returnElement(el:uint):Object{ var o:Object = new Object() o["elm"]= mendeleievElmnt[el]; o["elMass"]= mendeleievMass[el]; o["elIndex"]= el+1; return o; } var elmt:Object = returnElement(2); trace("index = " + elmt["elIndex"] + ", elm= " + elmt["elm"] + ", elmtMass = " + elmt["elMass"]); ``` Output: ``` // element[3] = Li, mass = 6.9 // index = 3, elm= Li, elmtMass = 6.9 ``` The Vector Class is really more efficient but I don't know if You expect to fill all those data dynamically... In this example, You have to populate the 103 Elements and their Mm in the two functions. Do You want to fill those data via a database dynamically??? Anyway I strongly suggest You to avoid Objects or Arrays... There's a lot of possibilities, so this is unclear to me... Sorry if the answer is not accurate so. 1° : Why do you want to get an object in place of get an index of a Vector? 2° : What's the project must look like? The answer of @GeorgeProfenza looks perfect in your case and gives You the opportunity to work in different directions. Best regards. Nicolas
40,905,160
I am trying to make a chemistry calculator where I can put in the elements letters, like "H", "He", "O", etc, so I have made an array called elements. Then I have made an array with the values. I want for the letters. Is there any way to make it that if I write `element[x]` it would use the `value[x]`? ``` var element:Array = new Array("H", "O") var mass:Array = new Array(1.01, 16.01); function elements() { if (input_Mm.text == element[0]) { Mm = mass[0]; } if (input_Mm.text == element[1]) { Mm = mass[1]; } } ``` So, I don't have to write one if statement for each and every possible element.
2016/12/01
[ "https://Stackoverflow.com/questions/40905160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7234872/" ]
use object ``` var element_mass:Object = { H: 1.01, O: 16.01 } function elements() { if(element_mass.hasOwnProperty(input_Mm.text)) Mm = element_mass[input_Mm.text]; } ```
There multiple ways to do this. The `Object` approach payam sbr suggest is pretty straight forward. To add to the existing answers: you could write a class to represent a chemical object value object(VO) (e.g. store it's name, notation, mass, etc.): ``` package { public class Element { private var _name:String; private var _notation:String; private var _mass:Number; public function Element(name:String,notation:String,mass:Number) { _name = name; _notation = notation; _mass = mass; } public function getName():String{ return _name; } public function setName(newName:String):void{ _name = newName; } public function getNotation():String{ return _notation; } public function setNotation(newNotation:String):void{ _notation = newNotation; } public function getMass():Number{ return _mass; } public function setMass(newMass:Number):void{ _mass = newMass; } public function toString():String{ return "[Element name="+_name+" notation="+_notation+" mass="+_mass+"]"; } } } ``` You could then create a one dimensional array of Elements and access the data each Element stores: ``` var elements:Vector.<Element> = new Vector.<Element>(); elements.push(new Element("Hydrogen","H",1.01)); elements.push(new Element("Oxygen","O",16.01)); var totalMass:Number = 0; for(var i:int = 0; i < elements.length; i++){ trace("elements[",i,"]",elements[i]); totalMass += elements[i].getMass(); } trace("total mass",totalMass); ``` Outputs: ``` elements[ 0 ] [Element name=Hydrogen notation=H mass=1.01] elements[ 1 ] [Element name=Oxygen notation=O mass=16.01] total mass 17.020000000000003 ``` Note that a typed Vector will be faster than an untyped `Array` of `Object` instances. Additionally as3.0 getters/setters can be a bit slow to, hence the code java style get / set methods. If you don't plan to go though a HUGE amount of elements and performance doesn't have to be as tight as possible you can use the typical as3 getter/setters that behave like properties (if this is more readable/easier to understand): ``` package { public class Element { private var _name:String; private var _notation:String; private var _mass:Number; public function Element(name:String,notation:String,mass:Number) { _name = name; _notation = notation; _mass = mass; } public function get name():String{ return _name; } public function set name(newName:String):void{ _name = newName; } public function get notation():String{ return _notation; } public function set notation(newNotation:String):void{ _notation = newNotation; } public function get mass():Number{ return _mass; } public function set mass(newMass:Number):void{ _mass = newMass; } public function toString():String{ return "[Element name="+_name+" notation="+_notation+" mass="+_mass+"]"; } } } ``` test code: ``` var elements:Vector.<Element> = new Vector.<Element>(); elements.push(new Element("Hydrogen","H",1.01)); elements.push(new Element("Oxygen","O",16.01)); var totalMass:Number = 0; for(var i:int = 0; i < elements.length; i++){ trace("elements[",i,"]",elements[i]); totalMass += elements[i].mass; } trace("total mass",totalMass); ``` If you use a class versus `Object` you'll also get auto-complete. If you want an option closer to the `Object` approach with less code for a quick prototype, you can probably get away with public properties: ``` package { public class Element { public var name:String; public var notation:String; public var mass:Number; public function Element(name:String,notation:String,mass:Number) { this.name = name; this.notation = notation; this.mass = mass; } public function toString():String{ return "[Element name="+name+" notation="+notation+" mass="+mass+"]"; } } } ```
2,895,141
(i) Find the prime factorisation of $6500$, and of $1120$. What is the typical way to go about this? Just using common divisibility rules? That's what I did. I'm not sure if there's a more structured way that I should be doing this, since it could be more difficult depending on the number? The above seem to be easy cases. $65 \times 100 = 6500$ $13 \times 5 \times 25 \times 4 = 6500$ $13 \times 5 \times 5^2 \times 2^2 = 6500$ $13 \times 5^3 \times 2^2 = 6500$ $1120 = 112 \times 10$ $= 66 \times 2 \times 5 \times 2$ $= 6 \times 11 \times 2^2 \times 5$ $= 3 \times 11 \times 2^3 \times 5$ (ii) Hence write down, in factorised form, $gcd(6500, 1120)$ and $lcm(6500, 1120)$. For GCD we just selected the highest powers of the numbers that are common to both? So it would be $\gcd(6500, 1120) = 5^3 \times 13 \times 2^3$? And I think for LCM we take the lowest powers of each number? So it would be $\operatorname{lcm}(6500, 1120) = 5 \times 2^2$? Thanks for any help.
2018/08/26
[ "https://math.stackexchange.com/questions/2895141", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
By assumption, the differentiable function $h(x) := g(x) - f(x)$ has a minimum point at $a$. Since $a$ is an interior point, then $h'(a) = 0$, i.e. $f'(a) = g'(a)$.
Fundamentally, the intuition here is that if two curves touch each other ($f(a)=g(a)$) and have different derivatives at that point, then one has to actually *cross* the other. If we are to have $f\leq g$ on the entire interval, then the only way those two curves can touch is if they just "kiss", tangent to each other, and then separate again without actually crossing. For example, if $f'(a)>g'(a)$, then $f$ is steeper than $g$ at $a$. Therefore, "obviously", at the point $a$, $f$ is cutting up across the curve of $g$ from below, and we will end up with $f(a+h)>g(a)$ for sufficiently small $h$. Now, the question is, how do we turn this visual intuition into a mathematical proof. There are many ways. One is to just look at the definition of the derivative directly. For sufficiently small $h$, we will have: $$\frac{f(a+h)-f(a)}{h}>\frac{g(a+h)-g(a)}{h}$$ This is true because it's true in the limit $h\to 0$, which means it has to be true for sufficiently small $h$. In detail: if we call the left hand side $A(h)$ and the right hand side $B(h)$, we have $\lim\_{h\to 0} A(h)>\lim\_{h\to 0} B(h)$, and you can prove from the definition of a limit that this implies $A(h)>B(h)$ for sufficiently small $h$. Anyway, going back to the inequality, we can cancel out $f(a)$ and $g(a)$ since they're equal to one another and we can multiply both sides by $h$ to get, for sufficiently small $h$: $$f(a+h)>g(a+h)$$ Which proves exactly what we said: because $f$ is steeper than $g$ at the point $a$, $f$ will be higher than $g$ immediately after $a$. The case $f'(a)<g'(a)$ can be handled in a similar way.
2,895,141
(i) Find the prime factorisation of $6500$, and of $1120$. What is the typical way to go about this? Just using common divisibility rules? That's what I did. I'm not sure if there's a more structured way that I should be doing this, since it could be more difficult depending on the number? The above seem to be easy cases. $65 \times 100 = 6500$ $13 \times 5 \times 25 \times 4 = 6500$ $13 \times 5 \times 5^2 \times 2^2 = 6500$ $13 \times 5^3 \times 2^2 = 6500$ $1120 = 112 \times 10$ $= 66 \times 2 \times 5 \times 2$ $= 6 \times 11 \times 2^2 \times 5$ $= 3 \times 11 \times 2^3 \times 5$ (ii) Hence write down, in factorised form, $gcd(6500, 1120)$ and $lcm(6500, 1120)$. For GCD we just selected the highest powers of the numbers that are common to both? So it would be $\gcd(6500, 1120) = 5^3 \times 13 \times 2^3$? And I think for LCM we take the lowest powers of each number? So it would be $\operatorname{lcm}(6500, 1120) = 5 \times 2^2$? Thanks for any help.
2018/08/26
[ "https://math.stackexchange.com/questions/2895141", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Proof ===== I will give a proof for the problem as follows, which totally depends on some most basic facts of calculus. According to the assumptions, $$\frac{f(x)-f(a)}{x-a}\leq \frac{g(x)-g(a)}{x-a},\tag1$$where $x$ belongs to some right neighborhood of $a.$ And$$\frac{f(x)-f(a)}{x-a}\geq \frac{g(x)-g(a)}{x-a},\tag2$$where $x$ belongs to some left neighborhood of $a.$Thus, for $(1)$, let $x \to a+.$ $$\lim\_{x \to a+}\frac{f(x)-f(a)}{x-a}\leq \lim\_{x \to a+}\frac{g(x)-g(a)}{x-a},\tag 3$$which implies $$f'\_+(a) \leq g'\_+(a).\tag4$$Likewise, for $(2)$, let $x \to a-.$ $$\lim\_{x \to a-}\frac{f(x)-f(a)}{x-a}\geq \lim\_{x \to a-}\frac{g(x)-g(a)}{x-a},\tag 5$$which implies $$f'\_-(a) \geq g'\_-(a).\tag6$$ But by the definition of the differentiability, we have $$f'(a)=f'\_+(a)=f'\_-(a),~~~~~g'(a)=g'\_+(a)=g'\_-(a).\tag7$$ Thus, $(4)$ and $(5)$ claim that $$f'(a) \leq g'(a),~~~~~f'(a) \geq g'(a)\tag8$$respectively, which demands $$f'(a)=g'(a).$$
Fundamentally, the intuition here is that if two curves touch each other ($f(a)=g(a)$) and have different derivatives at that point, then one has to actually *cross* the other. If we are to have $f\leq g$ on the entire interval, then the only way those two curves can touch is if they just "kiss", tangent to each other, and then separate again without actually crossing. For example, if $f'(a)>g'(a)$, then $f$ is steeper than $g$ at $a$. Therefore, "obviously", at the point $a$, $f$ is cutting up across the curve of $g$ from below, and we will end up with $f(a+h)>g(a)$ for sufficiently small $h$. Now, the question is, how do we turn this visual intuition into a mathematical proof. There are many ways. One is to just look at the definition of the derivative directly. For sufficiently small $h$, we will have: $$\frac{f(a+h)-f(a)}{h}>\frac{g(a+h)-g(a)}{h}$$ This is true because it's true in the limit $h\to 0$, which means it has to be true for sufficiently small $h$. In detail: if we call the left hand side $A(h)$ and the right hand side $B(h)$, we have $\lim\_{h\to 0} A(h)>\lim\_{h\to 0} B(h)$, and you can prove from the definition of a limit that this implies $A(h)>B(h)$ for sufficiently small $h$. Anyway, going back to the inequality, we can cancel out $f(a)$ and $g(a)$ since they're equal to one another and we can multiply both sides by $h$ to get, for sufficiently small $h$: $$f(a+h)>g(a+h)$$ Which proves exactly what we said: because $f$ is steeper than $g$ at the point $a$, $f$ will be higher than $g$ immediately after $a$. The case $f'(a)<g'(a)$ can be handled in a similar way.
7,874
I'm designing a microcontroller based device which spends most of the time in deep sleep. Every 10 seconds it wakes up, reads a potentiometer connected on an ADC line then goes back to sleep. My aim is to achieve a long battery life. How should I wire the potentiometer up to the microcontroller in order to minimise power use? For my first attempt, I wired a 1K pot to 3V3 and GND with the wiper attached to the ADC. No matter what resistance is set on the pot, this seems to consume 3-5mA continuously. Should one or more of the pot pins be connected to GPIOs and driven only when needed? If so, should the pins be driven low or tristated when not in use?
2010/12/14
[ "https://electronics.stackexchange.com/questions/7874", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/566/" ]
Your 1k pot is causing most of your quiescent (standby/off-state) current: I=V/R, and you've got 3-5mA and 3.3V/1000 = 3.3mA. You can either connect one side to a GPIO pin and drive it only when needed (as you suggested) and/or use a larger pot. Be careful when using very large pots (1M and higher), as the input impedance of your A/D pin might cause a slight variation in the voltage you read. This may or may not be significant for your project. I'd compromise by using a 100k pot and connecting one side of the pot straight to ground, and the other to the source of a P-channel MOSFET. Connect the center to your A/D pin, and the MOSFET gate to the microcontroller. That way, you can allow the microcontroller's weak internal pull-up resistor to bring it to 3V3, and dissipate minimal power. An additional power savings might be to add a constant voltage divider to your circuit (and an additional A/D line), and run straight from the batteries, eliminating the voltage regulator and its quiescent current requirements. Also, you might want to run the numbers and see what kinds of battery life you get with quicker pulses. Even if you slow your microcontroller down to 100kHz or so, you can probably take an A/D reading in a millisecond. Ten seconds between pulses gives you a duty cycle of 0.01%, which isn't that different from 0.1% or 0.3% for many applications. I'd speed it up to take a reading every 300ms or so to avoid having users resetting and otherwise fiddling with the device when it doesn't respond instantly. On second thought, I'm assuming a human is turning the pot, which may not be the case.
Instead of connecting the high end of the potmeter to +3V3 you could connect it to an I/O pin. Before going in sleep mode set the pin to input, so that there's no current running through the potmeter. (The resistor keeps both the high end and the wiper at ground.) When the uC wakes up set the I/O pin to output and set it to high level. Though 1K may not be a problem -- you'll draw 3.3mA from the output pin -- I suggest you take at least a 10K potmeter.
7,874
I'm designing a microcontroller based device which spends most of the time in deep sleep. Every 10 seconds it wakes up, reads a potentiometer connected on an ADC line then goes back to sleep. My aim is to achieve a long battery life. How should I wire the potentiometer up to the microcontroller in order to minimise power use? For my first attempt, I wired a 1K pot to 3V3 and GND with the wiper attached to the ADC. No matter what resistance is set on the pot, this seems to consume 3-5mA continuously. Should one or more of the pot pins be connected to GPIOs and driven only when needed? If so, should the pins be driven low or tristated when not in use?
2010/12/14
[ "https://electronics.stackexchange.com/questions/7874", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/566/" ]
I would suggest wiring both ends of the pot to port pins that can be configured not to burn quiescent current while sitting at half-rail (many processors have pins that can be configured to be either digital outputs or analog inputs) and float both ends of the pot while not taking readings. Connect the midpoint of the pot to an ADC input, with a significant-value cap to ground. If you have multiple pots and can't afford to use three processor pins for each one, you could e.g. use external chips to connect and disconnect the ends of the pots. Note that the ends of the various pots should not be tied together; when a pot is disconnected, it should not connect to anything else. If you do things this way, the ADC input voltage, with its cap to ground, should remain roughly constant when the pot is connected and disconnected. When powering up the cap, take readings repeatedly until either they stabilize or it becomes clear they won't (because they go up and down, rather than asymptotically approaching some value). If there isn't too much leakage in the circuit, you shouldn't have to have the pot powered up very long if it isn't being moved, since the cap should start out at, and remain at, the proper voltage.
Your 1k pot is causing most of your quiescent (standby/off-state) current: I=V/R, and you've got 3-5mA and 3.3V/1000 = 3.3mA. You can either connect one side to a GPIO pin and drive it only when needed (as you suggested) and/or use a larger pot. Be careful when using very large pots (1M and higher), as the input impedance of your A/D pin might cause a slight variation in the voltage you read. This may or may not be significant for your project. I'd compromise by using a 100k pot and connecting one side of the pot straight to ground, and the other to the source of a P-channel MOSFET. Connect the center to your A/D pin, and the MOSFET gate to the microcontroller. That way, you can allow the microcontroller's weak internal pull-up resistor to bring it to 3V3, and dissipate minimal power. An additional power savings might be to add a constant voltage divider to your circuit (and an additional A/D line), and run straight from the batteries, eliminating the voltage regulator and its quiescent current requirements. Also, you might want to run the numbers and see what kinds of battery life you get with quicker pulses. Even if you slow your microcontroller down to 100kHz or so, you can probably take an A/D reading in a millisecond. Ten seconds between pulses gives you a duty cycle of 0.01%, which isn't that different from 0.1% or 0.3% for many applications. I'd speed it up to take a reading every 300ms or so to avoid having users resetting and otherwise fiddling with the device when it doesn't respond instantly. On second thought, I'm assuming a human is turning the pot, which may not be the case.
7,874
I'm designing a microcontroller based device which spends most of the time in deep sleep. Every 10 seconds it wakes up, reads a potentiometer connected on an ADC line then goes back to sleep. My aim is to achieve a long battery life. How should I wire the potentiometer up to the microcontroller in order to minimise power use? For my first attempt, I wired a 1K pot to 3V3 and GND with the wiper attached to the ADC. No matter what resistance is set on the pot, this seems to consume 3-5mA continuously. Should one or more of the pot pins be connected to GPIOs and driven only when needed? If so, should the pins be driven low or tristated when not in use?
2010/12/14
[ "https://electronics.stackexchange.com/questions/7874", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/566/" ]
I would suggest wiring both ends of the pot to port pins that can be configured not to burn quiescent current while sitting at half-rail (many processors have pins that can be configured to be either digital outputs or analog inputs) and float both ends of the pot while not taking readings. Connect the midpoint of the pot to an ADC input, with a significant-value cap to ground. If you have multiple pots and can't afford to use three processor pins for each one, you could e.g. use external chips to connect and disconnect the ends of the pots. Note that the ends of the various pots should not be tied together; when a pot is disconnected, it should not connect to anything else. If you do things this way, the ADC input voltage, with its cap to ground, should remain roughly constant when the pot is connected and disconnected. When powering up the cap, take readings repeatedly until either they stabilize or it becomes clear they won't (because they go up and down, rather than asymptotically approaching some value). If there isn't too much leakage in the circuit, you shouldn't have to have the pot powered up very long if it isn't being moved, since the cap should start out at, and remain at, the proper voltage.
Instead of connecting the high end of the potmeter to +3V3 you could connect it to an I/O pin. Before going in sleep mode set the pin to input, so that there's no current running through the potmeter. (The resistor keeps both the high end and the wiper at ground.) When the uC wakes up set the I/O pin to output and set it to high level. Though 1K may not be a problem -- you'll draw 3.3mA from the output pin -- I suggest you take at least a 10K potmeter.
426,795
I have lots of problems with my Lenovo G470 after there was a water spill accident 3 months ago which caused half my keyboard to be damaged. 1. Recently the screen flickers or there will be totally no screen on boot. 2. There is one instant that after many tries, I got the screen to work but there is no network detected. But I know my wireless network works and that my computer's wireless is turned on. Anyone can help with this? Is it worth it to get it repair? I don't think that water spills are covered by the warranty: can they detect it?
2012/05/20
[ "https://superuser.com/questions/426795", "https://superuser.com", "https://superuser.com/users/135289/" ]
You will need console access (i.e. be ON the physical server) to reset the password, if you don't have any other passwords available. Is this server connected to an AD server? If so reset the password on the domain controller. If it is only using local usernames and passwords, try something such as the UBCD4Win CD to reset the password. The way that passwords are stored for users of a Windows system, you can not "recover" or "view" the password in clear text, only hashed form. Because of the vast possibilities that could create that password, you're better off clearing the password, and setting a new one
Try using `net user password` command detailed here; <http://support.microsoft.com/kb/251394> This may allow you to at least change the password from the command prompt