qid
int64 1
74.7M
| question
stringlengths 17
39.2k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
41.1k
| response_k
stringlengths 2
47.9k
|
---|---|---|---|---|---|
626,330 | I have an [eMachines T5246](http://www.cnet.com/products/emachines-t5246/specs/) running Ubuntu 14.04 LTS set up as a home media server with Plex.
Everything has been running well (if slowly) up until today when I installed the updates that showed up in the auto-update and restarted.
When I next booted it up, the screen was completely blank until I moved the mouse, at which point the pointer appeared. I have rebooted several times, and a few times the login screen and wallpaper has appeared, and after logging in, the wallpaper disappeared when I clicked onscreen.
I can boot to other devices. I booted to tails on a usb to see if I could access the files, but I don't remember the Admin password, so I couldn't access the files.
I think that when I first installed ubuntu, the computer had some graphics driver issues, but I believe that was from ubuntu automatically using 3rd party drivers.
What can I do?
UPDATE 1: I have not been able to fix the problem, but I can access the terminal from the login screen using CTRL+ALT+F1
UPDATE 2: I have tried booting using nomodeset, but I got the same screen and reaction when I booted up. | 2015/05/21 | [
"https://askubuntu.com/questions/626330",
"https://askubuntu.com",
"https://askubuntu.com/users/412200/"
] | Sometimes the package dependencies are related to packages out of x86\_64 architecture. Try these following steps:
1. `sudo dpkg --add-architecture i386`
2. `sudo apt-get update`
3. `sudo apt-get install libgtk2.0-dev`
I hope to help you. | I had the same issue trying to install Wireshark 1.7.0 on my Ubuntu 12.04 - wireshark requires `libgtk2.0-dev`.
Everything is stuck because of the package `libfontconfig1-dev`:
1. Add the precise-updates deb server in your `/etc/apt/sources.list` . For France:
```none
deb http://fr.archive.ubuntu.com/ubuntu/ precise-updates main restricted
```
2. Refresh `aptitude`:
```none
apt-get update
```
4. Now you can install the broken package
```none
apt-get install libfontconfig1-dev
```
5. Put all problematic packages on the same command line. Here:
```none
apt-get install libgtk2.0-dev libpango1.0-dev libcairo2-dev
``` |
626,330 | I have an [eMachines T5246](http://www.cnet.com/products/emachines-t5246/specs/) running Ubuntu 14.04 LTS set up as a home media server with Plex.
Everything has been running well (if slowly) up until today when I installed the updates that showed up in the auto-update and restarted.
When I next booted it up, the screen was completely blank until I moved the mouse, at which point the pointer appeared. I have rebooted several times, and a few times the login screen and wallpaper has appeared, and after logging in, the wallpaper disappeared when I clicked onscreen.
I can boot to other devices. I booted to tails on a usb to see if I could access the files, but I don't remember the Admin password, so I couldn't access the files.
I think that when I first installed ubuntu, the computer had some graphics driver issues, but I believe that was from ubuntu automatically using 3rd party drivers.
What can I do?
UPDATE 1: I have not been able to fix the problem, but I can access the terminal from the login screen using CTRL+ALT+F1
UPDATE 2: I have tried booting using nomodeset, but I got the same screen and reaction when I booted up. | 2015/05/21 | [
"https://askubuntu.com/questions/626330",
"https://askubuntu.com",
"https://askubuntu.com/users/412200/"
] | Sometimes the package dependencies are related to packages out of x86\_64 architecture. Try these following steps:
1. `sudo dpkg --add-architecture i386`
2. `sudo apt-get update`
3. `sudo apt-get install libgtk2.0-dev`
I hope to help you. | Test this:
Download this files to 32 bits:
===============================
```
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-dev_2.24.10-0ubuntu6_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/gir1.2-gtk-2.0_2.24.10-0ubuntu6_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/a/atk1.0/libatk1.0-dev_2.4.0-0ubuntu1_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/c/cairo/libcairo2-dev_1.10.2-6.1ubuntu2_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gdk-pixbuf/libgdk-pixbuf2.0-dev_2.26.1-1_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/glib2.0/libglib2.0-dev_2.32.1-0ubuntu2_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-0_2.24.10-0ubuntu6_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-common_2.24.10-0ubuntu6_all.deb
http://mirrors.kernel.org/ubuntu/pool/main/p/pango1.0/libpango1.0-dev_1.30.0-0ubuntu2_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/libx/libxcomposite/libxcomposite-dev_0.4.3-2build1_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/libx/libxdamage/libxdamage-dev_1.1.3-2build1_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/p/pkg-config/pkg-config_0.26-1ubuntu1_i386.deb
```
Or download this files to 64 bit:
=================================
```
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-dev_2.24.10-0ubuntu6_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/gir1.2-gtk-2.0_2.24.10-0ubuntu6_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/a/atk1.0/libatk1.0-dev_2.4.0-0ubuntu1_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/c/cairo/libcairo2-dev_1.10.2-6.1ubuntu2_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gdk-pixbuf/libgdk-pixbuf2.0-dev_2.26.1-1_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/glib2.0/libglib2.0-dev_2.32.1-0ubuntu2_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-0_2.24.10-0ubuntu6_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-common_2.24.10-0ubuntu6_all.deb
http://mirrors.kernel.org/ubuntu/pool/main/p/pango1.0/libpango1.0-dev_1.30.0-0ubuntu2_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/libx/libxcomposite/libxcomposite-dev_0.4.3-2build1_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/libx/libxdamage/libxdamage-dev_1.1.3-2build1_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/p/pkg-config/pkg-config_0.26-1ubuntu1_amd64.deb
```
Install them with the command:
==============================
```
sudo dpkg --force-all -i *.deb
```
Executed in the download directory |
626,330 | I have an [eMachines T5246](http://www.cnet.com/products/emachines-t5246/specs/) running Ubuntu 14.04 LTS set up as a home media server with Plex.
Everything has been running well (if slowly) up until today when I installed the updates that showed up in the auto-update and restarted.
When I next booted it up, the screen was completely blank until I moved the mouse, at which point the pointer appeared. I have rebooted several times, and a few times the login screen and wallpaper has appeared, and after logging in, the wallpaper disappeared when I clicked onscreen.
I can boot to other devices. I booted to tails on a usb to see if I could access the files, but I don't remember the Admin password, so I couldn't access the files.
I think that when I first installed ubuntu, the computer had some graphics driver issues, but I believe that was from ubuntu automatically using 3rd party drivers.
What can I do?
UPDATE 1: I have not been able to fix the problem, but I can access the terminal from the login screen using CTRL+ALT+F1
UPDATE 2: I have tried booting using nomodeset, but I got the same screen and reaction when I booted up. | 2015/05/21 | [
"https://askubuntu.com/questions/626330",
"https://askubuntu.com",
"https://askubuntu.com/users/412200/"
] | Try installing all of them at the same time, like this:
```
sudo apt-get install libgtk2.0-dev libpango1-dev libcairo2-dev libfontconfig1-dev
``` | I ran into this issue on 16.04 and the reason (for me at least) was that libcairo2-dev required on a specific version of libcairo-gobject2 and I had a newer one:
```
The following packages have unmet dependencies:
libgtk2.0-dev : Depends: libpango1.0-dev (>= 1.20) but it is not going to be installed
Depends: libcairo2-dev (>= 1.6.4-6.1) but it is not going to be installed
```
.
```
The following packages have unmet dependencies:
libcairo2-dev : Depends: libcairo-gobject2 (= 1.14.6-1) but 1.15.2-0intel1 is to be installed
E: Unable to correct problems, you have held broken packages.
```
So the fix was:
```
sudo apt-get install libcairo-gobject2=1.14.6-1
```
Which then allowed me to install libgtk2.0-dev
The real proper fix is for the maintainers of libcairo2-dev/libcairo-gobject2 to properly fix their dependency is that one can use later version of libcairo2-gobject2. |
626,330 | I have an [eMachines T5246](http://www.cnet.com/products/emachines-t5246/specs/) running Ubuntu 14.04 LTS set up as a home media server with Plex.
Everything has been running well (if slowly) up until today when I installed the updates that showed up in the auto-update and restarted.
When I next booted it up, the screen was completely blank until I moved the mouse, at which point the pointer appeared. I have rebooted several times, and a few times the login screen and wallpaper has appeared, and after logging in, the wallpaper disappeared when I clicked onscreen.
I can boot to other devices. I booted to tails on a usb to see if I could access the files, but I don't remember the Admin password, so I couldn't access the files.
I think that when I first installed ubuntu, the computer had some graphics driver issues, but I believe that was from ubuntu automatically using 3rd party drivers.
What can I do?
UPDATE 1: I have not been able to fix the problem, but I can access the terminal from the login screen using CTRL+ALT+F1
UPDATE 2: I have tried booting using nomodeset, but I got the same screen and reaction when I booted up. | 2015/05/21 | [
"https://askubuntu.com/questions/626330",
"https://askubuntu.com",
"https://askubuntu.com/users/412200/"
] | Try installing all of them at the same time, like this:
```
sudo apt-get install libgtk2.0-dev libpango1-dev libcairo2-dev libfontconfig1-dev
``` | Test this:
Download this files to 32 bits:
===============================
```
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-dev_2.24.10-0ubuntu6_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/gir1.2-gtk-2.0_2.24.10-0ubuntu6_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/a/atk1.0/libatk1.0-dev_2.4.0-0ubuntu1_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/c/cairo/libcairo2-dev_1.10.2-6.1ubuntu2_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gdk-pixbuf/libgdk-pixbuf2.0-dev_2.26.1-1_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/glib2.0/libglib2.0-dev_2.32.1-0ubuntu2_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-0_2.24.10-0ubuntu6_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-common_2.24.10-0ubuntu6_all.deb
http://mirrors.kernel.org/ubuntu/pool/main/p/pango1.0/libpango1.0-dev_1.30.0-0ubuntu2_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/libx/libxcomposite/libxcomposite-dev_0.4.3-2build1_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/libx/libxdamage/libxdamage-dev_1.1.3-2build1_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/p/pkg-config/pkg-config_0.26-1ubuntu1_i386.deb
```
Or download this files to 64 bit:
=================================
```
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-dev_2.24.10-0ubuntu6_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/gir1.2-gtk-2.0_2.24.10-0ubuntu6_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/a/atk1.0/libatk1.0-dev_2.4.0-0ubuntu1_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/c/cairo/libcairo2-dev_1.10.2-6.1ubuntu2_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gdk-pixbuf/libgdk-pixbuf2.0-dev_2.26.1-1_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/glib2.0/libglib2.0-dev_2.32.1-0ubuntu2_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-0_2.24.10-0ubuntu6_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-common_2.24.10-0ubuntu6_all.deb
http://mirrors.kernel.org/ubuntu/pool/main/p/pango1.0/libpango1.0-dev_1.30.0-0ubuntu2_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/libx/libxcomposite/libxcomposite-dev_0.4.3-2build1_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/libx/libxdamage/libxdamage-dev_1.1.3-2build1_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/p/pkg-config/pkg-config_0.26-1ubuntu1_amd64.deb
```
Install them with the command:
==============================
```
sudo dpkg --force-all -i *.deb
```
Executed in the download directory |
197,183 | I've seen *Blade Runner* many times but I'm currently reading *Do Androids Dream of Electric Sheep?* for the first time and I find myself wondering something I've never considered before: Why does Deckard need to use the Voight-Kampff test on the remaining escaped androids?
I know he needs to use the test to figure out who is an android and who isn't, but in this case Deckard is given his targets beforehand. And certainly, when an android is asked to take an empathy test, they would know their time is up - it necessarily robs the tester of the element of surprise.
In Chapter 9, Deckard goes to the opera house after Luba Luft.
>
> He reexamined the poop sheet, then leaned back, satisfied. I've now seen my third Nexus-6 android, he realized. This is Luba Luft.
>
>
>
Here, Deckard has the obvious advantage. Luft is unaware that she is being hunted at all. Given he knows that she is an android already, why doesn't he proceed with the next part and ~~kill~~ retire her right away so he can collect the bounty? Why bother with the test? | 2018/10/23 | [
"https://scifi.stackexchange.com/questions/197183",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/106349/"
] | The list that was provided to Deckard was based off "suspicions" as we can see when Bryant tells Deckard:
>
> "Dave used the Voigt-Kampff Altered Scale in testing out the individuals
> he **suspected** ***(Keep in mind that he only managed to test 3 androids, 2 which he retired and Polokov who shot him)***. You realize - you ought to, anyhow - that this test isn't specific for the new brain units.
>
>
>
Further down we confirm it is based off assumptions from the notes of Dave:
>
> Bryant turned the notes around so that
> Rick could see. "Max Polokov," Bryant said. "That's what it calls itself, anyhow. Assuming Dave was
> right. **Everything is based on that assumption, *this entire list.*** And yet the Voigt-Kampff Altered Scale
> has only been administered to the first three, the two Dave retired and then Polokov. It was while
> Dave was administering the test; that's when Polokov lasered him."
> "Which proves that Dave was right," Rick said. Otherwise he would not have been lasered;
> Polokov would have no motive.
>
>
>
So the list only helps Deckard locate the "suspected" androids. Polokov was retired because he exposed himself when he shot at Dave while taking the test. Deckard uses the test to confirm that his target is indeed an android, even though he may suspect it. | The test is fugazi. The test might "work", it might not, but it is certainly far from foolproof. After all, one of the primary themes of the book(and movie) is that androids and humans do not seem to fit any preconceived notions regarding morality or empathy.
Deep down, Deckard knows this. But he needs the test to justify what he is doing. Not simply because he has to believe that they are androids, but so he can pretend they are actually the monsters they are made out to be. |
18,379,350 | I have a `Date`. Now I want to calculate that the age of from that will be 2-12yrs if condition is true otherwise the age should be between 0-2 yrs. So how could we can calculate whether the age lies between 2-12 or 0-2 from a given date.
I have done something but I am confused how could I proceed.
```
public class Test {
public static void main(String args[]) throws ParseException {
String string = "29/07/13";
Date oneWayTripDate = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(string);
String myFormat = "dd/MM/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
}
}
```
Then condition will be some thing like this
```
for child age should be between 2-12 (So from Current Date will calulate to 12 yrs .if the date given lies between 2-12yrs then it is true otherwise false)
for infant age should be between 0-12 (So from Current Date will calulate to 2 yrs .if the date given lies between 0-2yrs then it is true otherwise false)
``` | 2013/08/22 | [
"https://Stackoverflow.com/questions/18379350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2618323/"
] | If you want to find age you need two date values. You can try something like this
```
DateFormat df=new SimpleDateFormat("dd/MM/yy");
Date birthDay=df.parse("29/07/13");
Date currentDay=new Date();
Calendar cal1=Calendar.getInstance();
Calendar cal2=Calendar.getInstance();
cal1.setTime(birthDay);
cal2.setTime(currentDay);
int years=cal2.get(Calendar.YEAR)-cal1.get(Calendar.YEAR);
if(3>years){
System.out.println("Infant");
}else if(years<13){
System.out.println("Child");
} else{
System.out.println("adult");
}
``` | You could use Joda Time [Period](http://joda-time.sourceforge.net/apidocs/org/joda/time/Period.html) ([Docs](http://joda-time.sourceforge.net/key_period.html))
```
Date tripDate;
Date dob;
Period period = new Period(dob, tripDate, PeriodType. YearMonthDay);
int years = period.getYears();
if(years < 3) {
// 0 - 2
} else if(years < 13) {
// 2 - 12
} else {
// adult
}
``` |
43,184,018 | I'm trying to setup SonarQube.com on travis for a maven project, but I see the following exception on build:
```
[INFO] User cache: /home/travis/.sonar/cache
[INFO] Load global settings
[INFO] Load global settings (done) | time=456ms
[INFO] User cache: /home/travis/.sonar/cache
[INFO] Load plugins index
[INFO] Load plugins index (done) | time=16ms
[INFO] Download sonar-scm-cvs-plugin-1.0.jar
[INFO] Download sonar-scm-svn-plugin-1.3.jar
[INFO] Download sonar-plsql-plugin-2.9.0.901.jar
[INFO] Download sonar-csharp-plugin-5.8.0.660.jar
[INFO] Download sonar-java-plugin-4.7.1.9272.jar
[INFO] Download sonar-web-plugin-2.5.0.476.jar
[INFO] Download sonar-flex-plugin-2.3.jar
[INFO] Download sonar-xml-plugin-1.4.2.885.jar
[INFO] Download sonar-vbnet-plugin-3.0.3.346.jar
[INFO] Download sonar-swift-plugin-2.0.0.1127.jar
[INFO] Download sonar-python-plugin-1.7.0.1195.jar
[INFO] Download sonar-github-plugin-1.4.0.699.jar
[INFO] Download sonar-cfamily-plugin-4.6.0.7071.jar
[INFO] Download sonar-auth-github-plugin-1.3.jar
[INFO] Download sonar-rpg-plugin-2.1.0.736.jar
[INFO] Download sonar-scm-mercurial-plugin-1.1.1.jar
[INFO] Download sonar-googleanalytics-plugin-1.1.jar
[INFO] Download sonar-widget-lab-plugin-1.8.1.jar
[INFO] Download sonar-pli-plugin-1.5.0.702.jar
[INFO] Download sonar-javascript-plugin-2.21.0.4409.jar
[INFO] Download sonar-groovy-plugin-1.4.jar
[INFO] Download sonar-cobol-plugin-3.3.1.1636.jar
[INFO] Download sonar-scm-git-plugin-1.2.jar
[INFO] Download sonar-php-plugin-2.10.0.2087.jar
[INFO] Download sonar-abap-plugin-3.3.jar
[INFO] Download sonar-governance-plugin-2.0.0.1789.jar
[INFO] Download qualinsight-sonarqube-badges-3.0.1.jar
[INFO] SonarQube version: 6.3.0
[INFO] Default locale: "en_US", source code encoding: "UTF-8"
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:42 min
[INFO] Finished at: 2017-04-03T09:47:20+00:00
[INFO] Final Memory: 70M/468M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.3.0.603:sonar (default-cli) on project jraft: No license for governance -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
```
Here is the `.travis.yml`:
```
language: java
jdk:
- oraclejdk8
addons:
sonarqube:
organization: ${SONAR_ORGANIZATION}
token:
secure: ${SONAR_TOKEN}
script:
- ./travis.sh
cache:
directories:
- $HOME/.m2/repository
- $HOME/.sonar
- $HOME/jvm
- $HOME/maven
```
Here is the `travis.sh`:
```
#!/bin/bash
set -e
INITIAL_VERSION=1.0-SNAPSHOT
export MAVEN_OPTS="-Xmx1G -Xms128m"
mvn package sonar:sonar \
$MAVEN_ARGS \
-Dsonar.host.url=$SONAR_HOST_URL \
-Dsonar.login=$SONAR_TOKEN \
-Dsonar.projectVersion=$INITIAL_VERSION
```
Why I am seeing this error `No license for governance` as I am not using any commercial sonar component (only sonar-java I suppose)?
The problem seems to be related to the fact that one of the plugins needs a commercial key, but How I can tell Travis to only install the java plugin? | 2017/04/03 | [
"https://Stackoverflow.com/questions/43184018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1269281/"
] | Taking a look at your repository, you should not override the various parameters that the Travis Add-on is specifying for you.
More specifically, when you override `SONAR_TOKEN` on the Maven command line (at [line 12](https://github.com/dzlab/jraft/blob/master/travis.sh#L12)), the consequence is that the token that you have encrypted and passed at [line 11](https://github.com/dzlab/jraft/blob/master/.travis.yml#L11) of your `.travis.yml` file is completely wiped out. Because of this, your analysis is run like if you were anonymous.
So please follow the [Get Started](http://about.sonarqube.com/get-started/) guide and simply run the following Maven command:
```
mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar
``` | sonar-governance plugin is commercial plugin.
check [here](https://www.sonarsource.com/why-us/products/plugins/governance.html)
```
.....
[INFO] Download sonar-governance-plugin-2.0.0.1789.jar
......
``` |
43,184,018 | I'm trying to setup SonarQube.com on travis for a maven project, but I see the following exception on build:
```
[INFO] User cache: /home/travis/.sonar/cache
[INFO] Load global settings
[INFO] Load global settings (done) | time=456ms
[INFO] User cache: /home/travis/.sonar/cache
[INFO] Load plugins index
[INFO] Load plugins index (done) | time=16ms
[INFO] Download sonar-scm-cvs-plugin-1.0.jar
[INFO] Download sonar-scm-svn-plugin-1.3.jar
[INFO] Download sonar-plsql-plugin-2.9.0.901.jar
[INFO] Download sonar-csharp-plugin-5.8.0.660.jar
[INFO] Download sonar-java-plugin-4.7.1.9272.jar
[INFO] Download sonar-web-plugin-2.5.0.476.jar
[INFO] Download sonar-flex-plugin-2.3.jar
[INFO] Download sonar-xml-plugin-1.4.2.885.jar
[INFO] Download sonar-vbnet-plugin-3.0.3.346.jar
[INFO] Download sonar-swift-plugin-2.0.0.1127.jar
[INFO] Download sonar-python-plugin-1.7.0.1195.jar
[INFO] Download sonar-github-plugin-1.4.0.699.jar
[INFO] Download sonar-cfamily-plugin-4.6.0.7071.jar
[INFO] Download sonar-auth-github-plugin-1.3.jar
[INFO] Download sonar-rpg-plugin-2.1.0.736.jar
[INFO] Download sonar-scm-mercurial-plugin-1.1.1.jar
[INFO] Download sonar-googleanalytics-plugin-1.1.jar
[INFO] Download sonar-widget-lab-plugin-1.8.1.jar
[INFO] Download sonar-pli-plugin-1.5.0.702.jar
[INFO] Download sonar-javascript-plugin-2.21.0.4409.jar
[INFO] Download sonar-groovy-plugin-1.4.jar
[INFO] Download sonar-cobol-plugin-3.3.1.1636.jar
[INFO] Download sonar-scm-git-plugin-1.2.jar
[INFO] Download sonar-php-plugin-2.10.0.2087.jar
[INFO] Download sonar-abap-plugin-3.3.jar
[INFO] Download sonar-governance-plugin-2.0.0.1789.jar
[INFO] Download qualinsight-sonarqube-badges-3.0.1.jar
[INFO] SonarQube version: 6.3.0
[INFO] Default locale: "en_US", source code encoding: "UTF-8"
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:42 min
[INFO] Finished at: 2017-04-03T09:47:20+00:00
[INFO] Final Memory: 70M/468M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.3.0.603:sonar (default-cli) on project jraft: No license for governance -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
```
Here is the `.travis.yml`:
```
language: java
jdk:
- oraclejdk8
addons:
sonarqube:
organization: ${SONAR_ORGANIZATION}
token:
secure: ${SONAR_TOKEN}
script:
- ./travis.sh
cache:
directories:
- $HOME/.m2/repository
- $HOME/.sonar
- $HOME/jvm
- $HOME/maven
```
Here is the `travis.sh`:
```
#!/bin/bash
set -e
INITIAL_VERSION=1.0-SNAPSHOT
export MAVEN_OPTS="-Xmx1G -Xms128m"
mvn package sonar:sonar \
$MAVEN_ARGS \
-Dsonar.host.url=$SONAR_HOST_URL \
-Dsonar.login=$SONAR_TOKEN \
-Dsonar.projectVersion=$INITIAL_VERSION
```
Why I am seeing this error `No license for governance` as I am not using any commercial sonar component (only sonar-java I suppose)?
The problem seems to be related to the fact that one of the plugins needs a commercial key, but How I can tell Travis to only install the java plugin? | 2017/04/03 | [
"https://Stackoverflow.com/questions/43184018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1269281/"
] | Taking a look at your repository, you should not override the various parameters that the Travis Add-on is specifying for you.
More specifically, when you override `SONAR_TOKEN` on the Maven command line (at [line 12](https://github.com/dzlab/jraft/blob/master/travis.sh#L12)), the consequence is that the token that you have encrypted and passed at [line 11](https://github.com/dzlab/jraft/blob/master/.travis.yml#L11) of your `.travis.yml` file is completely wiped out. Because of this, your analysis is run like if you were anonymous.
So please follow the [Get Started](http://about.sonarqube.com/get-started/) guide and simply run the following Maven command:
```
mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar
``` | For me the below works from my jenkins pipeline
```
node{
stage 'Code Quality'
sh "mvn sonar:sonar -Dsonar.host.url=http://<hostname>:9000"
}
``` |
1,681,438 | [![enter image description here](https://i.stack.imgur.com/SpLL7.png)](https://i.stack.imgur.com/SpLL7.png)
[![enter image description here](https://i.stack.imgur.com/2aUrA.png)](https://i.stack.imgur.com/2aUrA.png)
How do I calculate the number of hours worked within 24 hours?
If the shift starts at 6 AM and finishes at 2 PM with a half an hour break, and the shift the following day starts at 4 AM and finishes at 12 PM with a half an hour break, how many hours in 24 hours has that person worked, the 24 hour period starts at 6 AM which is the start of the first shift.
My formula doesn't seem to be accurate, I think I may be missing something.
```
=SUM((start break-start shift)+(finish break-finish shift)+(start break second shifts-start second shift)+(finish second shift-finish break second shift))
``` | 2021/10/13 | [
"https://superuser.com/questions/1681438",
"https://superuser.com",
"https://superuser.com/users/1574669/"
] | Assuming that:
1. You aren't interested in knowing if the window timed out
2. You aren't interested in knowing what button the user clicked on
3. You don't mind writing out a temporary VBScript file to generate the popup (and then removing it after)
then use the following:
```
echo WScript.CreateObject("Wscript.Shell").Popup "Line 1" ^& vbCrLf ^& "Line 2", 10, "Title", 262192 > %temp%\File.vbs
wscript %temp%\File.vbs
del /f %temp%\File.vbs
```
This will cause a pop-up to appear which has two lines of content ("Line 1" followed by "Line 2"), the title "Title", an exclamation icon, an OK button and a timeout of 10 seconds.
Further details on how to configure this window can be found in the documentation for the [Popup](https://ss64.com/vb/popup.html) command.
It’s worth noting that you can achieve an exclamation mark and an “OK” button with `48` instead of `262192` (which, technically, isn’t a valid numerical option). | Create a .vbs script that invokes the Windows Script Host popup() method.
That method has a parameter that determines how long the popup message window is shown. Then invoke your script from the command line with "wscript your\_script.vbs".
FYI, there are abundant reports of popup() method timing being erratic, and even failing to timeout at all, especially with larger timeout values. |
62,780,964 | I looked around and while this seems to be a common error I can't really find an answer to what I am doing wrong.
```
const express = require('express')
const expressGraphQL = require('express-graphql')
const app = express()
app.use('/graphql', expressGraphQL({
graphiql: true
}))
app.listen(5000., () => console.log('Server is Running'))
```
Whenever I compile that I get this error...
```
app.use('/graphql', expressGraphQL({
^
TypeError: expressGraphQL is not a function
at Object.<anonymous> (C:\Node\Project_GraphQL\server.js:5:21)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
[nodemon] app crashed - waiting for file changes before starting...
```
I'm trying to follow along with this video here and near as I can tell I have copied it line for line....
<https://youtu.be/ZQL7tL2S0oQ?t=565>
What have I misunderstood and done wrong? | 2020/07/07 | [
"https://Stackoverflow.com/questions/62780964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8857799/"
] | If you use the last version, express-graphql return an object, in this case you should use:
```
const { graphqlHTTP } = require('express-graphql')
```
or in your code
```
app.use('/graphql', expressGraphQL.graphqlHTTP({
graphiql: true
}))
``` | If you see the npm docs [here](https://www.npmjs.com/package/express-graphql). `graphqlHTTP` is the function which is exported form the module (it is using Object [destructring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#:%7E:text=The%20destructuring%20assignment%20syntax%20is,from%20objects%2C%20into%20distinct%20variables.)).
So your Code Should look like below
```
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const app = express();
app.use(
'/graphql',
graphqlHTTP({
graphiql: true,
}),
);
app.listen(5000., () => console.log('Server is Running'))
``` |
13,326 | On this website (<https://www.change.org/p/fran%C3%A7ois-hollande-monsieur-le-pr%C3%A9sident-la-france-doit-voter-%C3%A0-l-onu-l-interdiction-des-armes-nucl%C3%A9aires?tk=LANthiTZ4YhnYia83IpRD3C6fnMkdd6hLRkrojJFCpk&utm_medium=email&utm_source=signature_receipt&utm_campaign=new_signature>)
a button titled "signer la pétition" (sign the petition) is not displayed with TOR.
How can I manage to get this button displayed and sign the petition with Tor?
The button matches with other browsers (IE for example)
Regards
Denis | 2016/12/07 | [
"https://tor.stackexchange.com/questions/13326",
"https://tor.stackexchange.com",
"https://tor.stackexchange.com/users/15344/"
] | The site seems broken, accidentally. The way it's using Cloudflare breaks it for any IP that has some high "risk" score in their listing (I.E. any that would be prompted with a captcha before proceeding).
When you use the site you are first asked to fill in a Cloudflare captcha. Once it's successfully filled in Cloudflare assigns you some token in a cookie for the site that you can send with later requests to indicate that you've been previously validated by Cloudflare for access to the site.
However, this site serves at least some of it's content from a second sub-domain `assets.change.org`. It seem that the method of requesting causes any cookies to be stripped, as such when it's firing off the request our previously assigned Cloudflare cookie isn't present and this means that Cloudflare prompts us to fill in a new captcha instead of serving the content, this in turn means that some of the javascript that the site is trying to load isn't loaded, breaking functionality.
**Update**:
I was wrong, my own testing suggests this is *not* a firefox bug. Testing on a my own server, `<script async...>` tags are credentialed in cross-subdomain requests. This is a bug on their site, and likely not an intentional attempt to stop Tor users. | If it's not displayed - then the website is detecting that you're using Tor exit and refusing you to do the things you're trying to do. It **is** ridiculous - but even more odd things are happening so far, so it is not possible to do so: even if you will post a form successfully, it will be filtered out by the website - if it can detect Tor exit and refuses you in using it's functionality, it is able to prevent the form processing as well. |
29,849,882 | I want to draw some different JComponents in one JPanel. I create some JComponents with different paint methods. Then create the objects in the main and put them to the JFrame.
My problem is, that only the last Object is painted in the Window.
How can I put different JComponents in the window, without remove or repaint the old ones?
(Model2 works like Model1, but the paintComponent is a little bit different)
```
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GuiModel{
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setSize(600, 600);
frame.setLocation(150, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.getContentPane().add(new Model1(0,0));
frame.getContentPane().add(new Model2(25,37,true));
}
}
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
public class Model1 extends JComponent {
private int xPos, yPos;
Model1 (int x, int y){
this.xPos = x;
this.yPos = y;
}
@Override
protected void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.drawOval(xPos, yPos, 5, 5);
}
}
``` | 2015/04/24 | [
"https://Stackoverflow.com/questions/29849882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4811705/"
] | `JFrame` uses `BorderLayout` by default. When adding components without specifying the constraints, each component will be placed at `CENTER`.
Either specify the constraints, or if `BorderLayout` isn't suffice for you, switch to another layout.
To add constraints:
```
frame.add(new Model1(0,0), BorderLayout.NORTH);
```
I suggest reading [How to use BorderLayout](https://docs.oracle.com/javase/tutorial/uiswing/layout/border.html), as well as [guides on the other predefined layouts](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html). Also, feel free to look online for 3rd party layouts, if none of the layouts available through the JDK fit your needs. Or you could create your own `LayoutManager` if no layouts exist that fit your needs
---
I also recommend using `pack()` to *size your frame based on the components inside* instead of setting it's size with `frame.setSize`. This ensures your frame tightly wraps around anything inside of it, leaving no empty spaces. If you want empty spaces, it should be handled by the layout manager | You can specify size for components or use Layouts to place objects not in one place. Or you can create copy of Graphics and write in it:
```
protected void paintComponent(Graphics g) {
g = g.create();
g.setColor(Color.BLACK);
g.drawOval(xPos, yPos, 5, 5);
g.dispose();
}
```
But the last variant is not efficient: it makes copy of Graphics on each repaint. |
29,849,882 | I want to draw some different JComponents in one JPanel. I create some JComponents with different paint methods. Then create the objects in the main and put them to the JFrame.
My problem is, that only the last Object is painted in the Window.
How can I put different JComponents in the window, without remove or repaint the old ones?
(Model2 works like Model1, but the paintComponent is a little bit different)
```
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GuiModel{
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setSize(600, 600);
frame.setLocation(150, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.getContentPane().add(new Model1(0,0));
frame.getContentPane().add(new Model2(25,37,true));
}
}
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
public class Model1 extends JComponent {
private int xPos, yPos;
Model1 (int x, int y){
this.xPos = x;
this.yPos = y;
}
@Override
protected void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.drawOval(xPos, yPos, 5, 5);
}
}
``` | 2015/04/24 | [
"https://Stackoverflow.com/questions/29849882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4811705/"
] | When doing custom painting:
1. You need to override the `getPreferredSize()` method of your component to return the size of the component so a layout manager can display the component. Right now the size of your components are (0, 0) so there is nothing to paint.
2. The painting of a component is done from (0, 0), not (x, y). Then if you position the component at a specific point on the panel you use setLocation(x, y) to tell Swing where to painting the component.
3. If you want to paint the component at a random position then you also need to use a null layout on the panel and you must also set the size of the component. To set the size of the component you would use setSize( getPreferredSize()) in your constructor.
So your Model1 class would look something like:
```
public class Model1 extends JComponent {
//private int xPos, yPos;
Model1 (int x, int y){
//this.xPos = x;
//this.yPos = y;
setLocation(x, y);
setSize( getPreferredSize() );
}
@Override
public Dimension getPreferredSize()
{
return new Dimension(5, 5);
}
@Override
protected void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
//g.drawOval(xPos, yPos, 5, 5);
g.drawOval(0, 0, 5, 5);
}
}
``` | `JFrame` uses `BorderLayout` by default. When adding components without specifying the constraints, each component will be placed at `CENTER`.
Either specify the constraints, or if `BorderLayout` isn't suffice for you, switch to another layout.
To add constraints:
```
frame.add(new Model1(0,0), BorderLayout.NORTH);
```
I suggest reading [How to use BorderLayout](https://docs.oracle.com/javase/tutorial/uiswing/layout/border.html), as well as [guides on the other predefined layouts](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html). Also, feel free to look online for 3rd party layouts, if none of the layouts available through the JDK fit your needs. Or you could create your own `LayoutManager` if no layouts exist that fit your needs
---
I also recommend using `pack()` to *size your frame based on the components inside* instead of setting it's size with `frame.setSize`. This ensures your frame tightly wraps around anything inside of it, leaving no empty spaces. If you want empty spaces, it should be handled by the layout manager |
29,849,882 | I want to draw some different JComponents in one JPanel. I create some JComponents with different paint methods. Then create the objects in the main and put them to the JFrame.
My problem is, that only the last Object is painted in the Window.
How can I put different JComponents in the window, without remove or repaint the old ones?
(Model2 works like Model1, but the paintComponent is a little bit different)
```
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GuiModel{
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setSize(600, 600);
frame.setLocation(150, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.getContentPane().add(new Model1(0,0));
frame.getContentPane().add(new Model2(25,37,true));
}
}
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
public class Model1 extends JComponent {
private int xPos, yPos;
Model1 (int x, int y){
this.xPos = x;
this.yPos = y;
}
@Override
protected void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.drawOval(xPos, yPos, 5, 5);
}
}
``` | 2015/04/24 | [
"https://Stackoverflow.com/questions/29849882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4811705/"
] | When doing custom painting:
1. You need to override the `getPreferredSize()` method of your component to return the size of the component so a layout manager can display the component. Right now the size of your components are (0, 0) so there is nothing to paint.
2. The painting of a component is done from (0, 0), not (x, y). Then if you position the component at a specific point on the panel you use setLocation(x, y) to tell Swing where to painting the component.
3. If you want to paint the component at a random position then you also need to use a null layout on the panel and you must also set the size of the component. To set the size of the component you would use setSize( getPreferredSize()) in your constructor.
So your Model1 class would look something like:
```
public class Model1 extends JComponent {
//private int xPos, yPos;
Model1 (int x, int y){
//this.xPos = x;
//this.yPos = y;
setLocation(x, y);
setSize( getPreferredSize() );
}
@Override
public Dimension getPreferredSize()
{
return new Dimension(5, 5);
}
@Override
protected void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
//g.drawOval(xPos, yPos, 5, 5);
g.drawOval(0, 0, 5, 5);
}
}
``` | You can specify size for components or use Layouts to place objects not in one place. Or you can create copy of Graphics and write in it:
```
protected void paintComponent(Graphics g) {
g = g.create();
g.setColor(Color.BLACK);
g.drawOval(xPos, yPos, 5, 5);
g.dispose();
}
```
But the last variant is not efficient: it makes copy of Graphics on each repaint. |
39,000,111 | I have this simple query (TSQL) -
```
SELECT IdTour, Tour, TourOrder, IdContent
FROM View_ToursListContentId
WHERE (IdContent = 3) OR (IdContent = 4)
ORDER BY TourOrder DESC, Tour
```
Here is the result
```
58 Air & Style Tour 2015/16 NULL 3
48 FIS Europa Cup 2015/16 NULL 3
46 FIS World Cup Tour 2015/16 NULL 3
131 KDC Grand Slam Regional Qualifiers 2016 NULL 3
59 Swatch Freeride World Tour 2016 NULL 3
77 World Rookie Tour 2015/16 NULL 3
57 World Snowboard Tour 2015/16 NULL 3
45 X Games 2016 NULL 3
45 X Games 2016 NULL 4
```
What I need to do is. If ther is inside result IdTour with IdContent = 3 don't show the same IdTour with IdContent = 4. (Show IdTour with IdContent = 4 only, if there is not the same IdTour with IdContent = 3 - in my case show only one IdTour 45 with IdContent 3)
What is the easiest and the fastest way, how could I accomplish it?
Thanx a lot | 2016/08/17 | [
"https://Stackoverflow.com/questions/39000111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6596234/"
] | One way involves using `NOT EXISTS`:
```
SELECT IdTour, Tour, TourOrder, IdContent
FROM View_ToursListContentId t1
WHERE (IdContent = 3) OR
((IdContent = 4) AND NOT EXISTS (SELECT 1
FROM View_ToursListContentId t2
WHERE t1.IdTour = t2.IdTour AND
t2.IdContent = 3))
ORDER BY TourOrder DESC, Tour
```
The `NOT EXISTS` operator filters out records having `IdContent = 4` in case a record with the same `IdTour` and `IdContent = 3` exists. | you should just use `group by IdContent` in query
like
```
SELECT IdTour, Tour, TourOrder, IdContent
FROM View_ToursListContentId
WHERE (IdContent = 3) OR (IdContent = 4)
group by IdContent
ORDER BY TourOrder DESC, Tour
``` |
39,000,111 | I have this simple query (TSQL) -
```
SELECT IdTour, Tour, TourOrder, IdContent
FROM View_ToursListContentId
WHERE (IdContent = 3) OR (IdContent = 4)
ORDER BY TourOrder DESC, Tour
```
Here is the result
```
58 Air & Style Tour 2015/16 NULL 3
48 FIS Europa Cup 2015/16 NULL 3
46 FIS World Cup Tour 2015/16 NULL 3
131 KDC Grand Slam Regional Qualifiers 2016 NULL 3
59 Swatch Freeride World Tour 2016 NULL 3
77 World Rookie Tour 2015/16 NULL 3
57 World Snowboard Tour 2015/16 NULL 3
45 X Games 2016 NULL 3
45 X Games 2016 NULL 4
```
What I need to do is. If ther is inside result IdTour with IdContent = 3 don't show the same IdTour with IdContent = 4. (Show IdTour with IdContent = 4 only, if there is not the same IdTour with IdContent = 3 - in my case show only one IdTour 45 with IdContent 3)
What is the easiest and the fastest way, how could I accomplish it?
Thanx a lot | 2016/08/17 | [
"https://Stackoverflow.com/questions/39000111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6596234/"
] | One way involves using `NOT EXISTS`:
```
SELECT IdTour, Tour, TourOrder, IdContent
FROM View_ToursListContentId t1
WHERE (IdContent = 3) OR
((IdContent = 4) AND NOT EXISTS (SELECT 1
FROM View_ToursListContentId t2
WHERE t1.IdTour = t2.IdTour AND
t2.IdContent = 3))
ORDER BY TourOrder DESC, Tour
```
The `NOT EXISTS` operator filters out records having `IdContent = 4` in case a record with the same `IdTour` and `IdContent = 3` exists. | You could use a window function to obtain the lowest `IdContent` available for that `IdTour`:
```
SELECT IdTour,
Tour,
TourOrder,
IdContent,
MinIdContent = MIN(IdContent) OVER(PARTITION BY IdTour)
FROM View_ToursListContentId
WHERE IdContent IN (3, 4);
```
Then if this is 3 then you select only 3, if it is 4 then you select only 4, or more simply, only select IdContent that matches the minimum:
```
SELECT IdTour, Tour, TourOrder, IdContent
FROM ( SELECT IdTour,
Tour,
TourOrder,
IdContent,
MinIdContent = MIN(IdContent) OVER(PARTITION BY IdTour)
FROM View_ToursListContentId
WHERE IdContent IN (3, 4)
) AS t
WHERE IdContent = MinIdContent;
```
**FULL EXAMPLE**
```
WITH View_ToursListContentId AS
( SELECT IdTour, Tour, TourOrder, IdContent
FROM (VALUES
(58, 'Air & Style Tour 2015/16', NULL, 3),
(48, 'FIS Europa Cup 2015/16', NULL, 3),
(46, 'FIS World Cup Tour 2015/16', NULL, 3),
(131, 'KDC Grand Slam Regional Qualifiers 2016', NULL, 3),
(59, 'Swatch Freeride World Tour 2016', NULL, 3),
(77, 'World Rookie Tour 2015/16', NULL, 3),
(57, 'World Snowboard Tour 2015/16', NULL, 3),
(45, 'X Games 2016', NULL, 3),
(45, 'X Games 2016', NULL, 4)
) t (IdTour, Tour, TourOrder, IdContent)
)
SELECT IdTour, Tour, TourOrder, IdContent
FROM ( SELECT IdTour,
Tour,
TourOrder,
IdContent,
MinIdContent = MIN(IdContent) OVER(PARTITION BY IdTour)
FROM View_ToursListContentId
WHERE IdContent IN (3, 4)
) AS t
WHERE IdContent = MinIdContent;
``` |
39,000,111 | I have this simple query (TSQL) -
```
SELECT IdTour, Tour, TourOrder, IdContent
FROM View_ToursListContentId
WHERE (IdContent = 3) OR (IdContent = 4)
ORDER BY TourOrder DESC, Tour
```
Here is the result
```
58 Air & Style Tour 2015/16 NULL 3
48 FIS Europa Cup 2015/16 NULL 3
46 FIS World Cup Tour 2015/16 NULL 3
131 KDC Grand Slam Regional Qualifiers 2016 NULL 3
59 Swatch Freeride World Tour 2016 NULL 3
77 World Rookie Tour 2015/16 NULL 3
57 World Snowboard Tour 2015/16 NULL 3
45 X Games 2016 NULL 3
45 X Games 2016 NULL 4
```
What I need to do is. If ther is inside result IdTour with IdContent = 3 don't show the same IdTour with IdContent = 4. (Show IdTour with IdContent = 4 only, if there is not the same IdTour with IdContent = 3 - in my case show only one IdTour 45 with IdContent 3)
What is the easiest and the fastest way, how could I accomplish it?
Thanx a lot | 2016/08/17 | [
"https://Stackoverflow.com/questions/39000111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6596234/"
] | One way involves using `NOT EXISTS`:
```
SELECT IdTour, Tour, TourOrder, IdContent
FROM View_ToursListContentId t1
WHERE (IdContent = 3) OR
((IdContent = 4) AND NOT EXISTS (SELECT 1
FROM View_ToursListContentId t2
WHERE t1.IdTour = t2.IdTour AND
t2.IdContent = 3))
ORDER BY TourOrder DESC, Tour
```
The `NOT EXISTS` operator filters out records having `IdContent = 4` in case a record with the same `IdTour` and `IdContent = 3` exists. | ```
select * from (
select row_number() over (partition by IdTour, Tour, TourOrder order by IdContent) rownum,
IdTour, Tour, TourOrder, IdContent from View_ToursListContentId)src
where rownum=1
``` |
39,000,111 | I have this simple query (TSQL) -
```
SELECT IdTour, Tour, TourOrder, IdContent
FROM View_ToursListContentId
WHERE (IdContent = 3) OR (IdContent = 4)
ORDER BY TourOrder DESC, Tour
```
Here is the result
```
58 Air & Style Tour 2015/16 NULL 3
48 FIS Europa Cup 2015/16 NULL 3
46 FIS World Cup Tour 2015/16 NULL 3
131 KDC Grand Slam Regional Qualifiers 2016 NULL 3
59 Swatch Freeride World Tour 2016 NULL 3
77 World Rookie Tour 2015/16 NULL 3
57 World Snowboard Tour 2015/16 NULL 3
45 X Games 2016 NULL 3
45 X Games 2016 NULL 4
```
What I need to do is. If ther is inside result IdTour with IdContent = 3 don't show the same IdTour with IdContent = 4. (Show IdTour with IdContent = 4 only, if there is not the same IdTour with IdContent = 3 - in my case show only one IdTour 45 with IdContent 3)
What is the easiest and the fastest way, how could I accomplish it?
Thanx a lot | 2016/08/17 | [
"https://Stackoverflow.com/questions/39000111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6596234/"
] | You could use a window function to obtain the lowest `IdContent` available for that `IdTour`:
```
SELECT IdTour,
Tour,
TourOrder,
IdContent,
MinIdContent = MIN(IdContent) OVER(PARTITION BY IdTour)
FROM View_ToursListContentId
WHERE IdContent IN (3, 4);
```
Then if this is 3 then you select only 3, if it is 4 then you select only 4, or more simply, only select IdContent that matches the minimum:
```
SELECT IdTour, Tour, TourOrder, IdContent
FROM ( SELECT IdTour,
Tour,
TourOrder,
IdContent,
MinIdContent = MIN(IdContent) OVER(PARTITION BY IdTour)
FROM View_ToursListContentId
WHERE IdContent IN (3, 4)
) AS t
WHERE IdContent = MinIdContent;
```
**FULL EXAMPLE**
```
WITH View_ToursListContentId AS
( SELECT IdTour, Tour, TourOrder, IdContent
FROM (VALUES
(58, 'Air & Style Tour 2015/16', NULL, 3),
(48, 'FIS Europa Cup 2015/16', NULL, 3),
(46, 'FIS World Cup Tour 2015/16', NULL, 3),
(131, 'KDC Grand Slam Regional Qualifiers 2016', NULL, 3),
(59, 'Swatch Freeride World Tour 2016', NULL, 3),
(77, 'World Rookie Tour 2015/16', NULL, 3),
(57, 'World Snowboard Tour 2015/16', NULL, 3),
(45, 'X Games 2016', NULL, 3),
(45, 'X Games 2016', NULL, 4)
) t (IdTour, Tour, TourOrder, IdContent)
)
SELECT IdTour, Tour, TourOrder, IdContent
FROM ( SELECT IdTour,
Tour,
TourOrder,
IdContent,
MinIdContent = MIN(IdContent) OVER(PARTITION BY IdTour)
FROM View_ToursListContentId
WHERE IdContent IN (3, 4)
) AS t
WHERE IdContent = MinIdContent;
``` | you should just use `group by IdContent` in query
like
```
SELECT IdTour, Tour, TourOrder, IdContent
FROM View_ToursListContentId
WHERE (IdContent = 3) OR (IdContent = 4)
group by IdContent
ORDER BY TourOrder DESC, Tour
``` |
39,000,111 | I have this simple query (TSQL) -
```
SELECT IdTour, Tour, TourOrder, IdContent
FROM View_ToursListContentId
WHERE (IdContent = 3) OR (IdContent = 4)
ORDER BY TourOrder DESC, Tour
```
Here is the result
```
58 Air & Style Tour 2015/16 NULL 3
48 FIS Europa Cup 2015/16 NULL 3
46 FIS World Cup Tour 2015/16 NULL 3
131 KDC Grand Slam Regional Qualifiers 2016 NULL 3
59 Swatch Freeride World Tour 2016 NULL 3
77 World Rookie Tour 2015/16 NULL 3
57 World Snowboard Tour 2015/16 NULL 3
45 X Games 2016 NULL 3
45 X Games 2016 NULL 4
```
What I need to do is. If ther is inside result IdTour with IdContent = 3 don't show the same IdTour with IdContent = 4. (Show IdTour with IdContent = 4 only, if there is not the same IdTour with IdContent = 3 - in my case show only one IdTour 45 with IdContent 3)
What is the easiest and the fastest way, how could I accomplish it?
Thanx a lot | 2016/08/17 | [
"https://Stackoverflow.com/questions/39000111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6596234/"
] | ```
select * from (
select row_number() over (partition by IdTour, Tour, TourOrder order by IdContent) rownum,
IdTour, Tour, TourOrder, IdContent from View_ToursListContentId)src
where rownum=1
``` | you should just use `group by IdContent` in query
like
```
SELECT IdTour, Tour, TourOrder, IdContent
FROM View_ToursListContentId
WHERE (IdContent = 3) OR (IdContent = 4)
group by IdContent
ORDER BY TourOrder DESC, Tour
``` |
53,493,331 | How to capture and remove the first occurrence of a `<br/>` tag within a paragraph.
```
<p><br/>Hello World</p>
```
Becomes:
```
<p>Hello World</p>
```
But importantly the following remains unchanged:
```
<p><br/></p>
```
>
> Remove leading `<br>` tags from paragraphs that contain text
>
>
>
---
What I have so far:
```
preg_replace('/(<p>\s*<br *\/?>(.*?)<\/p>)+/si', '<p>$2</p>', $html);
```
Although this captures `<p><br></p>` instances... | 2018/11/27 | [
"https://Stackoverflow.com/questions/53493331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/913622/"
] | Here is how you would do it using PHP's built in [`DOMDocument`](http://php.net/manual/en/class.domdocument.php) and [`DOMXPath`](http://php.net/manual/en/class.domxpath.php) classes:
```
$html = "<div><p><br/>Hello World</p><p><br/></p><p> <br> </p></div>";
$doc = new DOMDocument();
$doc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($doc);
// find <br> within a <p> that has text content
$breaks = $xpath->query("//p[normalize-space()!='']/br");
$breaks = $xpath->query("//p[text()!='']/br");
// and remove them
foreach ($breaks as $br) {
$br->parentNode->removeChild($br);
}
echo $doc->saveHTML();
```
Note that there are two lines assigning values to `$breaks`. You should use the one which meets your requirements: the first will only strip `<br>` from elements which have non-whitespace characters between the `<p>` and `</p>`, while the second will also strip them from `<p>` elements containing only whitespace. The different effects can be seen in this [demo](https://3v4l.org/qFbdS). | If there are more rules, we can pass array in `preg_replace`. In my solution, first element in pattern will look for `<br />` with text. and second will look for just `<br />` without text. Also this search is made from the beginng of the string (`/^..`).
```
preg_replace(['/^(<p>\s*(<br *\/?>)([a-zA-Z0-9 ]+)<\/p>)+/si', '/^(<p>\s*(<br *\/?>)<\/p>)+/si'], ['<p>$3</p>', '$0'], $html);
``` |
53,493,331 | How to capture and remove the first occurrence of a `<br/>` tag within a paragraph.
```
<p><br/>Hello World</p>
```
Becomes:
```
<p>Hello World</p>
```
But importantly the following remains unchanged:
```
<p><br/></p>
```
>
> Remove leading `<br>` tags from paragraphs that contain text
>
>
>
---
What I have so far:
```
preg_replace('/(<p>\s*<br *\/?>(.*?)<\/p>)+/si', '<p>$2</p>', $html);
```
Although this captures `<p><br></p>` instances... | 2018/11/27 | [
"https://Stackoverflow.com/questions/53493331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/913622/"
] | Here is how you would do it using PHP's built in [`DOMDocument`](http://php.net/manual/en/class.domdocument.php) and [`DOMXPath`](http://php.net/manual/en/class.domxpath.php) classes:
```
$html = "<div><p><br/>Hello World</p><p><br/></p><p> <br> </p></div>";
$doc = new DOMDocument();
$doc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($doc);
// find <br> within a <p> that has text content
$breaks = $xpath->query("//p[normalize-space()!='']/br");
$breaks = $xpath->query("//p[text()!='']/br");
// and remove them
foreach ($breaks as $br) {
$br->parentNode->removeChild($br);
}
echo $doc->saveHTML();
```
Note that there are two lines assigning values to `$breaks`. You should use the one which meets your requirements: the first will only strip `<br>` from elements which have non-whitespace characters between the `<p>` and `</p>`, while the second will also strip them from `<p>` elements containing only whitespace. The different effects can be seen in this [demo](https://3v4l.org/qFbdS). | It is not a recommended way to parse html with regex. But just for a quick and temporary work, you may use this regex to capture a linebreak `<br/>` that is preceded by `<p>` tag and some text and do a lookahead that it should not be immediately followed by closing `</p>` tag.
```
<p>.*?\K<br\/>(?!<\/p>)
```
and replace such captured `<br/>` with empty string hence removing it.
**Explanation:**
* `<p>.*?` --> Match a paragraph tag followed by any characters in non-greedy way
* `\K` --> Reset whatever matched as we don't intend to replace that
* `<br\/>(?!<\/p>)` --> Match a line break tag that is not immediately followed by closing paragraph tag, which will be replaced with empty string.
[Demo](https://regex101.com/r/cKYeSo/1)
Here are sample php codes,
```
$html = '<p><br/>Hello World</p>';
$html = preg_replace('/<p>.*?\K<br\/>(?!<\/p>)/si', '', $html);
echo $html. "\n";
$html = '<p><br/></p>';
$html = preg_replace('/<p>.*?\K<br\/>(?!<\/p>)/si', '', $html);
echo $html. "\n";
```
Which prints following output,
```
<p>Hello World</p>
<p><br/></p>
``` |
25,940,241 | Is there a way we can fill `NA`s in a `zoo` or `xts` object with limited number of `NA`s forward. In other words like fill `NA`s up to 3 consecutive `NA`s, and then keep the `NA`s from the 4th value on until a valid number.
Something like this.
```
library(zoo)
x <- zoo(1:20, Sys.Date() + 1:20)
x[c(2:4, 6:10, 13:18)] <- NA
x
2014-09-20 2014-09-21 2014-09-22 2014-09-23 2014-09-24 2014-09-25 2014-09-26
1 NA NA NA 5 NA NA
2014-09-27 2014-09-28 2014-09-29 2014-09-30 2014-10-01 2014-10-02 2014-10-03
NA NA NA 11 12 NA NA
2014-10-04 2014-10-05 2014-10-06 2014-10-07 2014-10-08 2014-10-09
NA NA NA NA 19 20
```
Desired output, will be something with variable n = 3 is
```
2014-09-20 2014-09-21 2014-09-22 2014-09-23 2014-09-24 2014-09-25 2014-09-26
1 1 1 1 5 5 5
2014-09-27 2014-09-28 2014-09-29 2014-09-30 2014-10-01 2014-10-02 2014-10-03
5 NA NA 11 12 12 12
2014-10-04 2014-10-05 2014-10-06 2014-10-07 2014-10-08 2014-10-09
12 NA NA NA 19 20
```
I have tried lot of combination with `na.locf(x, maxgap = 3)` etc without much success. I can create a loop to get the desired output, I was wondering whether there is vectorized way of achieving this.
```
fillInTheBlanks <- function(v, n=3) {
result <- v
counter0 <- 1
for(i in 2:length(v)) {
value <- v[i]
if (is.na(value)) {
if (counter0 > n) {
result[i] <- v[i]
} else {
result[i] <- result[i-1]
counter0 <- counter0 + 1
} }
else {
result[i] <- v[i]
counter0 <- 1
}
}
return(result)
}
```
Thanks | 2014/09/19 | [
"https://Stackoverflow.com/questions/25940241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4059416/"
] | Here's another way:
```
l <- cumsum(! is.na(x))
c(NA, x[! is.na(x)])[replace(l, ave(l, l, FUN=seq_along) > 4, 0) + 1]
# [1] 1 1 1 1 5 5 5 5 NA NA 11 12 12 12 12 NA NA NA 19 20
```
**edit**: my previous answer required that `x` have no duplicates. The current answer does not.
**benchmarks**
```
x <- rep(x, length.out=1e4)
plourde <- function(x) {
l <- cumsum(! is.na(x))
c(NA, x[! is.na(x)])[replace(l, ave(l, l, FUN=seq_along) > 4, 0) + 1]
}
agstudy <- function(x) {
unlist(sapply(split(coredata(x),cumsum(!is.na(x))),
function(sx){
if(length(sx)>3)
sx[2:4] <- rep(sx[1],3)
else sx <- rep(sx[1],length(sx))
sx
}))
}
microbenchmark(plourde(x), agstudy(x))
# Unit: milliseconds
# expr min lq median uq max neval
# plourde(x) 5.30 5.591 6.409 6.774 57.13 100
# agstudy(x) 16.04 16.249 16.454 17.516 20.64 100
``` | Without using `na.locf`, but the idea is to split your xts by group of non missing values, then for each group replacing only the 3 first values (after the non misssing one) with the first value. It is a loop , but since it is only applied on group , it should be faster than a simple loop over all the values.
```
zz <-
unlist(sapply(split(coredata(x),cumsum(!is.na(x))),
function(sx){
if(length(sx)>3)
sx[2:4] <- rep(sx[1],3)
else sx <- rep(sx[1],length(sx))
sx
}))
## create the zoo object since , the latter algorithm is applied only to the values
zoo(zz,index(x))
2014-09-20 2014-09-21 2014-09-22 2014-09-23 2014-09-24 2014-09-25 2014-09-26 2014-09-27 2014-09-28 2014-09-29 2014-09-30 2014-10-01 2014-10-02
1 1 1 1 5 5 5 5 NA NA 11 12 12
2014-10-03 2014-10-04 2014-10-05 2014-10-06 2014-10-07 2014-10-08 2014-10-09
12 12 NA NA NA 19 20
``` |
25,940,241 | Is there a way we can fill `NA`s in a `zoo` or `xts` object with limited number of `NA`s forward. In other words like fill `NA`s up to 3 consecutive `NA`s, and then keep the `NA`s from the 4th value on until a valid number.
Something like this.
```
library(zoo)
x <- zoo(1:20, Sys.Date() + 1:20)
x[c(2:4, 6:10, 13:18)] <- NA
x
2014-09-20 2014-09-21 2014-09-22 2014-09-23 2014-09-24 2014-09-25 2014-09-26
1 NA NA NA 5 NA NA
2014-09-27 2014-09-28 2014-09-29 2014-09-30 2014-10-01 2014-10-02 2014-10-03
NA NA NA 11 12 NA NA
2014-10-04 2014-10-05 2014-10-06 2014-10-07 2014-10-08 2014-10-09
NA NA NA NA 19 20
```
Desired output, will be something with variable n = 3 is
```
2014-09-20 2014-09-21 2014-09-22 2014-09-23 2014-09-24 2014-09-25 2014-09-26
1 1 1 1 5 5 5
2014-09-27 2014-09-28 2014-09-29 2014-09-30 2014-10-01 2014-10-02 2014-10-03
5 NA NA 11 12 12 12
2014-10-04 2014-10-05 2014-10-06 2014-10-07 2014-10-08 2014-10-09
12 NA NA NA 19 20
```
I have tried lot of combination with `na.locf(x, maxgap = 3)` etc without much success. I can create a loop to get the desired output, I was wondering whether there is vectorized way of achieving this.
```
fillInTheBlanks <- function(v, n=3) {
result <- v
counter0 <- 1
for(i in 2:length(v)) {
value <- v[i]
if (is.na(value)) {
if (counter0 > n) {
result[i] <- v[i]
} else {
result[i] <- result[i-1]
counter0 <- counter0 + 1
} }
else {
result[i] <- v[i]
counter0 <- 1
}
}
return(result)
}
```
Thanks | 2014/09/19 | [
"https://Stackoverflow.com/questions/25940241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4059416/"
] | Without using `na.locf`, but the idea is to split your xts by group of non missing values, then for each group replacing only the 3 first values (after the non misssing one) with the first value. It is a loop , but since it is only applied on group , it should be faster than a simple loop over all the values.
```
zz <-
unlist(sapply(split(coredata(x),cumsum(!is.na(x))),
function(sx){
if(length(sx)>3)
sx[2:4] <- rep(sx[1],3)
else sx <- rep(sx[1],length(sx))
sx
}))
## create the zoo object since , the latter algorithm is applied only to the values
zoo(zz,index(x))
2014-09-20 2014-09-21 2014-09-22 2014-09-23 2014-09-24 2014-09-25 2014-09-26 2014-09-27 2014-09-28 2014-09-29 2014-09-30 2014-10-01 2014-10-02
1 1 1 1 5 5 5 5 NA NA 11 12 12
2014-10-03 2014-10-04 2014-10-05 2014-10-06 2014-10-07 2014-10-08 2014-10-09
12 12 NA NA NA 19 20
``` | From playing around in `data.table` comes this hacky solution:
```
np1 <- 3 + 1
dt[,
x_filled := x[c(rep(1, min(np1, .N)), rep(NA, max(0, .N - np1)))],
by = cumsum(!is.na(x))]
# Or slightly simplified:
dt[,
x_filled := ifelse(rowid(x) < 4, x[1], x[NA]),
by = cumsum(!is.na(x))]
> dt
date x x_filled
1: 2019-02-14 1 1
2: 2019-02-15 NA 1
3: 2019-02-16 NA 1
4: 2019-02-17 NA 1
5: 2019-02-18 5 5
6: 2019-02-19 NA 5
7: 2019-02-20 NA 5
8: 2019-02-21 NA 5
9: 2019-02-22 NA NA
10: 2019-02-23 NA NA
11: 2019-02-24 11 11
12: 2019-02-25 12 12
13: 2019-02-26 NA 12
14: 2019-02-27 NA 12
15: 2019-02-28 NA 12
16: 2019-03-01 NA NA
17: 2019-03-02 NA NA
18: 2019-03-03 NA NA
19: 2019-03-04 19 19
20: 2019-03-05 20 20
```
We build on the fact that subsetting vectors with `NA` returns `NA`.
*Data/Packages*
```
library(zoo)
library(data.table)
x <- zoo(1:20, Sys.Date() + 1:20)
x[c(2:4, 6:10, 13:18)] <- NA
dt <- data.table(date = index(x), x = as.integer(x))
``` |
25,940,241 | Is there a way we can fill `NA`s in a `zoo` or `xts` object with limited number of `NA`s forward. In other words like fill `NA`s up to 3 consecutive `NA`s, and then keep the `NA`s from the 4th value on until a valid number.
Something like this.
```
library(zoo)
x <- zoo(1:20, Sys.Date() + 1:20)
x[c(2:4, 6:10, 13:18)] <- NA
x
2014-09-20 2014-09-21 2014-09-22 2014-09-23 2014-09-24 2014-09-25 2014-09-26
1 NA NA NA 5 NA NA
2014-09-27 2014-09-28 2014-09-29 2014-09-30 2014-10-01 2014-10-02 2014-10-03
NA NA NA 11 12 NA NA
2014-10-04 2014-10-05 2014-10-06 2014-10-07 2014-10-08 2014-10-09
NA NA NA NA 19 20
```
Desired output, will be something with variable n = 3 is
```
2014-09-20 2014-09-21 2014-09-22 2014-09-23 2014-09-24 2014-09-25 2014-09-26
1 1 1 1 5 5 5
2014-09-27 2014-09-28 2014-09-29 2014-09-30 2014-10-01 2014-10-02 2014-10-03
5 NA NA 11 12 12 12
2014-10-04 2014-10-05 2014-10-06 2014-10-07 2014-10-08 2014-10-09
12 NA NA NA 19 20
```
I have tried lot of combination with `na.locf(x, maxgap = 3)` etc without much success. I can create a loop to get the desired output, I was wondering whether there is vectorized way of achieving this.
```
fillInTheBlanks <- function(v, n=3) {
result <- v
counter0 <- 1
for(i in 2:length(v)) {
value <- v[i]
if (is.na(value)) {
if (counter0 > n) {
result[i] <- v[i]
} else {
result[i] <- result[i-1]
counter0 <- counter0 + 1
} }
else {
result[i] <- v[i]
counter0 <- 1
}
}
return(result)
}
```
Thanks | 2014/09/19 | [
"https://Stackoverflow.com/questions/25940241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4059416/"
] | Here's another way:
```
l <- cumsum(! is.na(x))
c(NA, x[! is.na(x)])[replace(l, ave(l, l, FUN=seq_along) > 4, 0) + 1]
# [1] 1 1 1 1 5 5 5 5 NA NA 11 12 12 12 12 NA NA NA 19 20
```
**edit**: my previous answer required that `x` have no duplicates. The current answer does not.
**benchmarks**
```
x <- rep(x, length.out=1e4)
plourde <- function(x) {
l <- cumsum(! is.na(x))
c(NA, x[! is.na(x)])[replace(l, ave(l, l, FUN=seq_along) > 4, 0) + 1]
}
agstudy <- function(x) {
unlist(sapply(split(coredata(x),cumsum(!is.na(x))),
function(sx){
if(length(sx)>3)
sx[2:4] <- rep(sx[1],3)
else sx <- rep(sx[1],length(sx))
sx
}))
}
microbenchmark(plourde(x), agstudy(x))
# Unit: milliseconds
# expr min lq median uq max neval
# plourde(x) 5.30 5.591 6.409 6.774 57.13 100
# agstudy(x) 16.04 16.249 16.454 17.516 20.64 100
``` | And another idea that, unless I've missed something, seems valid:
```
na_locf_until = function(x, n = 3)
{
wnn = which(!is.na(x))
inds = sort(c(wnn, (wnn + n+1)[which((wnn + n+1) < c(wnn[-1], length(x)))]))
c(rep(NA, wnn[1] - 1),
as.vector(x)[rep(inds, c(diff(inds), length(x) - inds[length(inds)] + 1))])
}
na_locf_until(x)
#[1] 1 1 1 1 5 5 5 5 NA NA 11 12 12 12 12 NA NA NA 19 20
``` |
25,940,241 | Is there a way we can fill `NA`s in a `zoo` or `xts` object with limited number of `NA`s forward. In other words like fill `NA`s up to 3 consecutive `NA`s, and then keep the `NA`s from the 4th value on until a valid number.
Something like this.
```
library(zoo)
x <- zoo(1:20, Sys.Date() + 1:20)
x[c(2:4, 6:10, 13:18)] <- NA
x
2014-09-20 2014-09-21 2014-09-22 2014-09-23 2014-09-24 2014-09-25 2014-09-26
1 NA NA NA 5 NA NA
2014-09-27 2014-09-28 2014-09-29 2014-09-30 2014-10-01 2014-10-02 2014-10-03
NA NA NA 11 12 NA NA
2014-10-04 2014-10-05 2014-10-06 2014-10-07 2014-10-08 2014-10-09
NA NA NA NA 19 20
```
Desired output, will be something with variable n = 3 is
```
2014-09-20 2014-09-21 2014-09-22 2014-09-23 2014-09-24 2014-09-25 2014-09-26
1 1 1 1 5 5 5
2014-09-27 2014-09-28 2014-09-29 2014-09-30 2014-10-01 2014-10-02 2014-10-03
5 NA NA 11 12 12 12
2014-10-04 2014-10-05 2014-10-06 2014-10-07 2014-10-08 2014-10-09
12 NA NA NA 19 20
```
I have tried lot of combination with `na.locf(x, maxgap = 3)` etc without much success. I can create a loop to get the desired output, I was wondering whether there is vectorized way of achieving this.
```
fillInTheBlanks <- function(v, n=3) {
result <- v
counter0 <- 1
for(i in 2:length(v)) {
value <- v[i]
if (is.na(value)) {
if (counter0 > n) {
result[i] <- v[i]
} else {
result[i] <- result[i-1]
counter0 <- counter0 + 1
} }
else {
result[i] <- v[i]
counter0 <- 1
}
}
return(result)
}
```
Thanks | 2014/09/19 | [
"https://Stackoverflow.com/questions/25940241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4059416/"
] | Here's another way:
```
l <- cumsum(! is.na(x))
c(NA, x[! is.na(x)])[replace(l, ave(l, l, FUN=seq_along) > 4, 0) + 1]
# [1] 1 1 1 1 5 5 5 5 NA NA 11 12 12 12 12 NA NA NA 19 20
```
**edit**: my previous answer required that `x` have no duplicates. The current answer does not.
**benchmarks**
```
x <- rep(x, length.out=1e4)
plourde <- function(x) {
l <- cumsum(! is.na(x))
c(NA, x[! is.na(x)])[replace(l, ave(l, l, FUN=seq_along) > 4, 0) + 1]
}
agstudy <- function(x) {
unlist(sapply(split(coredata(x),cumsum(!is.na(x))),
function(sx){
if(length(sx)>3)
sx[2:4] <- rep(sx[1],3)
else sx <- rep(sx[1],length(sx))
sx
}))
}
microbenchmark(plourde(x), agstudy(x))
# Unit: milliseconds
# expr min lq median uq max neval
# plourde(x) 5.30 5.591 6.409 6.774 57.13 100
# agstudy(x) 16.04 16.249 16.454 17.516 20.64 100
``` | From playing around in `data.table` comes this hacky solution:
```
np1 <- 3 + 1
dt[,
x_filled := x[c(rep(1, min(np1, .N)), rep(NA, max(0, .N - np1)))],
by = cumsum(!is.na(x))]
# Or slightly simplified:
dt[,
x_filled := ifelse(rowid(x) < 4, x[1], x[NA]),
by = cumsum(!is.na(x))]
> dt
date x x_filled
1: 2019-02-14 1 1
2: 2019-02-15 NA 1
3: 2019-02-16 NA 1
4: 2019-02-17 NA 1
5: 2019-02-18 5 5
6: 2019-02-19 NA 5
7: 2019-02-20 NA 5
8: 2019-02-21 NA 5
9: 2019-02-22 NA NA
10: 2019-02-23 NA NA
11: 2019-02-24 11 11
12: 2019-02-25 12 12
13: 2019-02-26 NA 12
14: 2019-02-27 NA 12
15: 2019-02-28 NA 12
16: 2019-03-01 NA NA
17: 2019-03-02 NA NA
18: 2019-03-03 NA NA
19: 2019-03-04 19 19
20: 2019-03-05 20 20
```
We build on the fact that subsetting vectors with `NA` returns `NA`.
*Data/Packages*
```
library(zoo)
library(data.table)
x <- zoo(1:20, Sys.Date() + 1:20)
x[c(2:4, 6:10, 13:18)] <- NA
dt <- data.table(date = index(x), x = as.integer(x))
``` |
25,940,241 | Is there a way we can fill `NA`s in a `zoo` or `xts` object with limited number of `NA`s forward. In other words like fill `NA`s up to 3 consecutive `NA`s, and then keep the `NA`s from the 4th value on until a valid number.
Something like this.
```
library(zoo)
x <- zoo(1:20, Sys.Date() + 1:20)
x[c(2:4, 6:10, 13:18)] <- NA
x
2014-09-20 2014-09-21 2014-09-22 2014-09-23 2014-09-24 2014-09-25 2014-09-26
1 NA NA NA 5 NA NA
2014-09-27 2014-09-28 2014-09-29 2014-09-30 2014-10-01 2014-10-02 2014-10-03
NA NA NA 11 12 NA NA
2014-10-04 2014-10-05 2014-10-06 2014-10-07 2014-10-08 2014-10-09
NA NA NA NA 19 20
```
Desired output, will be something with variable n = 3 is
```
2014-09-20 2014-09-21 2014-09-22 2014-09-23 2014-09-24 2014-09-25 2014-09-26
1 1 1 1 5 5 5
2014-09-27 2014-09-28 2014-09-29 2014-09-30 2014-10-01 2014-10-02 2014-10-03
5 NA NA 11 12 12 12
2014-10-04 2014-10-05 2014-10-06 2014-10-07 2014-10-08 2014-10-09
12 NA NA NA 19 20
```
I have tried lot of combination with `na.locf(x, maxgap = 3)` etc without much success. I can create a loop to get the desired output, I was wondering whether there is vectorized way of achieving this.
```
fillInTheBlanks <- function(v, n=3) {
result <- v
counter0 <- 1
for(i in 2:length(v)) {
value <- v[i]
if (is.na(value)) {
if (counter0 > n) {
result[i] <- v[i]
} else {
result[i] <- result[i-1]
counter0 <- counter0 + 1
} }
else {
result[i] <- v[i]
counter0 <- 1
}
}
return(result)
}
```
Thanks | 2014/09/19 | [
"https://Stackoverflow.com/questions/25940241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4059416/"
] | Here's another way:
```
l <- cumsum(! is.na(x))
c(NA, x[! is.na(x)])[replace(l, ave(l, l, FUN=seq_along) > 4, 0) + 1]
# [1] 1 1 1 1 5 5 5 5 NA NA 11 12 12 12 12 NA NA NA 19 20
```
**edit**: my previous answer required that `x` have no duplicates. The current answer does not.
**benchmarks**
```
x <- rep(x, length.out=1e4)
plourde <- function(x) {
l <- cumsum(! is.na(x))
c(NA, x[! is.na(x)])[replace(l, ave(l, l, FUN=seq_along) > 4, 0) + 1]
}
agstudy <- function(x) {
unlist(sapply(split(coredata(x),cumsum(!is.na(x))),
function(sx){
if(length(sx)>3)
sx[2:4] <- rep(sx[1],3)
else sx <- rep(sx[1],length(sx))
sx
}))
}
microbenchmark(plourde(x), agstudy(x))
# Unit: milliseconds
# expr min lq median uq max neval
# plourde(x) 5.30 5.591 6.409 6.774 57.13 100
# agstudy(x) 16.04 16.249 16.454 17.516 20.64 100
``` | The cleanest way to implement this in `data.table` is probably using the join syntax:
```
na.omit(dt)[dt, on = .(date), roll = +3, .(date, x_filled = x, x = i.x)]
date x_filled x
1: 2019-02-14 1 1
2: 2019-02-15 1 NA
3: 2019-02-16 1 NA
4: 2019-02-17 1 NA
5: 2019-02-18 5 5
6: 2019-02-19 5 NA
7: 2019-02-20 5 NA
8: 2019-02-21 5 NA
9: 2019-02-22 NA NA
10: 2019-02-23 NA NA
11: 2019-02-24 11 11
12: 2019-02-25 12 12
13: 2019-02-26 12 NA
14: 2019-02-27 12 NA
15: 2019-02-28 12 NA
16: 2019-03-01 NA NA
17: 2019-03-02 NA NA
18: 2019-03-03 NA NA
19: 2019-03-04 19 19
20: 2019-03-05 20 20
```
\*This solution depends on the date columns and it being contiguous |
25,940,241 | Is there a way we can fill `NA`s in a `zoo` or `xts` object with limited number of `NA`s forward. In other words like fill `NA`s up to 3 consecutive `NA`s, and then keep the `NA`s from the 4th value on until a valid number.
Something like this.
```
library(zoo)
x <- zoo(1:20, Sys.Date() + 1:20)
x[c(2:4, 6:10, 13:18)] <- NA
x
2014-09-20 2014-09-21 2014-09-22 2014-09-23 2014-09-24 2014-09-25 2014-09-26
1 NA NA NA 5 NA NA
2014-09-27 2014-09-28 2014-09-29 2014-09-30 2014-10-01 2014-10-02 2014-10-03
NA NA NA 11 12 NA NA
2014-10-04 2014-10-05 2014-10-06 2014-10-07 2014-10-08 2014-10-09
NA NA NA NA 19 20
```
Desired output, will be something with variable n = 3 is
```
2014-09-20 2014-09-21 2014-09-22 2014-09-23 2014-09-24 2014-09-25 2014-09-26
1 1 1 1 5 5 5
2014-09-27 2014-09-28 2014-09-29 2014-09-30 2014-10-01 2014-10-02 2014-10-03
5 NA NA 11 12 12 12
2014-10-04 2014-10-05 2014-10-06 2014-10-07 2014-10-08 2014-10-09
12 NA NA NA 19 20
```
I have tried lot of combination with `na.locf(x, maxgap = 3)` etc without much success. I can create a loop to get the desired output, I was wondering whether there is vectorized way of achieving this.
```
fillInTheBlanks <- function(v, n=3) {
result <- v
counter0 <- 1
for(i in 2:length(v)) {
value <- v[i]
if (is.na(value)) {
if (counter0 > n) {
result[i] <- v[i]
} else {
result[i] <- result[i-1]
counter0 <- counter0 + 1
} }
else {
result[i] <- v[i]
counter0 <- 1
}
}
return(result)
}
```
Thanks | 2014/09/19 | [
"https://Stackoverflow.com/questions/25940241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4059416/"
] | And another idea that, unless I've missed something, seems valid:
```
na_locf_until = function(x, n = 3)
{
wnn = which(!is.na(x))
inds = sort(c(wnn, (wnn + n+1)[which((wnn + n+1) < c(wnn[-1], length(x)))]))
c(rep(NA, wnn[1] - 1),
as.vector(x)[rep(inds, c(diff(inds), length(x) - inds[length(inds)] + 1))])
}
na_locf_until(x)
#[1] 1 1 1 1 5 5 5 5 NA NA 11 12 12 12 12 NA NA NA 19 20
``` | From playing around in `data.table` comes this hacky solution:
```
np1 <- 3 + 1
dt[,
x_filled := x[c(rep(1, min(np1, .N)), rep(NA, max(0, .N - np1)))],
by = cumsum(!is.na(x))]
# Or slightly simplified:
dt[,
x_filled := ifelse(rowid(x) < 4, x[1], x[NA]),
by = cumsum(!is.na(x))]
> dt
date x x_filled
1: 2019-02-14 1 1
2: 2019-02-15 NA 1
3: 2019-02-16 NA 1
4: 2019-02-17 NA 1
5: 2019-02-18 5 5
6: 2019-02-19 NA 5
7: 2019-02-20 NA 5
8: 2019-02-21 NA 5
9: 2019-02-22 NA NA
10: 2019-02-23 NA NA
11: 2019-02-24 11 11
12: 2019-02-25 12 12
13: 2019-02-26 NA 12
14: 2019-02-27 NA 12
15: 2019-02-28 NA 12
16: 2019-03-01 NA NA
17: 2019-03-02 NA NA
18: 2019-03-03 NA NA
19: 2019-03-04 19 19
20: 2019-03-05 20 20
```
We build on the fact that subsetting vectors with `NA` returns `NA`.
*Data/Packages*
```
library(zoo)
library(data.table)
x <- zoo(1:20, Sys.Date() + 1:20)
x[c(2:4, 6:10, 13:18)] <- NA
dt <- data.table(date = index(x), x = as.integer(x))
``` |
25,940,241 | Is there a way we can fill `NA`s in a `zoo` or `xts` object with limited number of `NA`s forward. In other words like fill `NA`s up to 3 consecutive `NA`s, and then keep the `NA`s from the 4th value on until a valid number.
Something like this.
```
library(zoo)
x <- zoo(1:20, Sys.Date() + 1:20)
x[c(2:4, 6:10, 13:18)] <- NA
x
2014-09-20 2014-09-21 2014-09-22 2014-09-23 2014-09-24 2014-09-25 2014-09-26
1 NA NA NA 5 NA NA
2014-09-27 2014-09-28 2014-09-29 2014-09-30 2014-10-01 2014-10-02 2014-10-03
NA NA NA 11 12 NA NA
2014-10-04 2014-10-05 2014-10-06 2014-10-07 2014-10-08 2014-10-09
NA NA NA NA 19 20
```
Desired output, will be something with variable n = 3 is
```
2014-09-20 2014-09-21 2014-09-22 2014-09-23 2014-09-24 2014-09-25 2014-09-26
1 1 1 1 5 5 5
2014-09-27 2014-09-28 2014-09-29 2014-09-30 2014-10-01 2014-10-02 2014-10-03
5 NA NA 11 12 12 12
2014-10-04 2014-10-05 2014-10-06 2014-10-07 2014-10-08 2014-10-09
12 NA NA NA 19 20
```
I have tried lot of combination with `na.locf(x, maxgap = 3)` etc without much success. I can create a loop to get the desired output, I was wondering whether there is vectorized way of achieving this.
```
fillInTheBlanks <- function(v, n=3) {
result <- v
counter0 <- 1
for(i in 2:length(v)) {
value <- v[i]
if (is.na(value)) {
if (counter0 > n) {
result[i] <- v[i]
} else {
result[i] <- result[i-1]
counter0 <- counter0 + 1
} }
else {
result[i] <- v[i]
counter0 <- 1
}
}
return(result)
}
```
Thanks | 2014/09/19 | [
"https://Stackoverflow.com/questions/25940241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4059416/"
] | The cleanest way to implement this in `data.table` is probably using the join syntax:
```
na.omit(dt)[dt, on = .(date), roll = +3, .(date, x_filled = x, x = i.x)]
date x_filled x
1: 2019-02-14 1 1
2: 2019-02-15 1 NA
3: 2019-02-16 1 NA
4: 2019-02-17 1 NA
5: 2019-02-18 5 5
6: 2019-02-19 5 NA
7: 2019-02-20 5 NA
8: 2019-02-21 5 NA
9: 2019-02-22 NA NA
10: 2019-02-23 NA NA
11: 2019-02-24 11 11
12: 2019-02-25 12 12
13: 2019-02-26 12 NA
14: 2019-02-27 12 NA
15: 2019-02-28 12 NA
16: 2019-03-01 NA NA
17: 2019-03-02 NA NA
18: 2019-03-03 NA NA
19: 2019-03-04 19 19
20: 2019-03-05 20 20
```
\*This solution depends on the date columns and it being contiguous | From playing around in `data.table` comes this hacky solution:
```
np1 <- 3 + 1
dt[,
x_filled := x[c(rep(1, min(np1, .N)), rep(NA, max(0, .N - np1)))],
by = cumsum(!is.na(x))]
# Or slightly simplified:
dt[,
x_filled := ifelse(rowid(x) < 4, x[1], x[NA]),
by = cumsum(!is.na(x))]
> dt
date x x_filled
1: 2019-02-14 1 1
2: 2019-02-15 NA 1
3: 2019-02-16 NA 1
4: 2019-02-17 NA 1
5: 2019-02-18 5 5
6: 2019-02-19 NA 5
7: 2019-02-20 NA 5
8: 2019-02-21 NA 5
9: 2019-02-22 NA NA
10: 2019-02-23 NA NA
11: 2019-02-24 11 11
12: 2019-02-25 12 12
13: 2019-02-26 NA 12
14: 2019-02-27 NA 12
15: 2019-02-28 NA 12
16: 2019-03-01 NA NA
17: 2019-03-02 NA NA
18: 2019-03-03 NA NA
19: 2019-03-04 19 19
20: 2019-03-05 20 20
```
We build on the fact that subsetting vectors with `NA` returns `NA`.
*Data/Packages*
```
library(zoo)
library(data.table)
x <- zoo(1:20, Sys.Date() + 1:20)
x[c(2:4, 6:10, 13:18)] <- NA
dt <- data.table(date = index(x), x = as.integer(x))
``` |
41,772,857 | Have an apparently simple task of -
*Display a list of items using recycler view and each item should be card view.On click of any item new screen should open which shows detail of that item.*
I already have seen various questions posted on the same topic, **I would appreciate a little help on the attempt ive made rather than redirecting me there, since I'm pretty new and unable to understand how exactly to implement just by seeing those answers.I have tried to follow a tutorial closely but clearly have failed in replicating the results.HERE ARE THE FILES**
>
> MainActivity.java
>
>
>
```
. package com.example.hardikvats.recylerviewdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private String[] phones={"MotoX","Nokia Asha","Lumia 710","Iphone 7s"};
private String[] OperatingSytem={"Android","Symbian","Windows","Ios"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RecyclerView recyclerView= (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
MyAdapter adapter=new MyAdapter(this,phones);
recyclerView.setAdapter(adapter);
}
}
```
>
> MyAdapter.java
>
>
>
```
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
String[] phones;
String[] OperatingSystem;
//CONSTRUCTOR
public MyAdapter(Context c, String[] PhoneModel){
this.c=c;
this.phones=PhoneModel;
//this.OperatingSystem=OperatingSystem;
}
@Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//INFLATING FROM XML TO JAVA VIEW
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,null);
MyHolder holder=new MyHolder(v);
return holder;
}
@Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.PhoneModel.setText(phones[position]);
holder.setItemClickListner(new ItemClickListner() {
@Override
public void onItemClick(View v, int position) {
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[position]);
}
});
}
@Override
public int getItemCount() {
return phones.length;
}
}
```
MyHolder.java
```
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView PhoneModel;
ItemClickListner icl;
public MyHolder(View itemView) {
super(itemView);
PhoneModel=(TextView) itemView.findViewById(R.id.MobilePhone);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
this.icl.onItemClick(v,getLayoutPosition());
}
public void setItemClickListner(ItemClickListner itemClickListner){
this.icl=itemClickListner;
}
}
```
>
> DetailActivity.java
>
>
>
```
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity {
TextView OperatingSystem;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail2);
Intent i=getIntent();
final String OperatingSystem =i.getExtras().getString("Operating System");
}
}
```
>
> ItemClickListner.java(Interface)
>
>
>
```
`import android.view.View;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public interface ItemClickListner {
void onItemClick(View v, int position);
}`
```
The goal is to click each list item from phones array and get an activity listing the OS in a new activity in a new textfield | 2017/01/20 | [
"https://Stackoverflow.com/questions/41772857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6603368/"
] | after i.putExtra("OS NAME ....
add this line
```
c.startActivity(c,DetailActivity.class);
``` | ```
//set on item click listener like this
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
Toast.makeText(MainActivity.this, "Card at " + position + " is clicked", Toast.LENGTH_SHORT).show();
// here you can start your detail Activity
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[position]);
c.startActivity(i);
}
}));
// here is the on item click listener class
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
GestureDetector mGestureDetector;
public interface OnItemClickListener{
public void onItemClick(View view, int position);
}
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View childView = rv.findChildViewUnder(e.getX(),e.getY());
if(childView != null && mListener != null && mGestureDetector.onTouchEvent(e)){
mListener.onItemClick(childView, rv.getChildAdapterPosition(childView));
return true;
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override`enter code here`
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
``` |
41,772,857 | Have an apparently simple task of -
*Display a list of items using recycler view and each item should be card view.On click of any item new screen should open which shows detail of that item.*
I already have seen various questions posted on the same topic, **I would appreciate a little help on the attempt ive made rather than redirecting me there, since I'm pretty new and unable to understand how exactly to implement just by seeing those answers.I have tried to follow a tutorial closely but clearly have failed in replicating the results.HERE ARE THE FILES**
>
> MainActivity.java
>
>
>
```
. package com.example.hardikvats.recylerviewdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private String[] phones={"MotoX","Nokia Asha","Lumia 710","Iphone 7s"};
private String[] OperatingSytem={"Android","Symbian","Windows","Ios"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RecyclerView recyclerView= (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
MyAdapter adapter=new MyAdapter(this,phones);
recyclerView.setAdapter(adapter);
}
}
```
>
> MyAdapter.java
>
>
>
```
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
String[] phones;
String[] OperatingSystem;
//CONSTRUCTOR
public MyAdapter(Context c, String[] PhoneModel){
this.c=c;
this.phones=PhoneModel;
//this.OperatingSystem=OperatingSystem;
}
@Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//INFLATING FROM XML TO JAVA VIEW
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,null);
MyHolder holder=new MyHolder(v);
return holder;
}
@Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.PhoneModel.setText(phones[position]);
holder.setItemClickListner(new ItemClickListner() {
@Override
public void onItemClick(View v, int position) {
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[position]);
}
});
}
@Override
public int getItemCount() {
return phones.length;
}
}
```
MyHolder.java
```
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView PhoneModel;
ItemClickListner icl;
public MyHolder(View itemView) {
super(itemView);
PhoneModel=(TextView) itemView.findViewById(R.id.MobilePhone);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
this.icl.onItemClick(v,getLayoutPosition());
}
public void setItemClickListner(ItemClickListner itemClickListner){
this.icl=itemClickListner;
}
}
```
>
> DetailActivity.java
>
>
>
```
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity {
TextView OperatingSystem;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail2);
Intent i=getIntent();
final String OperatingSystem =i.getExtras().getString("Operating System");
}
}
```
>
> ItemClickListner.java(Interface)
>
>
>
```
`import android.view.View;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public interface ItemClickListner {
void onItemClick(View v, int position);
}`
```
The goal is to click each list item from phones array and get an activity listing the OS in a new activity in a new textfield | 2017/01/20 | [
"https://Stackoverflow.com/questions/41772857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6603368/"
] | after i.putExtra("OS NAME ....
add this line
```
c.startActivity(c,DetailActivity.class);
``` | As you did, in order that changes to be small, try this:
```
holder.PhoneModel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[holder.getAdapterPosition()]);
}
});
```
Holder will always retain your position. |
41,772,857 | Have an apparently simple task of -
*Display a list of items using recycler view and each item should be card view.On click of any item new screen should open which shows detail of that item.*
I already have seen various questions posted on the same topic, **I would appreciate a little help on the attempt ive made rather than redirecting me there, since I'm pretty new and unable to understand how exactly to implement just by seeing those answers.I have tried to follow a tutorial closely but clearly have failed in replicating the results.HERE ARE THE FILES**
>
> MainActivity.java
>
>
>
```
. package com.example.hardikvats.recylerviewdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private String[] phones={"MotoX","Nokia Asha","Lumia 710","Iphone 7s"};
private String[] OperatingSytem={"Android","Symbian","Windows","Ios"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RecyclerView recyclerView= (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
MyAdapter adapter=new MyAdapter(this,phones);
recyclerView.setAdapter(adapter);
}
}
```
>
> MyAdapter.java
>
>
>
```
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
String[] phones;
String[] OperatingSystem;
//CONSTRUCTOR
public MyAdapter(Context c, String[] PhoneModel){
this.c=c;
this.phones=PhoneModel;
//this.OperatingSystem=OperatingSystem;
}
@Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//INFLATING FROM XML TO JAVA VIEW
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,null);
MyHolder holder=new MyHolder(v);
return holder;
}
@Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.PhoneModel.setText(phones[position]);
holder.setItemClickListner(new ItemClickListner() {
@Override
public void onItemClick(View v, int position) {
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[position]);
}
});
}
@Override
public int getItemCount() {
return phones.length;
}
}
```
MyHolder.java
```
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView PhoneModel;
ItemClickListner icl;
public MyHolder(View itemView) {
super(itemView);
PhoneModel=(TextView) itemView.findViewById(R.id.MobilePhone);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
this.icl.onItemClick(v,getLayoutPosition());
}
public void setItemClickListner(ItemClickListner itemClickListner){
this.icl=itemClickListner;
}
}
```
>
> DetailActivity.java
>
>
>
```
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity {
TextView OperatingSystem;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail2);
Intent i=getIntent();
final String OperatingSystem =i.getExtras().getString("Operating System");
}
}
```
>
> ItemClickListner.java(Interface)
>
>
>
```
`import android.view.View;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public interface ItemClickListner {
void onItemClick(View v, int position);
}`
```
The goal is to click each list item from phones array and get an activity listing the OS in a new activity in a new textfield | 2017/01/20 | [
"https://Stackoverflow.com/questions/41772857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6603368/"
] | As you did, in order that changes to be small, try this:
```
holder.PhoneModel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[holder.getAdapterPosition()]);
}
});
```
Holder will always retain your position. | ```
//set on item click listener like this
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
Toast.makeText(MainActivity.this, "Card at " + position + " is clicked", Toast.LENGTH_SHORT).show();
// here you can start your detail Activity
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[position]);
c.startActivity(i);
}
}));
// here is the on item click listener class
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
GestureDetector mGestureDetector;
public interface OnItemClickListener{
public void onItemClick(View view, int position);
}
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View childView = rv.findChildViewUnder(e.getX(),e.getY());
if(childView != null && mListener != null && mGestureDetector.onTouchEvent(e)){
mListener.onItemClick(childView, rv.getChildAdapterPosition(childView));
return true;
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override`enter code here`
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
``` |
30,430,927 | I want to extract data from a table on a daily basis and save it in my local machine in a excel sheet. | 2015/05/25 | [
"https://Stackoverflow.com/questions/30430927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4152262/"
] | >
> I want to extract data from a table on a daily basis
>
>
>
You could use **[DBMS\_SCHEDULER](http://oracle-base.com/articles/10g/scheduler-10g.php)** to create a **job** and **schedule** to run daily.
For example, the below job will run every hour:
```
SQL> BEGIN
2 DBMS_SCHEDULER.DROP_JOB (JOB_NAME => 'test_full_job_definition');
3 END;
4 /
PL/SQL procedure successfully completed.
SQL>
SQL> BEGIN
2 DBMS_SCHEDULER.create_job (
3 job_name => 'test_full_job_definition',
4 job_type => 'PLSQL_BLOCK',
5 job_action => 'BEGIN my_job_procedure; END;',
6 start_date => SYSTIMESTAMP,
7 repeat_interval => 'freq=hourly; byminute=0; bysecond=0;',
8 end_date => NULL,
9 enabled => TRUE,
10 comments => 'Job defined entirely by the CREATE JOB procedure.');
11 END;
12 /
PL/SQL procedure successfully completed.
SQL>
SQL> SELECT JOB_NAME, ENABLED FROM DBA_SCHEDULER_JOBS where job_name ='TEST_FULL_JOB_DEFINITION'
2 /
JOB_NAME ENABL
---------------------------------------- -----
TEST_FULL_JOB_DEFINITION TRUE
SQL>
```
>
> save it in my local machine in a excel sheet
>
>
>
This is a *frequently asked question*, and people often get confused between a **CSV** file and a **Microsoft Excel** file. Generating a CSV file could be as easy as to **spool** it using **SQL\*Plus**. For writing the output into an Excel file, you need to do it **programmatically**.
You could use the following [code](https://technology.amis.nl/wp-content/uploads/2011/02/as_xlsx11.txt) developed by [Anton Scheffer](https://technology.amis.nl/2011/02/19/create-an-excel-file-with-plsql/):
```
CREATE OR REPLACE package as_xlsx
is
/**********************************************
**
** Author: Anton Scheffer
** Date: 19-02-2011
** Website: http://technology.amis.nl/blog
** See also: http://technology.amis.nl/blog/?p=10995
**
** Changelog:
** Date: 21-02-2011
** Added Aligment, horizontal, vertical, wrapText
** Date: 06-03-2011
** Added Comments, MergeCells, fixed bug for dependency on NLS-settings
** Date: 16-03-2011
** Added bold and italic fonts
** Date: 22-03-2011
** Fixed issue with timezone's set to a region(name) instead of a offset
** Date: 08-04-2011
** Fixed issue with XML-escaping from text
** Date: 27-05-2011
** Added MIT-license
** Date: 11-08-2011
** Fixed NLS-issue with column width
** Date: 29-09-2011
** Added font color
** Date: 16-10-2011
** fixed bug in add_string
** Date: 26-04-2012
** Fixed set_autofilter (only one autofilter per sheet, added _xlnm._FilterDatabase)
** Added list_validation = drop-down
** Date: 27-08-2013
** Added freeze_pane
**
******************************************************************************
******************************************************************************
Copyright (C) 2011, 2012 by Anton Scheffer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
******************************************************************************
******************************************** */
--
type tp_alignment is record
( vertical varchar2(11)
, horizontal varchar2(16)
, wrapText boolean
);
--
procedure clear_workbook;
--
procedure new_sheet( p_sheetname varchar2 := null );
--
function OraFmt2Excel( p_format varchar2 := null )
return varchar2;
--
function get_numFmt( p_format varchar2 := null )
return pls_integer;
--
function get_font
( p_name varchar2
, p_family pls_integer := 2
, p_fontsize number := 11
, p_theme pls_integer := 1
, p_underline boolean := false
, p_italic boolean := false
, p_bold boolean := false
, p_rgb varchar2 := null -- this is a hex ALPHA Red Green Blue value
)
return pls_integer;
--
function get_fill
( p_patternType varchar2
, p_fgRGB varchar2 := null -- this is a hex ALPHA Red Green Blue value
)
return pls_integer;
--
function get_border
( p_top varchar2 := 'thin'
, p_bottom varchar2 := 'thin'
, p_left varchar2 := 'thin'
, p_right varchar2 := 'thin'
)
/*
none
thin
medium
dashed
dotted
thick
double
hair
mediumDashed
dashDot
mediumDashDot
dashDotDot
mediumDashDotDot
slantDashDot
*/
return pls_integer;
--
function get_alignment
( p_vertical varchar2 := null
, p_horizontal varchar2 := null
, p_wrapText boolean := null
)
/* horizontal
center
centerContinuous
distributed
fill
general
justify
left
right
*/
/* vertical
bottom
center
distributed
justify
top
*/
return tp_alignment;
--
procedure cell
( p_col pls_integer
, p_row pls_integer
, p_value number
, p_numFmtId pls_integer := null
, p_fontId pls_integer := null
, p_fillId pls_integer := null
, p_borderId pls_integer := null
, p_alignment tp_alignment := null
, p_sheet pls_integer := null
);
--
procedure cell
( p_col pls_integer
, p_row pls_integer
, p_value varchar2
, p_numFmtId pls_integer := null
, p_fontId pls_integer := null
, p_fillId pls_integer := null
, p_borderId pls_integer := null
, p_alignment tp_alignment := null
, p_sheet pls_integer := null
);
--
procedure cell
( p_col pls_integer
, p_row pls_integer
, p_value date
, p_numFmtId pls_integer := null
, p_fontId pls_integer := null
, p_fillId pls_integer := null
, p_borderId pls_integer := null
, p_alignment tp_alignment := null
, p_sheet pls_integer := null
);
--
procedure hyperlink
( p_col pls_integer
, p_row pls_integer
, p_url varchar2
, p_value varchar2 := null
, p_sheet pls_integer := null
);
--
procedure comment
( p_col pls_integer
, p_row pls_integer
, p_text varchar2
, p_author varchar2 := null
, p_width pls_integer := 150 -- pixels
, p_height pls_integer := 100 -- pixels
, p_sheet pls_integer := null
);
--
procedure mergecells
( p_tl_col pls_integer -- top left
, p_tl_row pls_integer
, p_br_col pls_integer -- bottom right
, p_br_row pls_integer
, p_sheet pls_integer := null
);
--
procedure list_validation
( p_sqref_col pls_integer
, p_sqref_row pls_integer
, p_tl_col pls_integer -- top left
, p_tl_row pls_integer
, p_br_col pls_integer -- bottom right
, p_br_row pls_integer
, p_style varchar2 := 'stop' -- stop, warning, information
, p_title varchar2 := null
, p_prompt varchar := null
, p_show_error boolean := false
, p_error_title varchar2 := null
, p_error_txt varchar2 := null
, p_sheet pls_integer := null
);
--
procedure list_validation
( p_sqref_col pls_integer
, p_sqref_row pls_integer
, p_defined_name varchar2
, p_style varchar2 := 'stop' -- stop, warning, information
, p_title varchar2 := null
, p_prompt varchar := null
, p_show_error boolean := false
, p_error_title varchar2 := null
, p_error_txt varchar2 := null
, p_sheet pls_integer := null
);
--
procedure defined_name
( p_tl_col pls_integer -- top left
, p_tl_row pls_integer
, p_br_col pls_integer -- bottom right
, p_br_row pls_integer
, p_name varchar2
, p_sheet pls_integer := null
, p_localsheet pls_integer := null
);
--
procedure set_column_width
( p_col pls_integer
, p_width number
, p_sheet pls_integer := null
);
--
procedure set_column
( p_col pls_integer
, p_numFmtId pls_integer := null
, p_fontId pls_integer := null
, p_fillId pls_integer := null
, p_borderId pls_integer := null
, p_alignment tp_alignment := null
, p_sheet pls_integer := null
);
--
procedure set_row
( p_row pls_integer
, p_numFmtId pls_integer := null
, p_fontId pls_integer := null
, p_fillId pls_integer := null
, p_borderId pls_integer := null
, p_alignment tp_alignment := null
, p_sheet pls_integer := null
);
--
procedure freeze_rows
( p_nr_rows pls_integer := 1
, p_sheet pls_integer := null
);
--
procedure freeze_cols
( p_nr_cols pls_integer := 1
, p_sheet pls_integer := null
);
--
procedure freeze_pane
( p_col pls_integer
, p_row pls_integer
, p_sheet pls_integer := null
);
--
procedure set_autofilter
( p_column_start pls_integer := null
, p_column_end pls_integer := null
, p_row_start pls_integer := null
, p_row_end pls_integer := null
, p_sheet pls_integer := null
);
--
function finish
return blob;
--
procedure save
( p_directory varchar2
, p_filename varchar2
);
--
procedure query2sheet
( p_sql varchar2
, p_column_headers boolean := true
, p_directory varchar2 := null
, p_filename varchar2 := null
, p_sheet pls_integer := null
);
```
**Note :** It is a huge code with more than 90k PL/SQL lines of code, so I can't post the entire code here due to restriction of 30k characters. Only posting the important procedures, functions and the package details. Please follow the code link to get the entire code. | the least demanding way would be to daly insert table data into some temp table by some scheduled job
```
create table myexportable as (select sysdate exportdate, q.* from mytable q)
```
resp.
```
insert into myexportable (select sysdate exportdate, q.* from mytable q)
```
and then export that data using SQL Plus
```
set serveroutput on;
set linesize 10000;
set pagesize 10000;
set heading off;
set feed 0;
set trimspool on;
set colsep '|';
spool exptable.out;
select * from myexportable where trunc(exportdate) = trunc(sysdate)
/
quit;
```
and them at least import pipe delimited text file into excel. |
23,362,621 | I have stored date field at DB.
In PHP, i am getting that field and converted into date.
I want to compare that time with current time. If that difference is above 60 minutes. It will return some value.
I dont know how to write logic for that
```
$lastUpdatedField = $rows_fetch['lastUpdatedTime'];
$lastUpdatedDate = new DateTime($lastUpdatedField);
$nowDate = new DateTime(date('y-m-d h:m:s'));
```
I have old date&time is in $lastUpdatedDate variable, and current time is in $nowDate.
How to compare these two | 2014/04/29 | [
"https://Stackoverflow.com/questions/23362621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3584927/"
] | ```
$interval = $nowDate->diff($lastUpdatedDate);
echo $interval->h;
```
DateDiff: <http://www.php.net/manual/en/datetime.diff.php>
DateInterval: <http://www.php.net/manual/en/class.dateinterval.php> | First convert the current time and old time to one unit like Unix timestamp passing it through strtotime(). Then differentiate both the timestamp to get the difference between two times.
```
$difftime = strtotime(date('Y-m-d H:i:s')) - strtotime($rows_fetch['lastUpdatedTime']);
```
Then convert the difference to days as follows :
```
$days=$difftime/24*60*60;
```
Once you get the days you can get the minutes from it as below to compare to meet your need.
```
$timediff = $days * 24 * 60;
``` |
23,362,621 | I have stored date field at DB.
In PHP, i am getting that field and converted into date.
I want to compare that time with current time. If that difference is above 60 minutes. It will return some value.
I dont know how to write logic for that
```
$lastUpdatedField = $rows_fetch['lastUpdatedTime'];
$lastUpdatedDate = new DateTime($lastUpdatedField);
$nowDate = new DateTime(date('y-m-d h:m:s'));
```
I have old date&time is in $lastUpdatedDate variable, and current time is in $nowDate.
How to compare these two | 2014/04/29 | [
"https://Stackoverflow.com/questions/23362621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3584927/"
] | ```
$interval = $nowDate->diff($lastUpdatedDate);
echo $interval->h;
```
DateDiff: <http://www.php.net/manual/en/datetime.diff.php>
DateInterval: <http://www.php.net/manual/en/class.dateinterval.php> | Had The same problem earlier its actually quit simple
heres the piece where you declare your variables
```
$lastUpdateddate = new DateTime($lastUpdatedField);
$nowDate = new DateTime(date('y-m-d h:m:s'));
```
Then you have to convert them to second - format so that you can do math with them
To do that use strtotime
```
$Diff = strtotime($lastUpdatedDate) - strtotime($nowDate);
```
Then just check to see if the difference in time is more then 60 minutes,
So devide by 60 seconds to get minutes and by 60 to get hours
```
if ($diff/60/60 <= 1){
//do your thing here
{
``` |
32,104,533 | OK so I'm trying to design a simple program that checks to see if a substring of length 4 characters is within all initial strings. Here is my code as follows:
```
public class StringSearch{
private String[] s1Array = {"A","C","T","G","A","C","G","C","A","G"};
private String[] s2Array = {"T","C","A","C","A","A","C","G","G","G"};
private String[] s3Array = {"G","A","G","T","C","C","A","G","T","T"};
//{for (int i = 0; i < s1Array.length; i++){
// System.out.print(s1Array[i]);
//}}//check if Array loaded correctly
/**
* This is the search method.
*
* @param length length of sub string to search
* @param count counter for search engine
* @param i for-loop counter
* @return subStr returns strings of length = 4 that are found in all 3 input strings with at most
* one mismatched position.
*/
public String Search()
{
int length = 4;
int count = 0;
int i = 0;
ArrayList<StringSearch> subStr = new ArrayList<StringSearch>();
//String[] subStr = new String[4];
do
{
for (i = count; i < length; i++){
subStr.add(s1Array[i]); // cant find .add method???
count = count + 1;
}
if (s2Array.contains(subStr) && s3Array.contains(subStr)){ //can't find .contains method???
System.out.println(subStr + "is in all 3 lists.");
}
if (count = s1Array.length){
System.out.println("Task complete.");
}
else{
count = count - length;
count = count + 1;
}
}while (count <= s1Array.length);
}
```
}
For some reason, Java cannot seem to find the .add or .contains methods and I have no idea why. So my approach was to turn the initial Strings each into an array (since the assignment specified each string would be exactly N elements long, in this case N = 10) where 1 letter would be 1 element. The next thing I did was set up a for loop that would scan s1Array and add the first 4 elements to an ArrayList subStr which is used to search s2Array and s3Array. Here is where .add isn't a valid method, for whatever reason. Commenting that out and compiling again, I also ran into an issue with the .contains method not being a valid method. Why won't this work? What am I missing? Logically, it seems to make sense but I guess maybe I'm missing something in the syntax? Help would be appreciated, as I'm a Java novice. | 2015/08/19 | [
"https://Stackoverflow.com/questions/32104533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4687940/"
] | There are lots of errors and misunderstandings here.
Let's start with **#1**
```
private String[] s1Array = {"A","C","T","G","A","C","G","C","A","G"};
```
Making an array of strings is just silly, you should either use a single string or an array of characters.
```
private String s1 = "ACTGACGCAG";
```
Or
```
private char[] s1Array = {'A','C','T','G','A','C','G','C','A','G'};
```
Now **#2**
```
ArrayList<StringSearch> subStr = new ArrayList<StringSearch>();
```
This means you are trying to make an ArrayList that contains objects of type StringSearch. StringSearch is a class that contains your three arrays and your Search function so I don't think this is what you want.
If you wanted to make a list of 3 strings you might do something like this:
```
ArrayList<String> stringList = new ArrayList<String>();
stringList.add(s1);
stringList.add(s2);
stringList.add(s3);
```
Now say you defined s1, s2 and s3 as strings you can do something like this.
```
for(int i = 0; i <= s1.length() - 4; i++)
{
String subStr = s1.substring(i, i + 4);
if(s2.contains(subStr) && s3.contains(subStr))
{
System.out.println(subStr + " is in all 3 lists.");
}
}
System.out.println("Task Complete.");
```
The above code should achieve what it looks like you are trying to do. However, it should be noted that this isn't the most efficient way, just a way, of doing it. You should start with some more basic concepts judging by the code you have so far. | After declaring subStr as ArrayList you can call add or contains only with StringSearch objects as parameters. |
32,104,533 | OK so I'm trying to design a simple program that checks to see if a substring of length 4 characters is within all initial strings. Here is my code as follows:
```
public class StringSearch{
private String[] s1Array = {"A","C","T","G","A","C","G","C","A","G"};
private String[] s2Array = {"T","C","A","C","A","A","C","G","G","G"};
private String[] s3Array = {"G","A","G","T","C","C","A","G","T","T"};
//{for (int i = 0; i < s1Array.length; i++){
// System.out.print(s1Array[i]);
//}}//check if Array loaded correctly
/**
* This is the search method.
*
* @param length length of sub string to search
* @param count counter for search engine
* @param i for-loop counter
* @return subStr returns strings of length = 4 that are found in all 3 input strings with at most
* one mismatched position.
*/
public String Search()
{
int length = 4;
int count = 0;
int i = 0;
ArrayList<StringSearch> subStr = new ArrayList<StringSearch>();
//String[] subStr = new String[4];
do
{
for (i = count; i < length; i++){
subStr.add(s1Array[i]); // cant find .add method???
count = count + 1;
}
if (s2Array.contains(subStr) && s3Array.contains(subStr)){ //can't find .contains method???
System.out.println(subStr + "is in all 3 lists.");
}
if (count = s1Array.length){
System.out.println("Task complete.");
}
else{
count = count - length;
count = count + 1;
}
}while (count <= s1Array.length);
}
```
}
For some reason, Java cannot seem to find the .add or .contains methods and I have no idea why. So my approach was to turn the initial Strings each into an array (since the assignment specified each string would be exactly N elements long, in this case N = 10) where 1 letter would be 1 element. The next thing I did was set up a for loop that would scan s1Array and add the first 4 elements to an ArrayList subStr which is used to search s2Array and s3Array. Here is where .add isn't a valid method, for whatever reason. Commenting that out and compiling again, I also ran into an issue with the .contains method not being a valid method. Why won't this work? What am I missing? Logically, it seems to make sense but I guess maybe I'm missing something in the syntax? Help would be appreciated, as I'm a Java novice. | 2015/08/19 | [
"https://Stackoverflow.com/questions/32104533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4687940/"
] | There are lots of errors and misunderstandings here.
Let's start with **#1**
```
private String[] s1Array = {"A","C","T","G","A","C","G","C","A","G"};
```
Making an array of strings is just silly, you should either use a single string or an array of characters.
```
private String s1 = "ACTGACGCAG";
```
Or
```
private char[] s1Array = {'A','C','T','G','A','C','G','C','A','G'};
```
Now **#2**
```
ArrayList<StringSearch> subStr = new ArrayList<StringSearch>();
```
This means you are trying to make an ArrayList that contains objects of type StringSearch. StringSearch is a class that contains your three arrays and your Search function so I don't think this is what you want.
If you wanted to make a list of 3 strings you might do something like this:
```
ArrayList<String> stringList = new ArrayList<String>();
stringList.add(s1);
stringList.add(s2);
stringList.add(s3);
```
Now say you defined s1, s2 and s3 as strings you can do something like this.
```
for(int i = 0; i <= s1.length() - 4; i++)
{
String subStr = s1.substring(i, i + 4);
if(s2.contains(subStr) && s3.contains(subStr))
{
System.out.println(subStr + " is in all 3 lists.");
}
}
System.out.println("Task Complete.");
```
The above code should achieve what it looks like you are trying to do. However, it should be noted that this isn't the most efficient way, just a way, of doing it. You should start with some more basic concepts judging by the code you have so far. | Instead of:
```
ArrayList<StringSearch> subStr = new ArrayList<StringSearch>();
```
Replace it with:
```
String subStr = "";
```
And within the for loop to get the first 4 letters in s1 to be in its own string (subStr) add the line:
```
subStr += s1Array[i];
```
Also, s1Array is a String array, and not a String. The .contains method is a method that belongs to String variables, so for eg. the way you have it implemented, you can say s1Array[i].contains. But you cannot say s1Array.contains. If you change your String arrays to Strings and edit your code to suit, everything should work the way you expect it to work. |
32,104,533 | OK so I'm trying to design a simple program that checks to see if a substring of length 4 characters is within all initial strings. Here is my code as follows:
```
public class StringSearch{
private String[] s1Array = {"A","C","T","G","A","C","G","C","A","G"};
private String[] s2Array = {"T","C","A","C","A","A","C","G","G","G"};
private String[] s3Array = {"G","A","G","T","C","C","A","G","T","T"};
//{for (int i = 0; i < s1Array.length; i++){
// System.out.print(s1Array[i]);
//}}//check if Array loaded correctly
/**
* This is the search method.
*
* @param length length of sub string to search
* @param count counter for search engine
* @param i for-loop counter
* @return subStr returns strings of length = 4 that are found in all 3 input strings with at most
* one mismatched position.
*/
public String Search()
{
int length = 4;
int count = 0;
int i = 0;
ArrayList<StringSearch> subStr = new ArrayList<StringSearch>();
//String[] subStr = new String[4];
do
{
for (i = count; i < length; i++){
subStr.add(s1Array[i]); // cant find .add method???
count = count + 1;
}
if (s2Array.contains(subStr) && s3Array.contains(subStr)){ //can't find .contains method???
System.out.println(subStr + "is in all 3 lists.");
}
if (count = s1Array.length){
System.out.println("Task complete.");
}
else{
count = count - length;
count = count + 1;
}
}while (count <= s1Array.length);
}
```
}
For some reason, Java cannot seem to find the .add or .contains methods and I have no idea why. So my approach was to turn the initial Strings each into an array (since the assignment specified each string would be exactly N elements long, in this case N = 10) where 1 letter would be 1 element. The next thing I did was set up a for loop that would scan s1Array and add the first 4 elements to an ArrayList subStr which is used to search s2Array and s3Array. Here is where .add isn't a valid method, for whatever reason. Commenting that out and compiling again, I also ran into an issue with the .contains method not being a valid method. Why won't this work? What am I missing? Logically, it seems to make sense but I guess maybe I'm missing something in the syntax? Help would be appreciated, as I'm a Java novice. | 2015/08/19 | [
"https://Stackoverflow.com/questions/32104533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4687940/"
] | There are lots of errors and misunderstandings here.
Let's start with **#1**
```
private String[] s1Array = {"A","C","T","G","A","C","G","C","A","G"};
```
Making an array of strings is just silly, you should either use a single string or an array of characters.
```
private String s1 = "ACTGACGCAG";
```
Or
```
private char[] s1Array = {'A','C','T','G','A','C','G','C','A','G'};
```
Now **#2**
```
ArrayList<StringSearch> subStr = new ArrayList<StringSearch>();
```
This means you are trying to make an ArrayList that contains objects of type StringSearch. StringSearch is a class that contains your three arrays and your Search function so I don't think this is what you want.
If you wanted to make a list of 3 strings you might do something like this:
```
ArrayList<String> stringList = new ArrayList<String>();
stringList.add(s1);
stringList.add(s2);
stringList.add(s3);
```
Now say you defined s1, s2 and s3 as strings you can do something like this.
```
for(int i = 0; i <= s1.length() - 4; i++)
{
String subStr = s1.substring(i, i + 4);
if(s2.contains(subStr) && s3.contains(subStr))
{
System.out.println(subStr + " is in all 3 lists.");
}
}
System.out.println("Task Complete.");
```
The above code should achieve what it looks like you are trying to do. However, it should be noted that this isn't the most efficient way, just a way, of doing it. You should start with some more basic concepts judging by the code you have so far. | First of all you need to educate yourself on the concept of Java generics.
The most basic thing about generics is that once you declare a collection, here it is the arraylist, as you can only add objects of StringSearch.
Second of all, logically what you can do is to implement an algorithm called
[Longest Common Subsequence.](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem) Check in pairs whether the longest subsequeces are 4 or not on the arrays. |
55,174,252 | So I have a form on a web page and I need to send the data to a php file. That much is okay - BUT there is a part of the form that can be added dynamically (using JavaScript) and so I need JavaScript to get this data and convert it to JSON (or any other format) and send to to the PHP file, preferably using POST.
My question is; how can I submit the form to PHP and then parse the specific area with JavaScript and then send that to the PHP form? Below is what I have:
```
<form id="dataForm" action="summary.php" method="post" onSubmit="parseData(this)">
<div className="actorDivHTML">
<div className="actorInfoDiv"> //can be added dynamically
//dynamic <input className="actorInfo"> goes here
</div>
</div>
</form>
```
JavaScript (in a seperate file called "scripts.js" - declared at top of HTML page)
```
function parseData( form ) {
var form = formID;
//list of divs with this class name - dynamically added
var infoDivs = form.getElementsByClassName( "actorInfoDiv" );
var info = [];
//loop through each div and append the raw data
for ( i = 0; i < infoDivs.length; i++ ) {
info.push( [ ...infoDivs[ i ].getElementsByClassName( "actorInfo" ) ] );
}
//extract the value of the input from the raw data
var extractedInfo = [];
for ( j = 0; j < info.length; j++ ) {
var ind = [];
for ( k = 0; k < info[ j ].length; k++ ) {
ind.push( info[ j ][ k ].value );
}
extractedInfo.push( ind );
}
// $.post('/summary.php',{array: JSON.stringify(extractedInfo)}); - first attepmt
console.log( extractedInfo );
//POST to PHP
request = new XMLHttpRequest();
request.open( "POST", "summary.php", true );
request.setRequestHeader( "Content-type", "application/json" );
request.send( JSON.stringify( extractedInfo ) );
}
```
And the PHP file - which obviously doesn't get the JSON data as I would like
```
//gets all other form data
$str_json = file_get_contents( 'php://input' );
print_r( $str_json );
//continues to get all other form data
```
Happy to clarify and post more code!
Cheers!
EDIT1 - K3lly:
So my HTML file now looks like this:
```
<form id="dataForm" onSubmit="onSub()">
<input type="submit" name="submit_button" value="Submit">
<script src="https://code.jquery.com/jquery-1.10.2.js">
function onSub(){
$("#dataForm").submit(function(event){
event.preventDefault();
var data = $("#dataForm").serializeArray();
//POST to PHP
$.ajax({
type: "POST",
url: "summary.php",
data: JSON.Stringify(data),
success: function(response){
//Do whatever you want when form is sent.
},
dataType: "JSON"
});
});
}
</script>
```
And PHP:
```
echo json_decode($_POST);
```
However, when the submit button is clicked the URL shows all the form data like `GET` would and the summary.php page is never loaded? The URL also doesn't show any of the dynamically added inputs.
EDIT 2 - k3lly:
```
$("#dataForm").submit(function(event){
event.preventDefault();
//var serData = $("#dataForm").serialize();
var test = $("#title").val();
var serData = 'test1='+test;
//POST to PHP
$.ajax({
type: "POST",
url: "summary.php",
data: serData,
success: function(response){
//Do whatever you want when form is sent.
},
dataType: "JSON"
});
```
In the PHP file:
```
$test = $_POST["test1"];
echo $test;
```
There is no output. What am I doing wrong? | 2019/03/15 | [
"https://Stackoverflow.com/questions/55174252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6634934/"
] | Since you are using jQuery as far I can see in your code, the solution to do this is a lot simpler.
Your JavaScript code will be as simple as:
```
$("#dataForm").submit(function(event){
event.preventDefault();
var data = $("#dataForm").serializeArray();
//POST to PHP
$.ajax({
type: "POST",
url: "summary.php",
data: JSON.Stringify(data),
success: function(response){
//Do whatever you want when form is sent.
},
dataType: "JSON"
});
});
```
After this, just make sure to read your POST data correctly with `json_decode()` in PHP. Try some debbuging first to see what you are getting server-side by echoing the entire POST result. | If you're passing the data via your JavaScript's `XMLHttpRequest`, then you don't need the form to be submitted - add an event listener and use `preventDefault` through JavaScript, and use `document.getElementById` to get the form:
```
<form id="dataForm">
<!-- Your form data here
</form>
```
JS:
```
function parseData() {
var form = formID;
//list of divs with this class name - dynamically added
var infoDivs = form.getElementsByClassName( "actorInfoDiv" );
var info = [];
//loop through each div and append the raw data
for ( i = 0; i < infoDivs.length; i++ ) {
info.push( [ ...infoDivs[ i ].getElementsByClassName( "actorInfo" ) ] );
}
//extract the value of the input from the raw data
var extractedInfo = [];
for ( j = 0; j < info.length; j++ ) {
var ind = [];
for ( k = 0; k < info[ j ].length; k++ ) {
ind.push( info[ j ][ k ].value );
}
extractedInfo.push( ind );
}
// $.post('/summary.php',{array: JSON.stringify(extractedInfo)}); - first attepmt
console.log( extractedInfo );
//POST to PHP
request = new XMLHttpRequest();
request.open( "POST", "summary.php", true );
request.setRequestHeader( "Content-type", "application/json" );
request.send( JSON.stringify( extractedInfo ) );
}
document.getElementById("dataForm").addEventListener("submit", e => {
e.preventDefault();
parseData();
});
``` |
51,079,921 | I am using JFrog Artifactory OSS Docker image version 6.0.0 to create the repository in Amazon Linux. The issue I was facing is the Artifactory is not coming up. The docker container is up, but I verified the localhost logs it's showing error as
```
java.lang.RuntimeException: master.key file is missing - timed out while waiting for master.key after 60 seconds. Please provide it manually`
java.lang.IllegalStateException: Artifactory home not initialized`
```
But the starting line of localhost log shows
```
org.apache.catalina.core.ApplicationContext.log Using artifactory.home at '/opt/jfrog/artifactory' resolved from: System property
```
Any help is much appreciated as I was new to JFrog Artifactory. | 2018/06/28 | [
"https://Stackoverflow.com/questions/51079921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4008934/"
] | One of the purposes of the master.key is to make sure an Artifactory server is not connected to a DB of another Artifactory server.
When starting up a new Artifactory server, this means with a clean DB, it creates the master.key. In your case, it looks like you are trying to connect to a DB that was already serving another Artifactory server.
Therefore you need to copy over the master.key (available at $ARTIFACTORY\_HOME/etc/security/) from the Artifactory server that used this DB.
In case this is a new setup, you need to connect to a clean DB. | It could be due to the slowness of your docker host.
On my local machine, when I fire:
```
docker run --name artifactory -p 8081:8081 docker.bintray.io/jfrog/artifactory-oss:6.0.0
```
it loads everything in 27 seconds (Core i5 4th gen, 8GB RAM, no SSD) |
4,725,789 | I am using the following code to expand and center on div on :hover
```
$(document).ready(function(){
//animation on hover
$('#sliding_grid li').hover(function() {
$(this).addClass('highlight');
}, function() {
//$(this).removeClass('highlight');
});
$(".highlight").live("hover", function(){
$(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"-94px", "margin-left":"-152px"}, 500);
});
$(".highlight").live("mouseout", function(){
$(this).animate({"width": "148px", "height":"90px", "top: ":"0px", "left":"0px", "margin-top: ":"0", "margin-left":"0"}, 500, function(){
$(this).removeClass('highlight');
});
});
});
```
My problem is two things:
1) I'm not sure how to reset the "top" and "left" css coordinates to their original value on mouseOut. To see a working demo, go here:
<http://jsfiddle.net/kTFvj/1/>
2) The z-index (see here: <http://jsfiddle.net/kTFvj/1/>) is not affecting the :hovered grid elements. Not sure why. | 2011/01/18 | [
"https://Stackoverflow.com/questions/4725789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/187750/"
] | You can use jQuerys [.data](http://api.jquery.com/data/) method to store the original values and retrieve them on mouseout
I have made a modification to your original code that might work like you wish.. it uses .data and also updates the z-index so the active element is always on top
<http://jsfiddle.net/kTFvj/2/> | What about using % instead of pixels?
Another solution is saving the actual value of width and height in some vars and restoring on mouse out. |
4,725,789 | I am using the following code to expand and center on div on :hover
```
$(document).ready(function(){
//animation on hover
$('#sliding_grid li').hover(function() {
$(this).addClass('highlight');
}, function() {
//$(this).removeClass('highlight');
});
$(".highlight").live("hover", function(){
$(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"-94px", "margin-left":"-152px"}, 500);
});
$(".highlight").live("mouseout", function(){
$(this).animate({"width": "148px", "height":"90px", "top: ":"0px", "left":"0px", "margin-top: ":"0", "margin-left":"0"}, 500, function(){
$(this).removeClass('highlight');
});
});
});
```
My problem is two things:
1) I'm not sure how to reset the "top" and "left" css coordinates to their original value on mouseOut. To see a working demo, go here:
<http://jsfiddle.net/kTFvj/1/>
2) The z-index (see here: <http://jsfiddle.net/kTFvj/1/>) is not affecting the :hovered grid elements. Not sure why. | 2011/01/18 | [
"https://Stackoverflow.com/questions/4725789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/187750/"
] | You can use jQuerys [.data](http://api.jquery.com/data/) method to store the original values and retrieve them on mouseout
I have made a modification to your original code that might work like you wish.. it uses .data and also updates the z-index so the active element is always on top
<http://jsfiddle.net/kTFvj/2/> | 1. as Martin said, store the values when the animation begins using a variable, and restore when done.
2. about z-Index: just have a variable called maxZIndex=0
and everytime an animation begins, set the object's zIndex property to maxZIndex++ |
4,725,789 | I am using the following code to expand and center on div on :hover
```
$(document).ready(function(){
//animation on hover
$('#sliding_grid li').hover(function() {
$(this).addClass('highlight');
}, function() {
//$(this).removeClass('highlight');
});
$(".highlight").live("hover", function(){
$(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"-94px", "margin-left":"-152px"}, 500);
});
$(".highlight").live("mouseout", function(){
$(this).animate({"width": "148px", "height":"90px", "top: ":"0px", "left":"0px", "margin-top: ":"0", "margin-left":"0"}, 500, function(){
$(this).removeClass('highlight');
});
});
});
```
My problem is two things:
1) I'm not sure how to reset the "top" and "left" css coordinates to their original value on mouseOut. To see a working demo, go here:
<http://jsfiddle.net/kTFvj/1/>
2) The z-index (see here: <http://jsfiddle.net/kTFvj/1/>) is not affecting the :hovered grid elements. Not sure why. | 2011/01/18 | [
"https://Stackoverflow.com/questions/4725789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/187750/"
] | 1. as Martin said, store the values when the animation begins using a variable, and restore when done.
2. about z-Index: just have a variable called maxZIndex=0
and everytime an animation begins, set the object's zIndex property to maxZIndex++ | What about using % instead of pixels?
Another solution is saving the actual value of width and height in some vars and restoring on mouse out. |
13,288,735 | I am on windows environment and using maven to compile my project. Although I just created the project and added the dependencies for various libararies.
As I added them maven started complaining for the missing `tools.jar`, so i added below to my `pom.xml`:
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
```
When i ran the maven install, i got an error for the missing jar as below :
```
[ERROR] Failed to execute goal on project GApp: Could not resolve dependencies for project GApp:GApp:war:0.0.1-SNAPSHOT: Could not find artifact com.sun:tools:jar:1.6 at specified path C:\Program Files\Java\jre6\lib\tools.jar -> [Help 1]
```
The issue is that the `tools.jar` is in "`C:\Program Files\Java\jdk1.6.0_26\lib`" and is correctly set in the `JAVA_HOME` environment variable but the maven is still looking in jre folder as in error message "`C:\Program Files\Java\jre6\lib\tools.jar`".
```
C:\>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.6.0_26
```
**Interestingly**: when i set the full path in dependency, it worked just fine. But i don't want to hard code it.
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>C:\Program Files\Java\jdk1.6.0_26\lib\tools.jar</systemPath>
</dependency>
```
Can someone suggest any dynamic solution for this? | 2012/11/08 | [
"https://Stackoverflow.com/questions/13288735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129313/"
] | When you add the JAVA\_HOME environment variable, if there are spaces in the path you must wrap the whole thing in quotes. | Sounds like you are running Maven in Eclipse. Eclipse does not consult JAVA\_HOME.
Make sure you have set your JRE in Eclipse preferences to your desired JDK. |
13,288,735 | I am on windows environment and using maven to compile my project. Although I just created the project and added the dependencies for various libararies.
As I added them maven started complaining for the missing `tools.jar`, so i added below to my `pom.xml`:
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
```
When i ran the maven install, i got an error for the missing jar as below :
```
[ERROR] Failed to execute goal on project GApp: Could not resolve dependencies for project GApp:GApp:war:0.0.1-SNAPSHOT: Could not find artifact com.sun:tools:jar:1.6 at specified path C:\Program Files\Java\jre6\lib\tools.jar -> [Help 1]
```
The issue is that the `tools.jar` is in "`C:\Program Files\Java\jdk1.6.0_26\lib`" and is correctly set in the `JAVA_HOME` environment variable but the maven is still looking in jre folder as in error message "`C:\Program Files\Java\jre6\lib\tools.jar`".
```
C:\>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.6.0_26
```
**Interestingly**: when i set the full path in dependency, it worked just fine. But i don't want to hard code it.
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>C:\Program Files\Java\jdk1.6.0_26\lib\tools.jar</systemPath>
</dependency>
```
Can someone suggest any dynamic solution for this? | 2012/11/08 | [
"https://Stackoverflow.com/questions/13288735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129313/"
] | Maven ${java.home} property is set and taken from different places depending your Eclipse execution:
* from the default JRE selected for the workspace
>
> Window>Preferences>Java>Installed JREs
>
>
>
* from the specific Eclipse project,
>
> Java Build Path>Libraries>JRE System Library
>
>
>
* from the Run configuration.
>
> Run Configurations> Specific Run Configuration > JRE
>
>
>
Remember your JRE home paths points to a JDK or JRE under JDK | When you add the JAVA\_HOME environment variable, if there are spaces in the path you must wrap the whole thing in quotes. |
13,288,735 | I am on windows environment and using maven to compile my project. Although I just created the project and added the dependencies for various libararies.
As I added them maven started complaining for the missing `tools.jar`, so i added below to my `pom.xml`:
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
```
When i ran the maven install, i got an error for the missing jar as below :
```
[ERROR] Failed to execute goal on project GApp: Could not resolve dependencies for project GApp:GApp:war:0.0.1-SNAPSHOT: Could not find artifact com.sun:tools:jar:1.6 at specified path C:\Program Files\Java\jre6\lib\tools.jar -> [Help 1]
```
The issue is that the `tools.jar` is in "`C:\Program Files\Java\jdk1.6.0_26\lib`" and is correctly set in the `JAVA_HOME` environment variable but the maven is still looking in jre folder as in error message "`C:\Program Files\Java\jre6\lib\tools.jar`".
```
C:\>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.6.0_26
```
**Interestingly**: when i set the full path in dependency, it worked just fine. But i don't want to hard code it.
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>C:\Program Files\Java\jdk1.6.0_26\lib\tools.jar</systemPath>
</dependency>
```
Can someone suggest any dynamic solution for this? | 2012/11/08 | [
"https://Stackoverflow.com/questions/13288735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129313/"
] | You should NEVER use system scope dependencies. All the code in tools.jar will be available just via the running JVM already. You should remove this dependency altogether..
Also in order to check what runtime Maven is using just call
```
mvn -v
```
If you are still having a dependency to the tools jar as a problem, one of the dependencies you added has that dependency (and it is really bad quality). To find out which one it is run
```
mvn dependency:tree
```
or if that fails just remove one dependency after another until the problems is gone for the command above.
Then, when you know where it comes from you can decide what to do next. One path would be to use an exclusion on the dependency that pull tools in. | Also look in the .mavenrc file in your home dir.
This caught me off guard.
I changed everything as suggested only to find that my .mavenrc file set the JAVA\_HOME to an older version. |
13,288,735 | I am on windows environment and using maven to compile my project. Although I just created the project and added the dependencies for various libararies.
As I added them maven started complaining for the missing `tools.jar`, so i added below to my `pom.xml`:
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
```
When i ran the maven install, i got an error for the missing jar as below :
```
[ERROR] Failed to execute goal on project GApp: Could not resolve dependencies for project GApp:GApp:war:0.0.1-SNAPSHOT: Could not find artifact com.sun:tools:jar:1.6 at specified path C:\Program Files\Java\jre6\lib\tools.jar -> [Help 1]
```
The issue is that the `tools.jar` is in "`C:\Program Files\Java\jdk1.6.0_26\lib`" and is correctly set in the `JAVA_HOME` environment variable but the maven is still looking in jre folder as in error message "`C:\Program Files\Java\jre6\lib\tools.jar`".
```
C:\>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.6.0_26
```
**Interestingly**: when i set the full path in dependency, it worked just fine. But i don't want to hard code it.
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>C:\Program Files\Java\jdk1.6.0_26\lib\tools.jar</systemPath>
</dependency>
```
Can someone suggest any dynamic solution for this? | 2012/11/08 | [
"https://Stackoverflow.com/questions/13288735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129313/"
] | It's a bug in the Eclipse Maven support. Eclipse doesn't support all of the global Maven properties as per the [**Maven specs**](http://docs.codehaus.org/display/MAVENUSER/MavenPropertiesGuide).
According to the specs:
>
> ${java.home} specifies the path to the current JRE\_HOME environment
> use with relative paths to get for example
>
>
>
At least in Eclipse 4.3.1 that is not the case, here `java.home` always points to the *JRE that was used to launch Eclipse*, not the build JRE.
To fix the issue you need to start Eclipse using the JRE from the JDK by adding something like this to `eclipse.ini` (*before* `-vmargs`!):
```
-vm
C:/<your_path_to_jdk170>/jre/bin/server/jvm.dll
``` | It seems your JAVA\_HOME is set to point to the JRE in eclipse. |
13,288,735 | I am on windows environment and using maven to compile my project. Although I just created the project and added the dependencies for various libararies.
As I added them maven started complaining for the missing `tools.jar`, so i added below to my `pom.xml`:
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
```
When i ran the maven install, i got an error for the missing jar as below :
```
[ERROR] Failed to execute goal on project GApp: Could not resolve dependencies for project GApp:GApp:war:0.0.1-SNAPSHOT: Could not find artifact com.sun:tools:jar:1.6 at specified path C:\Program Files\Java\jre6\lib\tools.jar -> [Help 1]
```
The issue is that the `tools.jar` is in "`C:\Program Files\Java\jdk1.6.0_26\lib`" and is correctly set in the `JAVA_HOME` environment variable but the maven is still looking in jre folder as in error message "`C:\Program Files\Java\jre6\lib\tools.jar`".
```
C:\>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.6.0_26
```
**Interestingly**: when i set the full path in dependency, it worked just fine. But i don't want to hard code it.
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>C:\Program Files\Java\jdk1.6.0_26\lib\tools.jar</systemPath>
</dependency>
```
Can someone suggest any dynamic solution for this? | 2012/11/08 | [
"https://Stackoverflow.com/questions/13288735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129313/"
] | Maven ${java.home} property is set and taken from different places depending your Eclipse execution:
* from the default JRE selected for the workspace
>
> Window>Preferences>Java>Installed JREs
>
>
>
* from the specific Eclipse project,
>
> Java Build Path>Libraries>JRE System Library
>
>
>
* from the Run configuration.
>
> Run Configurations> Specific Run Configuration > JRE
>
>
>
Remember your JRE home paths points to a JDK or JRE under JDK | Also look in the .mavenrc file in your home dir.
This caught me off guard.
I changed everything as suggested only to find that my .mavenrc file set the JAVA\_HOME to an older version. |
13,288,735 | I am on windows environment and using maven to compile my project. Although I just created the project and added the dependencies for various libararies.
As I added them maven started complaining for the missing `tools.jar`, so i added below to my `pom.xml`:
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
```
When i ran the maven install, i got an error for the missing jar as below :
```
[ERROR] Failed to execute goal on project GApp: Could not resolve dependencies for project GApp:GApp:war:0.0.1-SNAPSHOT: Could not find artifact com.sun:tools:jar:1.6 at specified path C:\Program Files\Java\jre6\lib\tools.jar -> [Help 1]
```
The issue is that the `tools.jar` is in "`C:\Program Files\Java\jdk1.6.0_26\lib`" and is correctly set in the `JAVA_HOME` environment variable but the maven is still looking in jre folder as in error message "`C:\Program Files\Java\jre6\lib\tools.jar`".
```
C:\>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.6.0_26
```
**Interestingly**: when i set the full path in dependency, it worked just fine. But i don't want to hard code it.
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>C:\Program Files\Java\jdk1.6.0_26\lib\tools.jar</systemPath>
</dependency>
```
Can someone suggest any dynamic solution for this? | 2012/11/08 | [
"https://Stackoverflow.com/questions/13288735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129313/"
] | You might be using the wrong Maven installation. Switch it in Window > Preferences > Maven > Installations. I had mine set to the Fedora Maven install; changing it back to the default (the version embedded in m2e) fixed the problem for me.
I suspect what was causing this issue is that the Fedora Maven install was using Fedora's OpenJDK, which probably puts tools.jar in a weird location (everything about Fedora's OpenJDK is weird and non-standard), so Maven can't find it. | Sounds like you are running Maven in Eclipse. Eclipse does not consult JAVA\_HOME.
Make sure you have set your JRE in Eclipse preferences to your desired JDK. |
13,288,735 | I am on windows environment and using maven to compile my project. Although I just created the project and added the dependencies for various libararies.
As I added them maven started complaining for the missing `tools.jar`, so i added below to my `pom.xml`:
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
```
When i ran the maven install, i got an error for the missing jar as below :
```
[ERROR] Failed to execute goal on project GApp: Could not resolve dependencies for project GApp:GApp:war:0.0.1-SNAPSHOT: Could not find artifact com.sun:tools:jar:1.6 at specified path C:\Program Files\Java\jre6\lib\tools.jar -> [Help 1]
```
The issue is that the `tools.jar` is in "`C:\Program Files\Java\jdk1.6.0_26\lib`" and is correctly set in the `JAVA_HOME` environment variable but the maven is still looking in jre folder as in error message "`C:\Program Files\Java\jre6\lib\tools.jar`".
```
C:\>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.6.0_26
```
**Interestingly**: when i set the full path in dependency, it worked just fine. But i don't want to hard code it.
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>C:\Program Files\Java\jdk1.6.0_26\lib\tools.jar</systemPath>
</dependency>
```
Can someone suggest any dynamic solution for this? | 2012/11/08 | [
"https://Stackoverflow.com/questions/13288735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129313/"
] | It's a bug in the Eclipse Maven support. Eclipse doesn't support all of the global Maven properties as per the [**Maven specs**](http://docs.codehaus.org/display/MAVENUSER/MavenPropertiesGuide).
According to the specs:
>
> ${java.home} specifies the path to the current JRE\_HOME environment
> use with relative paths to get for example
>
>
>
At least in Eclipse 4.3.1 that is not the case, here `java.home` always points to the *JRE that was used to launch Eclipse*, not the build JRE.
To fix the issue you need to start Eclipse using the JRE from the JDK by adding something like this to `eclipse.ini` (*before* `-vmargs`!):
```
-vm
C:/<your_path_to_jdk170>/jre/bin/server/jvm.dll
``` | Sounds like you are running Maven in Eclipse. Eclipse does not consult JAVA\_HOME.
Make sure you have set your JRE in Eclipse preferences to your desired JDK. |
13,288,735 | I am on windows environment and using maven to compile my project. Although I just created the project and added the dependencies for various libararies.
As I added them maven started complaining for the missing `tools.jar`, so i added below to my `pom.xml`:
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
```
When i ran the maven install, i got an error for the missing jar as below :
```
[ERROR] Failed to execute goal on project GApp: Could not resolve dependencies for project GApp:GApp:war:0.0.1-SNAPSHOT: Could not find artifact com.sun:tools:jar:1.6 at specified path C:\Program Files\Java\jre6\lib\tools.jar -> [Help 1]
```
The issue is that the `tools.jar` is in "`C:\Program Files\Java\jdk1.6.0_26\lib`" and is correctly set in the `JAVA_HOME` environment variable but the maven is still looking in jre folder as in error message "`C:\Program Files\Java\jre6\lib\tools.jar`".
```
C:\>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.6.0_26
```
**Interestingly**: when i set the full path in dependency, it worked just fine. But i don't want to hard code it.
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>C:\Program Files\Java\jdk1.6.0_26\lib\tools.jar</systemPath>
</dependency>
```
Can someone suggest any dynamic solution for this? | 2012/11/08 | [
"https://Stackoverflow.com/questions/13288735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129313/"
] | It's a bug in the Eclipse Maven support. Eclipse doesn't support all of the global Maven properties as per the [**Maven specs**](http://docs.codehaus.org/display/MAVENUSER/MavenPropertiesGuide).
According to the specs:
>
> ${java.home} specifies the path to the current JRE\_HOME environment
> use with relative paths to get for example
>
>
>
At least in Eclipse 4.3.1 that is not the case, here `java.home` always points to the *JRE that was used to launch Eclipse*, not the build JRE.
To fix the issue you need to start Eclipse using the JRE from the JDK by adding something like this to `eclipse.ini` (*before* `-vmargs`!):
```
-vm
C:/<your_path_to_jdk170>/jre/bin/server/jvm.dll
``` | Check to see if you have a .mavenrc file, it may be forcing JAVA\_HOME to be something other that what is set in the environment variable. |
13,288,735 | I am on windows environment and using maven to compile my project. Although I just created the project and added the dependencies for various libararies.
As I added them maven started complaining for the missing `tools.jar`, so i added below to my `pom.xml`:
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
```
When i ran the maven install, i got an error for the missing jar as below :
```
[ERROR] Failed to execute goal on project GApp: Could not resolve dependencies for project GApp:GApp:war:0.0.1-SNAPSHOT: Could not find artifact com.sun:tools:jar:1.6 at specified path C:\Program Files\Java\jre6\lib\tools.jar -> [Help 1]
```
The issue is that the `tools.jar` is in "`C:\Program Files\Java\jdk1.6.0_26\lib`" and is correctly set in the `JAVA_HOME` environment variable but the maven is still looking in jre folder as in error message "`C:\Program Files\Java\jre6\lib\tools.jar`".
```
C:\>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.6.0_26
```
**Interestingly**: when i set the full path in dependency, it worked just fine. But i don't want to hard code it.
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>C:\Program Files\Java\jdk1.6.0_26\lib\tools.jar</systemPath>
</dependency>
```
Can someone suggest any dynamic solution for this? | 2012/11/08 | [
"https://Stackoverflow.com/questions/13288735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129313/"
] | It's a bug in the Eclipse Maven support. Eclipse doesn't support all of the global Maven properties as per the [**Maven specs**](http://docs.codehaus.org/display/MAVENUSER/MavenPropertiesGuide).
According to the specs:
>
> ${java.home} specifies the path to the current JRE\_HOME environment
> use with relative paths to get for example
>
>
>
At least in Eclipse 4.3.1 that is not the case, here `java.home` always points to the *JRE that was used to launch Eclipse*, not the build JRE.
To fix the issue you need to start Eclipse using the JRE from the JDK by adding something like this to `eclipse.ini` (*before* `-vmargs`!):
```
-vm
C:/<your_path_to_jdk170>/jre/bin/server/jvm.dll
``` | You might be using the wrong Maven installation. Switch it in Window > Preferences > Maven > Installations. I had mine set to the Fedora Maven install; changing it back to the default (the version embedded in m2e) fixed the problem for me.
I suspect what was causing this issue is that the Fedora Maven install was using Fedora's OpenJDK, which probably puts tools.jar in a weird location (everything about Fedora's OpenJDK is weird and non-standard), so Maven can't find it. |
13,288,735 | I am on windows environment and using maven to compile my project. Although I just created the project and added the dependencies for various libararies.
As I added them maven started complaining for the missing `tools.jar`, so i added below to my `pom.xml`:
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
```
When i ran the maven install, i got an error for the missing jar as below :
```
[ERROR] Failed to execute goal on project GApp: Could not resolve dependencies for project GApp:GApp:war:0.0.1-SNAPSHOT: Could not find artifact com.sun:tools:jar:1.6 at specified path C:\Program Files\Java\jre6\lib\tools.jar -> [Help 1]
```
The issue is that the `tools.jar` is in "`C:\Program Files\Java\jdk1.6.0_26\lib`" and is correctly set in the `JAVA_HOME` environment variable but the maven is still looking in jre folder as in error message "`C:\Program Files\Java\jre6\lib\tools.jar`".
```
C:\>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.6.0_26
```
**Interestingly**: when i set the full path in dependency, it worked just fine. But i don't want to hard code it.
```
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>C:\Program Files\Java\jdk1.6.0_26\lib\tools.jar</systemPath>
</dependency>
```
Can someone suggest any dynamic solution for this? | 2012/11/08 | [
"https://Stackoverflow.com/questions/13288735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129313/"
] | It seems your JAVA\_HOME is set to point to the JRE in eclipse. | Sounds like you are running Maven in Eclipse. Eclipse does not consult JAVA\_HOME.
Make sure you have set your JRE in Eclipse preferences to your desired JDK. |
739,309 | We have dedicated internet connection an our ISP has provided us with some real IP addresses.
We have several servers which we use, including a one that has a real IP on it as they enter to the server remotely from outside office and work.
Many people have suggested me that this is a bad idea as the server might be attacked and compromised given its public exposure via the real IP.
However, it is true that the IP is exposed, and maximum an attacker can do is reach the login screen and get stuck there as he does not have the password.
* What other things can go wrong while having a real IP on the server
(Microsoft Server 2012)? and why usually it is a bad idea, (if it is at all)
* What are methods that I can use to enhance the security of the IP?
(as low cost as possible) | 2015/11/27 | [
"https://serverfault.com/questions/739309",
"https://serverfault.com",
"https://serverfault.com/users/272852/"
] | You can try to "hide" your server under a firewall. That's the best solution, putting it into a DMZ, in a different LAN of your other devices.
Also, you can configure port forwarding, in a cheap router, so an attacker need to know, furthermore, your established port (60k possibilities).
In addition, you should configure methods to block DDoS and Force brute attacks (IP block?) to ensure your High Availability.
By last, check your Windows Event Viewer, to monitor all login atempts.
PD: One thing to keep in mind, it is not said "real" IP, but Public IP.
Regards. | For a small company that is looking to have a server publicly accessible, it is often not easy to make sure that it is entirely safe.
Your first order of business is probably to make sure that if the server is compromised, you limit the amount of risk.
* Seperate the public facing server on a seperate LAN
* Don't share credentials between that server and the rest of your environment
* Limit access methods from the public server to the rest of your environment
As for hardening the server yourself. If you're a small company with budget constraints, there is a windows wizard available for basic hardening.
The [Security Configuration Wizard](https://technet.microsoft.com/en-us/library/cc771492(v=ws.10).aspx) will do some basic hardening on your server.
Keep in mind though, it is an automated process, so make sure you backup before implementing it, and test thoroughly afterwards. |
5,944,225 | Hello again I'm trying to get an error to display in the app below if there is no internet connection. Here are the files.
FirstViewController.h:
```
//
// FirstViewController.h
// DailyJoke
//
// Created by John Bridge on 5/4/11.
// Copyright 2011 Bridge and co. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface FirstViewController : UIViewController {
IBOutlet UIWebView *webView;
}
@end
```
Here is FirstViewController.m:
//
// FirstViewController.m
// DailyJoke
//
// Created by John Bridge on 5/4/11.
// Copyright 2011 Bridge and co. All rights reserved.
//
```
#import "FirstViewController.h"
@implementation FirstViewController
-(void)awakeFromNib
{
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.johnbridge180.com/IPhoneIPad/IPhone/DailyJoke/DailyJoke.html"]]];
}
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end
``` | 2011/05/10 | [
"https://Stackoverflow.com/questions/5944225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/735165/"
] | Implement UIWebViewDelegate to your controller class. And override following methods in your controller class. These methods names are self explanatory. You need to handle errors accordingly. Set your webview delegate to your controller class by setting following sentence in your viewDidLoad method.Also dont forget to implement UIWebViewDelegate to your class.
>
> * webView.delegate = self;
>
>
>
```
#pragma mark webView delegate
-(void)webViewDidStartLoad:(UIWebView *)wView{
[UIApplication sharedApplication].networkActivityIndicatorVisible = TRUE;
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
if ([error code] == -999) {
}
else if([error code] == -1009 || [[error localizedDescription] isEqualToString:@"no Internet connection"]){
[UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
}
else if([error code] == -1001 || [[error localizedDescription] isEqualToString:@"timed out"]){
}
else if([error code] == -1004 || [[error localizedDescription] isEqualToString:@"can’t connect to host"]){
}
else if (error != NULL) {
}
else{
}
}
-(void)webViewDidFinishLoad:(UIWebView *)wView{
[UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
}
```
Hope it helps. | Lots of folks use the Reachability example provided by apple: <http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html>
Looks like:
+ (Reachability\*) reachabilityWithHostName: (NSString\*) hostName;
would be the place start.
Another way would be to load the HTML using an NSURLConnection and supply it to the webview. If the url connection fails, the client probably doesn't have an internet connection. |
5,944,225 | Hello again I'm trying to get an error to display in the app below if there is no internet connection. Here are the files.
FirstViewController.h:
```
//
// FirstViewController.h
// DailyJoke
//
// Created by John Bridge on 5/4/11.
// Copyright 2011 Bridge and co. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface FirstViewController : UIViewController {
IBOutlet UIWebView *webView;
}
@end
```
Here is FirstViewController.m:
//
// FirstViewController.m
// DailyJoke
//
// Created by John Bridge on 5/4/11.
// Copyright 2011 Bridge and co. All rights reserved.
//
```
#import "FirstViewController.h"
@implementation FirstViewController
-(void)awakeFromNib
{
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.johnbridge180.com/IPhoneIPad/IPhone/DailyJoke/DailyJoke.html"]]];
}
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end
``` | 2011/05/10 | [
"https://Stackoverflow.com/questions/5944225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/735165/"
] | Lots of folks use the Reachability example provided by apple: <http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html>
Looks like:
+ (Reachability\*) reachabilityWithHostName: (NSString\*) hostName;
would be the place start.
Another way would be to load the HTML using an NSURLConnection and supply it to the webview. If the url connection fails, the client probably doesn't have an internet connection. | If you are using:
```
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
```
You can find network error codes here:
<https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/constant_group/URL_Loading_System_Error_Codes> |
5,944,225 | Hello again I'm trying to get an error to display in the app below if there is no internet connection. Here are the files.
FirstViewController.h:
```
//
// FirstViewController.h
// DailyJoke
//
// Created by John Bridge on 5/4/11.
// Copyright 2011 Bridge and co. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface FirstViewController : UIViewController {
IBOutlet UIWebView *webView;
}
@end
```
Here is FirstViewController.m:
//
// FirstViewController.m
// DailyJoke
//
// Created by John Bridge on 5/4/11.
// Copyright 2011 Bridge and co. All rights reserved.
//
```
#import "FirstViewController.h"
@implementation FirstViewController
-(void)awakeFromNib
{
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.johnbridge180.com/IPhoneIPad/IPhone/DailyJoke/DailyJoke.html"]]];
}
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end
``` | 2011/05/10 | [
"https://Stackoverflow.com/questions/5944225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/735165/"
] | Implement UIWebViewDelegate to your controller class. And override following methods in your controller class. These methods names are self explanatory. You need to handle errors accordingly. Set your webview delegate to your controller class by setting following sentence in your viewDidLoad method.Also dont forget to implement UIWebViewDelegate to your class.
>
> * webView.delegate = self;
>
>
>
```
#pragma mark webView delegate
-(void)webViewDidStartLoad:(UIWebView *)wView{
[UIApplication sharedApplication].networkActivityIndicatorVisible = TRUE;
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
if ([error code] == -999) {
}
else if([error code] == -1009 || [[error localizedDescription] isEqualToString:@"no Internet connection"]){
[UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
}
else if([error code] == -1001 || [[error localizedDescription] isEqualToString:@"timed out"]){
}
else if([error code] == -1004 || [[error localizedDescription] isEqualToString:@"can’t connect to host"]){
}
else if (error != NULL) {
}
else{
}
}
-(void)webViewDidFinishLoad:(UIWebView *)wView{
[UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
}
```
Hope it helps. | If you are using:
```
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
```
You can find network error codes here:
<https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/constant_group/URL_Loading_System_Error_Codes> |
25,038,510 | I am working on web services in android,
i have three strings
```
String username = "Rajesh";
String password = "abc"
String usertype = "member";
```
and i want to send them to web service in the following form
```
{"UserName":username,"Password":password,"UserType":usertype}
```
like
```
{"UserName":"Rajesh","Password":"abc","UserType":"member"}
```
web service url is something like : <http://abc.xyz.org/api/login>
i dont have any idea how to do it, please help me,
how can i convert strings to json like above and how can i pass it to web service
Thank you | 2014/07/30 | [
"https://Stackoverflow.com/questions/25038510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2002625/"
] | **Issue:**
Once you clear objects and build the list again selected items disappear regardless of you are keeping it in a variable or not. Because to keep this info the variable for selected items must be declared as a variable which is dynamically attached to OLV control. That's why once the list is cleared the variable won't be able to keep selected items.
**About workaround:**
I have a workaround for this issue. Most of people may think to implement `objectListViewUserList.SelectedItem` property but this property has some issues. It is not consistent with some reason. So for my workaround, I will introduce this property `objectListViewUserList.MouseMoveHitTest`. It sounds like it's a test variable but it works like a charm.
**Assumption:**
Additionally, to implement this workaround, it is assumed that first column is the ID column.
**Workaround:**
Here's the workaround. Keep the text information of the first column in a public string in the click event.
```
private void objectListViewUserList_Click(object sender, EventArgs e)
{
if (objectListViewUserList.MouseMoveHitTest.Item != null)
selectedItemText = objectListViewUserList.MouseMoveHitTest.Item.Text;
else
selectedItemText = "";
}
```
In my application, I refresh the OLV control with `fillOnlineUsers` method. This is arbitrary. It can be any method. In my application this method works with a timer. After each refresh, I select the items by searching the ID in the new list.
```
public void fillOnlineUsers()
{
objectListViewUserList.ClearObjects();
objectListViewUserList.AddObjects(onlineUsers);
objectListViewUserList.BuildList();
if (selectedItemText != "")
{
foreach (OLVListItem olvi in objectListViewUserList.Items)
if (olvi.Text == selectedItemText)
olvi.Selected = true;
}
}
```
This workaround has O(n) complexity. Which means it may slow down your application if you have thousands of records. | if you use version 2.9.1 of the ObjectListView and just use olv.SetObjects(YourDataObject)
the existing selection will be preserved and you do not need any of the time consuming methods or workarounds to remember the active selection.
Your code should try to maintain the original objects in the Data if possible, update those where needed. If you clear all objects and recreate new ones, you loose the selection and are forced to resort to other ways to remember selection. |
25,038,510 | I am working on web services in android,
i have three strings
```
String username = "Rajesh";
String password = "abc"
String usertype = "member";
```
and i want to send them to web service in the following form
```
{"UserName":username,"Password":password,"UserType":usertype}
```
like
```
{"UserName":"Rajesh","Password":"abc","UserType":"member"}
```
web service url is something like : <http://abc.xyz.org/api/login>
i dont have any idea how to do it, please help me,
how can i convert strings to json like above and how can i pass it to web service
Thank you | 2014/07/30 | [
"https://Stackoverflow.com/questions/25038510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2002625/"
] | **Issue:**
Once you clear objects and build the list again selected items disappear regardless of you are keeping it in a variable or not. Because to keep this info the variable for selected items must be declared as a variable which is dynamically attached to OLV control. That's why once the list is cleared the variable won't be able to keep selected items.
**About workaround:**
I have a workaround for this issue. Most of people may think to implement `objectListViewUserList.SelectedItem` property but this property has some issues. It is not consistent with some reason. So for my workaround, I will introduce this property `objectListViewUserList.MouseMoveHitTest`. It sounds like it's a test variable but it works like a charm.
**Assumption:**
Additionally, to implement this workaround, it is assumed that first column is the ID column.
**Workaround:**
Here's the workaround. Keep the text information of the first column in a public string in the click event.
```
private void objectListViewUserList_Click(object sender, EventArgs e)
{
if (objectListViewUserList.MouseMoveHitTest.Item != null)
selectedItemText = objectListViewUserList.MouseMoveHitTest.Item.Text;
else
selectedItemText = "";
}
```
In my application, I refresh the OLV control with `fillOnlineUsers` method. This is arbitrary. It can be any method. In my application this method works with a timer. After each refresh, I select the items by searching the ID in the new list.
```
public void fillOnlineUsers()
{
objectListViewUserList.ClearObjects();
objectListViewUserList.AddObjects(onlineUsers);
objectListViewUserList.BuildList();
if (selectedItemText != "")
{
foreach (OLVListItem olvi in objectListViewUserList.Items)
if (olvi.Text == selectedItemText)
olvi.Selected = true;
}
}
```
This workaround has O(n) complexity. Which means it may slow down your application if you have thousands of records. | so from the other posts it looks like your records have a Guid, that's good news! If you implement `GetHashCode` and `Equals` then you can clear the list and reselect the old selection by passing in the old list `olv.SelectedObjects.Cast<object>().ToList()`.
```
public partial class Form1 : Form
{
private Guid _guid1;
private Guid _guid2;
class MyClass
{
public readonly Guid Guid;
public string Key;
public string Value;
public MyClass(Guid guid, string key, string value)
{
Key = key;
Guid = guid;
Value = value;
}
public override int GetHashCode()
{
return Guid.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj is MyClass)
return this.Guid.Equals(((MyClass) obj).Guid);
return base.Equals(obj);
}
}
public Form1()
{
InitializeComponent();
olv.FullRowSelect = true;
olv.HideSelection = false;
_guid1 = Guid.Parse("026c90aa-7fb8-452d-b8bc-b42fd7bc0e7f");
_guid2 = Guid.Parse("85ea0ce0-da65-412f-8198-724c196342da");
olv.AddObjects(new []
{
//two objects that will be updated
new MyClass(_guid1,"go","nuts"),
new MyClass(_guid2,"lol","rly?"),
//one object that will disapear
new MyClass(Guid.NewGuid(),"bye","bye")
});
}
private void BtnRefreshObjects_Click(object sender, System.EventArgs e)
{
olv.BeginUpdate();
//remember the old objects
var oldSelection = olv.SelectedObjects.Cast<object>().ToList();
//swap them for the new objects
olv.ClearObjects();
olv.AddObjects(
new []
{
//This object stays the same
new MyClass(_guid1,"go","nuts"),
//This object changes fields (but is still the same record due to Guid)
new MyClass(_guid2,"omg2","omg3"),
//This is a new object
new MyClass(Guid.NewGuid(),"omg5","omg6")
});
//reset the old selection (even though they are stale objects the selection works because of Equality override)
olv.SelectedObjects = oldSelection;
olv.EndUpdate();
}
}
``` |
25,038,510 | I am working on web services in android,
i have three strings
```
String username = "Rajesh";
String password = "abc"
String usertype = "member";
```
and i want to send them to web service in the following form
```
{"UserName":username,"Password":password,"UserType":usertype}
```
like
```
{"UserName":"Rajesh","Password":"abc","UserType":"member"}
```
web service url is something like : <http://abc.xyz.org/api/login>
i dont have any idea how to do it, please help me,
how can i convert strings to json like above and how can i pass it to web service
Thank you | 2014/07/30 | [
"https://Stackoverflow.com/questions/25038510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2002625/"
] | This is my solution (based on Barry Guvenkaya answer). I assume that
1. More than one item can be selected (by mouse or by keyboard)
2. Object ID is not stored in a column of OLVListItem, but inside the object (columns can be hidden, their order can be different).
My `Refresh()` function:
```
PushSelected();
objectListView.SetObjects(...);
PopSelected();
```
Save and restore selection with:
```
private List<Guid> selected; // Keeping the ID's of selected objects
public void PushSelected()
{
// Value of SelectedList can be get using
// objectListView.SelectedObjects
selected.Clear();
foreach (MyObject r in SelectedList)
selected.Add(r.id);
}
public void PopSelected()
{
D.DeselectAll();
if (selected.Count != 0)
for (int i = 0; i < objectListView.Items.Count; i ++)
{
OLVListItem item = (OLVListItem)objectListView.Items[i];
Guid g = ((MyObject)item.RowObject).id;
if (selected.Contains(g))
item.Selected = true;
}
}
```
Of course, this solution also has O(n) complexity and even O(n\*n) if all items were selected. | if you use version 2.9.1 of the ObjectListView and just use olv.SetObjects(YourDataObject)
the existing selection will be preserved and you do not need any of the time consuming methods or workarounds to remember the active selection.
Your code should try to maintain the original objects in the Data if possible, update those where needed. If you clear all objects and recreate new ones, you loose the selection and are forced to resort to other ways to remember selection. |
25,038,510 | I am working on web services in android,
i have three strings
```
String username = "Rajesh";
String password = "abc"
String usertype = "member";
```
and i want to send them to web service in the following form
```
{"UserName":username,"Password":password,"UserType":usertype}
```
like
```
{"UserName":"Rajesh","Password":"abc","UserType":"member"}
```
web service url is something like : <http://abc.xyz.org/api/login>
i dont have any idea how to do it, please help me,
how can i convert strings to json like above and how can i pass it to web service
Thank you | 2014/07/30 | [
"https://Stackoverflow.com/questions/25038510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2002625/"
] | This is my solution (based on Barry Guvenkaya answer). I assume that
1. More than one item can be selected (by mouse or by keyboard)
2. Object ID is not stored in a column of OLVListItem, but inside the object (columns can be hidden, their order can be different).
My `Refresh()` function:
```
PushSelected();
objectListView.SetObjects(...);
PopSelected();
```
Save and restore selection with:
```
private List<Guid> selected; // Keeping the ID's of selected objects
public void PushSelected()
{
// Value of SelectedList can be get using
// objectListView.SelectedObjects
selected.Clear();
foreach (MyObject r in SelectedList)
selected.Add(r.id);
}
public void PopSelected()
{
D.DeselectAll();
if (selected.Count != 0)
for (int i = 0; i < objectListView.Items.Count; i ++)
{
OLVListItem item = (OLVListItem)objectListView.Items[i];
Guid g = ((MyObject)item.RowObject).id;
if (selected.Contains(g))
item.Selected = true;
}
}
```
Of course, this solution also has O(n) complexity and even O(n\*n) if all items were selected. | so from the other posts it looks like your records have a Guid, that's good news! If you implement `GetHashCode` and `Equals` then you can clear the list and reselect the old selection by passing in the old list `olv.SelectedObjects.Cast<object>().ToList()`.
```
public partial class Form1 : Form
{
private Guid _guid1;
private Guid _guid2;
class MyClass
{
public readonly Guid Guid;
public string Key;
public string Value;
public MyClass(Guid guid, string key, string value)
{
Key = key;
Guid = guid;
Value = value;
}
public override int GetHashCode()
{
return Guid.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj is MyClass)
return this.Guid.Equals(((MyClass) obj).Guid);
return base.Equals(obj);
}
}
public Form1()
{
InitializeComponent();
olv.FullRowSelect = true;
olv.HideSelection = false;
_guid1 = Guid.Parse("026c90aa-7fb8-452d-b8bc-b42fd7bc0e7f");
_guid2 = Guid.Parse("85ea0ce0-da65-412f-8198-724c196342da");
olv.AddObjects(new []
{
//two objects that will be updated
new MyClass(_guid1,"go","nuts"),
new MyClass(_guid2,"lol","rly?"),
//one object that will disapear
new MyClass(Guid.NewGuid(),"bye","bye")
});
}
private void BtnRefreshObjects_Click(object sender, System.EventArgs e)
{
olv.BeginUpdate();
//remember the old objects
var oldSelection = olv.SelectedObjects.Cast<object>().ToList();
//swap them for the new objects
olv.ClearObjects();
olv.AddObjects(
new []
{
//This object stays the same
new MyClass(_guid1,"go","nuts"),
//This object changes fields (but is still the same record due to Guid)
new MyClass(_guid2,"omg2","omg3"),
//This is a new object
new MyClass(Guid.NewGuid(),"omg5","omg6")
});
//reset the old selection (even though they are stale objects the selection works because of Equality override)
olv.SelectedObjects = oldSelection;
olv.EndUpdate();
}
}
``` |
22,051,970 | I want to make an attribute accessible from instance and class that cannot be reassigned. I have the "prevent from reassigned" part tackled thanks to a metaclass. However, now the attribute cannot be read from the class. How to make it so.
Having this:
```
class Meta(type):
def __setattr__(cls, attr, val):
if attr =="frozen":
print "You can't unfreeze the frozen"
else:
cls.name = val
class Fixed(object):
__metaclass__ = Meta
frzn = 'I AM AWESOME'
def holdset(_,val):
_.frzn = _.frzn
print "frozen is frozen not setting to ", val
def get(_):
return _.frzn
frozen = property(fset=holdset,fget=get)
```
When calling
```
print Fixed.frozen
print Fixed().frozen
```
Gives
```none
<property object at 0x106dbeba8>
I AM AWESOME
```
Why doesn't it give the same? How to make it give the same? | 2014/02/26 | [
"https://Stackoverflow.com/questions/22051970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2876289/"
] | Not really. When it comes to coding, the best way to learn is by doing. Learning from your mistake will be the best thing you can do, but that doesn't mean don't seek out help.
You can teach yourself with some books. But when it comes down to it this is not a read the book and pass the test with an A type thing. This is developing certain methods that will work for you and the environment and the only way to learn is by doing. | How about learning programming concepts with a graphical environment? I would say [Alice](http://www.alice.org/) is the answer.
From the website:
>
> Using an innovative programming environment to support the creation of
> 3D animations, the Alice Project provides tools and materials for
> teaching and learning computational thinking, problem solving, and
> computer programming across a spectrum of ages and grade levels.
>
>
> |
22,051,970 | I want to make an attribute accessible from instance and class that cannot be reassigned. I have the "prevent from reassigned" part tackled thanks to a metaclass. However, now the attribute cannot be read from the class. How to make it so.
Having this:
```
class Meta(type):
def __setattr__(cls, attr, val):
if attr =="frozen":
print "You can't unfreeze the frozen"
else:
cls.name = val
class Fixed(object):
__metaclass__ = Meta
frzn = 'I AM AWESOME'
def holdset(_,val):
_.frzn = _.frzn
print "frozen is frozen not setting to ", val
def get(_):
return _.frzn
frozen = property(fset=holdset,fget=get)
```
When calling
```
print Fixed.frozen
print Fixed().frozen
```
Gives
```none
<property object at 0x106dbeba8>
I AM AWESOME
```
Why doesn't it give the same? How to make it give the same? | 2014/02/26 | [
"https://Stackoverflow.com/questions/22051970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2876289/"
] | Not really. When it comes to coding, the best way to learn is by doing. Learning from your mistake will be the best thing you can do, but that doesn't mean don't seek out help.
You can teach yourself with some books. But when it comes down to it this is not a read the book and pass the test with an A type thing. This is developing certain methods that will work for you and the environment and the only way to learn is by doing. | Since *Programming* involves writing instructions for a computer, I'm not sure it would make sense to learn programming without learning a language.
If you want to study the underlying theories without getting too stuck in implementation, you could study *Computer Science* and look into automata theory and data structures and algorithm analysis and other subjects which don't bind you to any specific language. |
3,764,236 | My book, Classic Set Theory: For Guided Independent Study, gives me this theorem:
"let $y\_0$ be any element of $ℕ$ and $h"ℕ×ℕ×→ℕ$ a function on pairs $(x,y)∈ℕ×ℕ$. Then there exists a unique function $f:ℕ→ℕ$ such that $f(0)=y\_0$ and $f(n^+)=h(n,f(n))$ for all $n∈ℕ$"
($n^+$ is the successor of the number $n$, which in this case, since the natural numbers are defined as sets, is $n^+=n∪\{n\}$)
then it says:
"for defining addition, the trick is to use recursion to define $m+n$ for a fixed $m$ and all $n$. The $f$ in the theorem will be defined so that $f(n)$ is to be regarded as $m+n$. To emphasize this, we shall refer to this $f$ as $f\_m$."
then it defines addition in this way:
"$f(0)=m$ and $f\_m(n^+)=(f\_m(n))^+$
I understand this last part, since $m+n^+=m+n+1=(m+n)+1=(m+n)^+$, but i don't understand what $h(n,f(n))$ is.
It gives also this exercise (you don't need to read this part, but maybe it can help you answering the question), which i actually dont understand..
"Define $h(x,y)$ so that $f\_m(n^+)=h(m,f\_m(n))$"
the solution is:
"$h(x,y)=y^+$"
(which comes from the definition above: $f(n^+)=h(n,f(n))$ but since $f\_m(n^+)=(f\_m(n))^+$ we have $h(n,f(n))=(f\_m(n))^+$)
what i dont get about this excercise is the first "$m$" in $h(m,f\_m(n))$, i don't know if this is a typo or not, what i thought is that since $m$ is fixed and in the theorem it says "for all $n$" you can write it like that, but it doesn't really makes sense since in $h$, $n$ appears multiple times you have to replace it throughout the equation.
If it can be useful, multiplication is defined using the definition of addition and that theorem as $f\_m(0)=0$ and $f\_m(n^+)=f\_m(n)+m$ where $f\_m(n)$ means $m·n$
Could you guys help me out please? Could you tell me what $h(n,f(n))$ means in the definition of addition (and if you want also multiplication)? | 2020/07/21 | [
"https://math.stackexchange.com/questions/3764236",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/473425/"
] | First, the Theorem you gave is a particular case of the Recursion theorem
>
> let E be a set. if there exists $x\_0\in E$ and $h:E\to E,$ then there exists a unique $f: \Bbb N\to E$ by $f(0)=x\_0$ and $f(n^+)=h(f(n))$.
>
>
>
Notice that there exists $S:\Bbb N\to \Bbb N$ by $S(n)=n^+ \forall n\in \Bbb N.$ (the succession)
For any $m \in \Bbb N$. Addition to $m$ is usually defined as $f\_m:\Bbb N\to \Bbb N$ by $f\_m(0)=m$ and $f\_m(n^+)=S(f\_m(n))=f\_m(n)^+$ (i.e $m+0=m, m+1=m+1, m+2=(m+1)+1.... )$
In your book, the author defined $h:\Bbb N\times \Bbb N\to \Bbb N$ by $h(n,f(n))=f(n)^+\forall n$, which uses $\Bbb N\times \Bbb N$ as the domain to keep track of $n$, instead of just $\Bbb N$. I think it is not necessary, and $S$ defined above is good enugh.
For multiplication to $m$:
there exists $M\_m:\Bbb N\to \Bbb N$ by $M(n)=n+m$ (as $+$ is defined above)
Multiplication is defined as $g:\Bbb N\to \Bbb N$ by $g\_m(0)=0$ and $g\_m(n^+)=M(g\_m(n))=g\_m(n)+m$ $(m\times 0=0, m\times 1=(m\times0)+m, m\times 2=(m\times1)+m...$) | $h$ is just *some* function. It poses no conditions on the arguments that you can pass to it (other than their domain). This function is defined on $\mathbb{N}\times\mathbb{N}$.
Now, the theorem states that every such function $h$ can be defined recursively as *some* function $f : \mathbb{N}\to\mathbb{N}$, where the recursive call $f(n^+)$ is handled by $h(n, f(n))$. In other words, $h$ contains the recipe of how to calculate $f(n^+)$ from $n$ and $f(n)$.
Regarding the exercise, it could be a typo, but it doesn't really matter.
The assignment gives you a function $f\_m$ and asks you to find the recipe ($h$) for the recursive case in terms of $m$ and $f\_m(n)$. Because the recipe drops the first argument $m$ and only uses the second argument $f\_m(n)$, it doesn't matter whether the first argument is $m$ or $n$ or some other number.
Suppose it's not a typo. We have a fixed number $m$ (it is not a variable, because it's fixed), a function $f\_m:\mathbb{N}\to\mathbb{N}$, and a function $h:\mathbb{N}\times\mathbb{N}\to\mathbb{N}$. $h$ needs two arguments and the exercise requires that the first argument is always the fixed $m$. Then, in the context of this fixed $m$, you can consider some $h':\mathbb{N}\to\mathbb{N}$ such that $h'(x) = h(m,x)$ and work with $h'$. Or better, you can define $h':\mathbb{N}\times\mathbb{N}\to\mathbb{N}$ such that $h'(n,y) = h(m,y)$. Then, $h'$ fits the formulas and requirements of the theorem. |
11,118,568 | I have a ReferenceID varchar(6) column in over 80 different tables. I need to extend this to a varchar(8) throughout the db following a change implemented by the government organisation that assigns the IDs.
I was hoping to declare a cursor to get the table names as follows:
```
DECLARE @TableName AS VARCHAR(200)
DECLARE TableCursor CURSOR LOCAL READ_ONLY FOR
SELECT t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name = 'ReferenceID'
OPEN TableCursor
FETCH NEXT FROM TableCursor
INTO @TableName
```
and then edit the type as follows:
```
ALTER TABLE @TableName ALTER COLUMN ReferenceID VARCHAR(8)
```
This fails because the column is part of the Primary Key in some of the tables (and the columns included in the PK vary from table to table).
I really don't want to have to drop and recreate each PK manually for each table.
Within the cursor, is there a way either to disable the PK before altering the datatype and then re-enable it, or to drop and recreate the PK either side of altering the datatype, bearing in mind that the PK will depend on which table we're currently looking at? | 2012/06/20 | [
"https://Stackoverflow.com/questions/11118568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1468962/"
] | You need to specify `NOT NULL` explicitly in an `ALTER TABLE ... ALTER COLUMN` otherwise it defaults to allowing `NULL`. This is not permitted in a PK column.
The following works fine.
```
CREATE TABLE p
(
ReferenceID VARCHAR(6) NOT NULL PRIMARY KEY
)
INSERT INTO p VALUES ('AAAAAA')
ALTER TABLE p ALTER COLUMN ReferenceID VARCHAR(8) NOT NULL
```
when the `NOT NULL` is omitted it gives the following error
```
Msg 5074, Level 16, State 1, Line 1
The object 'PK__p__E1A99A792180FB33' is dependent on column 'ReferenceID'.
Msg 4922, Level 16, State 9, Line 1
ALTER TABLE ALTER COLUMN ReferenceID failed because one or more objects access this column.
```
A couple of things to consider in your programmatic approach is that you *would* need to drop any foreign keys referencing the `ReferenceID` columns temporarily and also make sure you don't include the `NOT NULL` for (Non PK) `ReferenceID` columns that currently *are* nullable. | You need to execute the `ALTER` statement as dynamic SQL: Build the statement as a SQL string and pass it to `sp_executesql`. |
11,118,568 | I have a ReferenceID varchar(6) column in over 80 different tables. I need to extend this to a varchar(8) throughout the db following a change implemented by the government organisation that assigns the IDs.
I was hoping to declare a cursor to get the table names as follows:
```
DECLARE @TableName AS VARCHAR(200)
DECLARE TableCursor CURSOR LOCAL READ_ONLY FOR
SELECT t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name = 'ReferenceID'
OPEN TableCursor
FETCH NEXT FROM TableCursor
INTO @TableName
```
and then edit the type as follows:
```
ALTER TABLE @TableName ALTER COLUMN ReferenceID VARCHAR(8)
```
This fails because the column is part of the Primary Key in some of the tables (and the columns included in the PK vary from table to table).
I really don't want to have to drop and recreate each PK manually for each table.
Within the cursor, is there a way either to disable the PK before altering the datatype and then re-enable it, or to drop and recreate the PK either side of altering the datatype, bearing in mind that the PK will depend on which table we're currently looking at? | 2012/06/20 | [
"https://Stackoverflow.com/questions/11118568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1468962/"
] | **EDIT** This solution is needed if you have a muddled database with a mixture of varchar(6) and char(6) columns caused by development extending over 10 years (with enough changes of government policy to cause any attempt at "good database design" to collapse eventually.)
**END EDIT**
To those who said I would have to drop and recreate the PK, you were right. Indexes and Foreign Keys also needed dropping and recreating.
Fortunately, there were a manageable number of indexes and FKs so I handled these as 'exceptional' and dropped them all, one at a time, at the beginning of the script, then re-added them, one at a time, at the end of the script (see the two sections in /\* \*/ below).
The main body of the SQL script then tips complete details about the FKs into a temporary table, then loops through each table name, dropping the FK, altering the datatype, re-adding the FK.
The SQL strings that get assembled are PRINTed in the script below. If you intend to reuse this (no warranties provided, etc., blah blah), comment these out to knock up to 50% off the execution time.
```
SET NOCOUNT ON
/* Handle exceptional tables here
* Remove indexes and foreign keys
* --Lots of "IF EXISTS ... ALTER TABLE <name> DROP CONSTRAINT <constraint name>, etc.
*/
--Declare variables
DECLARE @SQL VARCHAR(8000)
DECLARE @TableName VARCHAR(512)
DECLARE @ConstraintName VARCHAR(512)
DECLARE @tColumn VARCHAR(512)
DECLARE @Columns VARCHAR(8000)
DECLARE @IsDescending BIT
--Set up temporary table
SELECT
tbl.[schema_id],
tbl.name AS TableName,
i.NAME AS IndexName,
i.type_desc,
c.[column],
c.key_ordinal,
c.is_desc,
i.[object_id],
s.no_recompute,
i.[ignore_dup_key],
i.[allow_row_locks],
i.[allow_page_locks],
i.[fill_factor],
dsi.type,
dsi.name AS DataSpaceName
INTO #PKBackup
FROM
sys.tables AS tbl
INNER JOIN sys.indexes AS i
ON (
i.index_id > 0
AND i.is_hypothetical = 0
)
AND ( i.[object_id] = tbl.[object_id] )
INNER JOIN (
SELECT
ic.[object_id] ,
c.[name] [column] ,
ic.is_descending_key [is_desc],
ic.key_ordinal
FROM
sys.index_columns ic
INNER JOIN
sys.indexes i
ON
i.[object_id] = ic.[object_id]
AND
i.index_id = 1
AND
ic.index_id = 1
INNER JOIN
sys.tables t
ON
t.[object_id] = ic.[object_id]
INNER JOIN
sys.columns c
ON
c.[object_id] = t.[object_id]
AND
c.column_id = ic.column_id
) AS c
ON c.[object_id] = i.[object_id]
LEFT OUTER JOIN
sys.key_constraints AS k
ON
k.parent_object_id = i.[object_id]
AND
k.unique_index_id = i.index_id
LEFT OUTER JOIN
sys.data_spaces AS dsi
ON
dsi.data_space_id = i.data_space_id
LEFT OUTER JOIN
sys.xml_indexes AS xi
ON
xi.[object_id] = i.[object_id]
AND
xi.index_id = i.index_id
LEFT OUTER JOIN
sys.stats AS s
ON
s.stats_id = i.index_id
AND
s.[object_id] = i.[object_id]
WHERE
k.TYPE = 'PK'
DECLARE TableCursor CURSOR LOCAL READ_ONLY FOR
SELECT t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE
c.name = 'ReferenceID'
OPEN TableCursor
FETCH NEXT FROM TableCursor
INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT('--Updating ' + @TableName + '...')
SELECT @ConstraintName = PK.CONSTRAINT_NAME
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
WHERE
PK.TABLE_NAME = @TableName
AND
PK.CONSTRAINT_TYPE = 'PRIMARY KEY'
--drop the constraint
--Some tables don't have a PK defined, only do the next bit if they do
IF (SELECT COUNT(*) FROM #PKBackup PK WHERE PK.TableName = @TableName) > 0
BEGIN
SET @SQL = 'ALTER TABLE @TableName DROP CONSTRAINT @ConstraintName'
SET @SQL = REPLACE(@SQL, '@TableName', @TableName)
SET @SQL = REPLACE(@SQL, '@ConstraintName', @ConstraintName)
PRINT @SQL
EXEC (@SQL)
END
--This is where we actually change the datatype of the column
SET @SQL = 'ALTER TABLE @TableName ALTER COLUMN ReferenceID VARCHAR(8)' + (SELECT CASE WHEN C.Is_Nullable = 'NO' THEN ' NOT NULL' ELSE '' END
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE C.TABLE_NAME = @TableName AND C.COLUMN_NAME = 'ReferenceID')
SET @SQL = REPLACE(@SQL, '@TableName', @TableName)
PRINT(@SQL)
EXEC(@SQL)
--Recreate the constraint
--Some tables don't have a PK defined, only do the next bit if they do
IF (SELECT COUNT(*) FROM #PKBackup PK WHERE PK.TableName = @TableName) > 0
BEGIN
--First set up @SQL template
SELECT @SQL = 'ALTER TABLE [' + SCHEMA_NAME(PK.schema_id) + '].[' + PK.TableName
+ '] ADD CONSTRAINT [' + PK.IndexName
+ '] PRIMARY KEY ' + Type_desc + ' ( @Columns ) WITH '
+ '( PAD_INDEX = ' + CASE WHEN CAST(INDEXPROPERTY(pk.[object_id], PK.IndexName, N'IsPadIndex') AS BIT) = 0 THEN 'OFF'
ELSE 'ON'
END + ', '
+ 'STATISTICS_NORECOMPUTE = ' + CASE WHEN pk.no_recompute = 0 THEN 'OFF'
ELSE 'ON'
END
+ ', SORT_IN_TEMPDB = OFF, '
+ 'IGNORE_DUP_KEY = ' + CASE WHEN pk.[ignore_dup_key] = 0 THEN 'OFF'
ELSE 'ON'
END + ', '
+ 'ONLINE = OFF, '
+ 'ALLOW_ROW_LOCKS = ' + CASE WHEN pk.allow_row_locks = 0 THEN 'OFF'
ELSE 'ON'
END + ', '
+ 'ALLOW_PAGE_LOCKS = ' + CASE WHEN pk.allow_page_locks = 0 THEN 'OFF'
ELSE 'ON'
END + ', '
+ 'FILLFACTOR = ' + CASE WHEN pk.[fill_factor] = 0 THEN '100'
ELSE CONVERT(NVARCHAR, pk.[fill_factor])
END + ' '
+ ') ON [' + CASE WHEN 'FG' = pk.[type] THEN pk.DataSpaceName
ELSE N''
END + ']'
FROM
#PKBackup PK WHERE PK.TableName = @TableName
SET @SQL = REPLACE(@SQL, '@TableName', @TableName)
SET @SQL = REPLACE(@SQL, '@ConstraintName', @ConstraintName)
--Second, build up @Columns
SET @Columns = ' '
DECLARE ColumnCursor CURSOR LOCAL READ_ONLY FOR
SELECT pk.[column], PK.is_desc
FROM #PKBackup PK
WHERE PK.TableName = @TableName
ORDER BY PK.key_ordinal ASC
OPEN ColumnCursor
FETCH NEXT FROM ColumnCursor
INTO @tColumn, @IsDescending
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Columns = @Columns + @tColumn + CASE WHEN @IsDescending = 1 THEN ' DESC, ' ELSE ' ASC, ' END
--Get the next TableName
FETCH NEXT FROM ColumnCursor
INTO @tColumn, @IsDescending
END
--Tidy up
CLOSE ColumnCursor
DEALLOCATE ColumnCursor
--Delete the last comma
SET @Columns = LEFT(@Columns, LEN(@Columns) - 1)
END
--Recreate the constraint
SET @SQL = REPLACE(@SQL, '@Columns', @Columns)
PRINT @SQL
EXEC (@SQL)
PRINT('--Done
')
SET @SQL = ''
--Get the next TableName
FETCH NEXT FROM TableCursor
INTO @TableName
END
--Tidy up
CLOSE TableCursor
DEALLOCATE TableCursor
DROP TABLE #PKBackup
/* Handle exceptional tables here
* Replace indexes and foreign keys that were removed at the start
*/
SET NOCOUNT OFF
``` | You need to execute the `ALTER` statement as dynamic SQL: Build the statement as a SQL string and pass it to `sp_executesql`. |
11,118,568 | I have a ReferenceID varchar(6) column in over 80 different tables. I need to extend this to a varchar(8) throughout the db following a change implemented by the government organisation that assigns the IDs.
I was hoping to declare a cursor to get the table names as follows:
```
DECLARE @TableName AS VARCHAR(200)
DECLARE TableCursor CURSOR LOCAL READ_ONLY FOR
SELECT t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name = 'ReferenceID'
OPEN TableCursor
FETCH NEXT FROM TableCursor
INTO @TableName
```
and then edit the type as follows:
```
ALTER TABLE @TableName ALTER COLUMN ReferenceID VARCHAR(8)
```
This fails because the column is part of the Primary Key in some of the tables (and the columns included in the PK vary from table to table).
I really don't want to have to drop and recreate each PK manually for each table.
Within the cursor, is there a way either to disable the PK before altering the datatype and then re-enable it, or to drop and recreate the PK either side of altering the datatype, bearing in mind that the PK will depend on which table we're currently looking at? | 2012/06/20 | [
"https://Stackoverflow.com/questions/11118568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1468962/"
] | You need to specify `NOT NULL` explicitly in an `ALTER TABLE ... ALTER COLUMN` otherwise it defaults to allowing `NULL`. This is not permitted in a PK column.
The following works fine.
```
CREATE TABLE p
(
ReferenceID VARCHAR(6) NOT NULL PRIMARY KEY
)
INSERT INTO p VALUES ('AAAAAA')
ALTER TABLE p ALTER COLUMN ReferenceID VARCHAR(8) NOT NULL
```
when the `NOT NULL` is omitted it gives the following error
```
Msg 5074, Level 16, State 1, Line 1
The object 'PK__p__E1A99A792180FB33' is dependent on column 'ReferenceID'.
Msg 4922, Level 16, State 9, Line 1
ALTER TABLE ALTER COLUMN ReferenceID failed because one or more objects access this column.
```
A couple of things to consider in your programmatic approach is that you *would* need to drop any foreign keys referencing the `ReferenceID` columns temporarily and also make sure you don't include the `NOT NULL` for (Non PK) `ReferenceID` columns that currently *are* nullable. | **EDIT** This solution is needed if you have a muddled database with a mixture of varchar(6) and char(6) columns caused by development extending over 10 years (with enough changes of government policy to cause any attempt at "good database design" to collapse eventually.)
**END EDIT**
To those who said I would have to drop and recreate the PK, you were right. Indexes and Foreign Keys also needed dropping and recreating.
Fortunately, there were a manageable number of indexes and FKs so I handled these as 'exceptional' and dropped them all, one at a time, at the beginning of the script, then re-added them, one at a time, at the end of the script (see the two sections in /\* \*/ below).
The main body of the SQL script then tips complete details about the FKs into a temporary table, then loops through each table name, dropping the FK, altering the datatype, re-adding the FK.
The SQL strings that get assembled are PRINTed in the script below. If you intend to reuse this (no warranties provided, etc., blah blah), comment these out to knock up to 50% off the execution time.
```
SET NOCOUNT ON
/* Handle exceptional tables here
* Remove indexes and foreign keys
* --Lots of "IF EXISTS ... ALTER TABLE <name> DROP CONSTRAINT <constraint name>, etc.
*/
--Declare variables
DECLARE @SQL VARCHAR(8000)
DECLARE @TableName VARCHAR(512)
DECLARE @ConstraintName VARCHAR(512)
DECLARE @tColumn VARCHAR(512)
DECLARE @Columns VARCHAR(8000)
DECLARE @IsDescending BIT
--Set up temporary table
SELECT
tbl.[schema_id],
tbl.name AS TableName,
i.NAME AS IndexName,
i.type_desc,
c.[column],
c.key_ordinal,
c.is_desc,
i.[object_id],
s.no_recompute,
i.[ignore_dup_key],
i.[allow_row_locks],
i.[allow_page_locks],
i.[fill_factor],
dsi.type,
dsi.name AS DataSpaceName
INTO #PKBackup
FROM
sys.tables AS tbl
INNER JOIN sys.indexes AS i
ON (
i.index_id > 0
AND i.is_hypothetical = 0
)
AND ( i.[object_id] = tbl.[object_id] )
INNER JOIN (
SELECT
ic.[object_id] ,
c.[name] [column] ,
ic.is_descending_key [is_desc],
ic.key_ordinal
FROM
sys.index_columns ic
INNER JOIN
sys.indexes i
ON
i.[object_id] = ic.[object_id]
AND
i.index_id = 1
AND
ic.index_id = 1
INNER JOIN
sys.tables t
ON
t.[object_id] = ic.[object_id]
INNER JOIN
sys.columns c
ON
c.[object_id] = t.[object_id]
AND
c.column_id = ic.column_id
) AS c
ON c.[object_id] = i.[object_id]
LEFT OUTER JOIN
sys.key_constraints AS k
ON
k.parent_object_id = i.[object_id]
AND
k.unique_index_id = i.index_id
LEFT OUTER JOIN
sys.data_spaces AS dsi
ON
dsi.data_space_id = i.data_space_id
LEFT OUTER JOIN
sys.xml_indexes AS xi
ON
xi.[object_id] = i.[object_id]
AND
xi.index_id = i.index_id
LEFT OUTER JOIN
sys.stats AS s
ON
s.stats_id = i.index_id
AND
s.[object_id] = i.[object_id]
WHERE
k.TYPE = 'PK'
DECLARE TableCursor CURSOR LOCAL READ_ONLY FOR
SELECT t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE
c.name = 'ReferenceID'
OPEN TableCursor
FETCH NEXT FROM TableCursor
INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT('--Updating ' + @TableName + '...')
SELECT @ConstraintName = PK.CONSTRAINT_NAME
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
WHERE
PK.TABLE_NAME = @TableName
AND
PK.CONSTRAINT_TYPE = 'PRIMARY KEY'
--drop the constraint
--Some tables don't have a PK defined, only do the next bit if they do
IF (SELECT COUNT(*) FROM #PKBackup PK WHERE PK.TableName = @TableName) > 0
BEGIN
SET @SQL = 'ALTER TABLE @TableName DROP CONSTRAINT @ConstraintName'
SET @SQL = REPLACE(@SQL, '@TableName', @TableName)
SET @SQL = REPLACE(@SQL, '@ConstraintName', @ConstraintName)
PRINT @SQL
EXEC (@SQL)
END
--This is where we actually change the datatype of the column
SET @SQL = 'ALTER TABLE @TableName ALTER COLUMN ReferenceID VARCHAR(8)' + (SELECT CASE WHEN C.Is_Nullable = 'NO' THEN ' NOT NULL' ELSE '' END
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE C.TABLE_NAME = @TableName AND C.COLUMN_NAME = 'ReferenceID')
SET @SQL = REPLACE(@SQL, '@TableName', @TableName)
PRINT(@SQL)
EXEC(@SQL)
--Recreate the constraint
--Some tables don't have a PK defined, only do the next bit if they do
IF (SELECT COUNT(*) FROM #PKBackup PK WHERE PK.TableName = @TableName) > 0
BEGIN
--First set up @SQL template
SELECT @SQL = 'ALTER TABLE [' + SCHEMA_NAME(PK.schema_id) + '].[' + PK.TableName
+ '] ADD CONSTRAINT [' + PK.IndexName
+ '] PRIMARY KEY ' + Type_desc + ' ( @Columns ) WITH '
+ '( PAD_INDEX = ' + CASE WHEN CAST(INDEXPROPERTY(pk.[object_id], PK.IndexName, N'IsPadIndex') AS BIT) = 0 THEN 'OFF'
ELSE 'ON'
END + ', '
+ 'STATISTICS_NORECOMPUTE = ' + CASE WHEN pk.no_recompute = 0 THEN 'OFF'
ELSE 'ON'
END
+ ', SORT_IN_TEMPDB = OFF, '
+ 'IGNORE_DUP_KEY = ' + CASE WHEN pk.[ignore_dup_key] = 0 THEN 'OFF'
ELSE 'ON'
END + ', '
+ 'ONLINE = OFF, '
+ 'ALLOW_ROW_LOCKS = ' + CASE WHEN pk.allow_row_locks = 0 THEN 'OFF'
ELSE 'ON'
END + ', '
+ 'ALLOW_PAGE_LOCKS = ' + CASE WHEN pk.allow_page_locks = 0 THEN 'OFF'
ELSE 'ON'
END + ', '
+ 'FILLFACTOR = ' + CASE WHEN pk.[fill_factor] = 0 THEN '100'
ELSE CONVERT(NVARCHAR, pk.[fill_factor])
END + ' '
+ ') ON [' + CASE WHEN 'FG' = pk.[type] THEN pk.DataSpaceName
ELSE N''
END + ']'
FROM
#PKBackup PK WHERE PK.TableName = @TableName
SET @SQL = REPLACE(@SQL, '@TableName', @TableName)
SET @SQL = REPLACE(@SQL, '@ConstraintName', @ConstraintName)
--Second, build up @Columns
SET @Columns = ' '
DECLARE ColumnCursor CURSOR LOCAL READ_ONLY FOR
SELECT pk.[column], PK.is_desc
FROM #PKBackup PK
WHERE PK.TableName = @TableName
ORDER BY PK.key_ordinal ASC
OPEN ColumnCursor
FETCH NEXT FROM ColumnCursor
INTO @tColumn, @IsDescending
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Columns = @Columns + @tColumn + CASE WHEN @IsDescending = 1 THEN ' DESC, ' ELSE ' ASC, ' END
--Get the next TableName
FETCH NEXT FROM ColumnCursor
INTO @tColumn, @IsDescending
END
--Tidy up
CLOSE ColumnCursor
DEALLOCATE ColumnCursor
--Delete the last comma
SET @Columns = LEFT(@Columns, LEN(@Columns) - 1)
END
--Recreate the constraint
SET @SQL = REPLACE(@SQL, '@Columns', @Columns)
PRINT @SQL
EXEC (@SQL)
PRINT('--Done
')
SET @SQL = ''
--Get the next TableName
FETCH NEXT FROM TableCursor
INTO @TableName
END
--Tidy up
CLOSE TableCursor
DEALLOCATE TableCursor
DROP TABLE #PKBackup
/* Handle exceptional tables here
* Replace indexes and foreign keys that were removed at the start
*/
SET NOCOUNT OFF
``` |
11,118,568 | I have a ReferenceID varchar(6) column in over 80 different tables. I need to extend this to a varchar(8) throughout the db following a change implemented by the government organisation that assigns the IDs.
I was hoping to declare a cursor to get the table names as follows:
```
DECLARE @TableName AS VARCHAR(200)
DECLARE TableCursor CURSOR LOCAL READ_ONLY FOR
SELECT t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name = 'ReferenceID'
OPEN TableCursor
FETCH NEXT FROM TableCursor
INTO @TableName
```
and then edit the type as follows:
```
ALTER TABLE @TableName ALTER COLUMN ReferenceID VARCHAR(8)
```
This fails because the column is part of the Primary Key in some of the tables (and the columns included in the PK vary from table to table).
I really don't want to have to drop and recreate each PK manually for each table.
Within the cursor, is there a way either to disable the PK before altering the datatype and then re-enable it, or to drop and recreate the PK either side of altering the datatype, bearing in mind that the PK will depend on which table we're currently looking at? | 2012/06/20 | [
"https://Stackoverflow.com/questions/11118568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1468962/"
] | You need to specify `NOT NULL` explicitly in an `ALTER TABLE ... ALTER COLUMN` otherwise it defaults to allowing `NULL`. This is not permitted in a PK column.
The following works fine.
```
CREATE TABLE p
(
ReferenceID VARCHAR(6) NOT NULL PRIMARY KEY
)
INSERT INTO p VALUES ('AAAAAA')
ALTER TABLE p ALTER COLUMN ReferenceID VARCHAR(8) NOT NULL
```
when the `NOT NULL` is omitted it gives the following error
```
Msg 5074, Level 16, State 1, Line 1
The object 'PK__p__E1A99A792180FB33' is dependent on column 'ReferenceID'.
Msg 4922, Level 16, State 9, Line 1
ALTER TABLE ALTER COLUMN ReferenceID failed because one or more objects access this column.
```
A couple of things to consider in your programmatic approach is that you *would* need to drop any foreign keys referencing the `ReferenceID` columns temporarily and also make sure you don't include the `NOT NULL` for (Non PK) `ReferenceID` columns that currently *are* nullable. | From my experience of databases over 30 years, the one constant is the need for continual changes of the structure of any database you are working with, as data requirements change. Furthermore, there are plenty of instances where an auto-increment primary key is not the most appropriate, in particular where you want to ensure that the data remains meaningfully accessible directly through the DBMS (e.g. SQL Server) when the program that used the database is no longer available. One of the great flaws of database management is the usual impenetrability of the database when the program has died - something that runs completely counter to the principle of long-term data management.
Therefore, the inability to easily change the size of a primary key field is NOT because of poor database design, it is because the DBMS and SQL tools to handle the database are grossly inadequate, clearly designed by programmers with a theoretical rather than an actual understanding of the real world. Other examples of such programming flaws are array indexes starting from 0 rather than 1 (the number of errors arising from having to add or subtract 1 to switch from index to count are legion), the inability for numeric variables to natively handle null values, etc. I look forward to the day when database structure modification is seen as a mainstream necessity, rather than arising from so-called poor database design. |
11,118,568 | I have a ReferenceID varchar(6) column in over 80 different tables. I need to extend this to a varchar(8) throughout the db following a change implemented by the government organisation that assigns the IDs.
I was hoping to declare a cursor to get the table names as follows:
```
DECLARE @TableName AS VARCHAR(200)
DECLARE TableCursor CURSOR LOCAL READ_ONLY FOR
SELECT t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name = 'ReferenceID'
OPEN TableCursor
FETCH NEXT FROM TableCursor
INTO @TableName
```
and then edit the type as follows:
```
ALTER TABLE @TableName ALTER COLUMN ReferenceID VARCHAR(8)
```
This fails because the column is part of the Primary Key in some of the tables (and the columns included in the PK vary from table to table).
I really don't want to have to drop and recreate each PK manually for each table.
Within the cursor, is there a way either to disable the PK before altering the datatype and then re-enable it, or to drop and recreate the PK either side of altering the datatype, bearing in mind that the PK will depend on which table we're currently looking at? | 2012/06/20 | [
"https://Stackoverflow.com/questions/11118568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1468962/"
] | **EDIT** This solution is needed if you have a muddled database with a mixture of varchar(6) and char(6) columns caused by development extending over 10 years (with enough changes of government policy to cause any attempt at "good database design" to collapse eventually.)
**END EDIT**
To those who said I would have to drop and recreate the PK, you were right. Indexes and Foreign Keys also needed dropping and recreating.
Fortunately, there were a manageable number of indexes and FKs so I handled these as 'exceptional' and dropped them all, one at a time, at the beginning of the script, then re-added them, one at a time, at the end of the script (see the two sections in /\* \*/ below).
The main body of the SQL script then tips complete details about the FKs into a temporary table, then loops through each table name, dropping the FK, altering the datatype, re-adding the FK.
The SQL strings that get assembled are PRINTed in the script below. If you intend to reuse this (no warranties provided, etc., blah blah), comment these out to knock up to 50% off the execution time.
```
SET NOCOUNT ON
/* Handle exceptional tables here
* Remove indexes and foreign keys
* --Lots of "IF EXISTS ... ALTER TABLE <name> DROP CONSTRAINT <constraint name>, etc.
*/
--Declare variables
DECLARE @SQL VARCHAR(8000)
DECLARE @TableName VARCHAR(512)
DECLARE @ConstraintName VARCHAR(512)
DECLARE @tColumn VARCHAR(512)
DECLARE @Columns VARCHAR(8000)
DECLARE @IsDescending BIT
--Set up temporary table
SELECT
tbl.[schema_id],
tbl.name AS TableName,
i.NAME AS IndexName,
i.type_desc,
c.[column],
c.key_ordinal,
c.is_desc,
i.[object_id],
s.no_recompute,
i.[ignore_dup_key],
i.[allow_row_locks],
i.[allow_page_locks],
i.[fill_factor],
dsi.type,
dsi.name AS DataSpaceName
INTO #PKBackup
FROM
sys.tables AS tbl
INNER JOIN sys.indexes AS i
ON (
i.index_id > 0
AND i.is_hypothetical = 0
)
AND ( i.[object_id] = tbl.[object_id] )
INNER JOIN (
SELECT
ic.[object_id] ,
c.[name] [column] ,
ic.is_descending_key [is_desc],
ic.key_ordinal
FROM
sys.index_columns ic
INNER JOIN
sys.indexes i
ON
i.[object_id] = ic.[object_id]
AND
i.index_id = 1
AND
ic.index_id = 1
INNER JOIN
sys.tables t
ON
t.[object_id] = ic.[object_id]
INNER JOIN
sys.columns c
ON
c.[object_id] = t.[object_id]
AND
c.column_id = ic.column_id
) AS c
ON c.[object_id] = i.[object_id]
LEFT OUTER JOIN
sys.key_constraints AS k
ON
k.parent_object_id = i.[object_id]
AND
k.unique_index_id = i.index_id
LEFT OUTER JOIN
sys.data_spaces AS dsi
ON
dsi.data_space_id = i.data_space_id
LEFT OUTER JOIN
sys.xml_indexes AS xi
ON
xi.[object_id] = i.[object_id]
AND
xi.index_id = i.index_id
LEFT OUTER JOIN
sys.stats AS s
ON
s.stats_id = i.index_id
AND
s.[object_id] = i.[object_id]
WHERE
k.TYPE = 'PK'
DECLARE TableCursor CURSOR LOCAL READ_ONLY FOR
SELECT t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE
c.name = 'ReferenceID'
OPEN TableCursor
FETCH NEXT FROM TableCursor
INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT('--Updating ' + @TableName + '...')
SELECT @ConstraintName = PK.CONSTRAINT_NAME
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
WHERE
PK.TABLE_NAME = @TableName
AND
PK.CONSTRAINT_TYPE = 'PRIMARY KEY'
--drop the constraint
--Some tables don't have a PK defined, only do the next bit if they do
IF (SELECT COUNT(*) FROM #PKBackup PK WHERE PK.TableName = @TableName) > 0
BEGIN
SET @SQL = 'ALTER TABLE @TableName DROP CONSTRAINT @ConstraintName'
SET @SQL = REPLACE(@SQL, '@TableName', @TableName)
SET @SQL = REPLACE(@SQL, '@ConstraintName', @ConstraintName)
PRINT @SQL
EXEC (@SQL)
END
--This is where we actually change the datatype of the column
SET @SQL = 'ALTER TABLE @TableName ALTER COLUMN ReferenceID VARCHAR(8)' + (SELECT CASE WHEN C.Is_Nullable = 'NO' THEN ' NOT NULL' ELSE '' END
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE C.TABLE_NAME = @TableName AND C.COLUMN_NAME = 'ReferenceID')
SET @SQL = REPLACE(@SQL, '@TableName', @TableName)
PRINT(@SQL)
EXEC(@SQL)
--Recreate the constraint
--Some tables don't have a PK defined, only do the next bit if they do
IF (SELECT COUNT(*) FROM #PKBackup PK WHERE PK.TableName = @TableName) > 0
BEGIN
--First set up @SQL template
SELECT @SQL = 'ALTER TABLE [' + SCHEMA_NAME(PK.schema_id) + '].[' + PK.TableName
+ '] ADD CONSTRAINT [' + PK.IndexName
+ '] PRIMARY KEY ' + Type_desc + ' ( @Columns ) WITH '
+ '( PAD_INDEX = ' + CASE WHEN CAST(INDEXPROPERTY(pk.[object_id], PK.IndexName, N'IsPadIndex') AS BIT) = 0 THEN 'OFF'
ELSE 'ON'
END + ', '
+ 'STATISTICS_NORECOMPUTE = ' + CASE WHEN pk.no_recompute = 0 THEN 'OFF'
ELSE 'ON'
END
+ ', SORT_IN_TEMPDB = OFF, '
+ 'IGNORE_DUP_KEY = ' + CASE WHEN pk.[ignore_dup_key] = 0 THEN 'OFF'
ELSE 'ON'
END + ', '
+ 'ONLINE = OFF, '
+ 'ALLOW_ROW_LOCKS = ' + CASE WHEN pk.allow_row_locks = 0 THEN 'OFF'
ELSE 'ON'
END + ', '
+ 'ALLOW_PAGE_LOCKS = ' + CASE WHEN pk.allow_page_locks = 0 THEN 'OFF'
ELSE 'ON'
END + ', '
+ 'FILLFACTOR = ' + CASE WHEN pk.[fill_factor] = 0 THEN '100'
ELSE CONVERT(NVARCHAR, pk.[fill_factor])
END + ' '
+ ') ON [' + CASE WHEN 'FG' = pk.[type] THEN pk.DataSpaceName
ELSE N''
END + ']'
FROM
#PKBackup PK WHERE PK.TableName = @TableName
SET @SQL = REPLACE(@SQL, '@TableName', @TableName)
SET @SQL = REPLACE(@SQL, '@ConstraintName', @ConstraintName)
--Second, build up @Columns
SET @Columns = ' '
DECLARE ColumnCursor CURSOR LOCAL READ_ONLY FOR
SELECT pk.[column], PK.is_desc
FROM #PKBackup PK
WHERE PK.TableName = @TableName
ORDER BY PK.key_ordinal ASC
OPEN ColumnCursor
FETCH NEXT FROM ColumnCursor
INTO @tColumn, @IsDescending
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Columns = @Columns + @tColumn + CASE WHEN @IsDescending = 1 THEN ' DESC, ' ELSE ' ASC, ' END
--Get the next TableName
FETCH NEXT FROM ColumnCursor
INTO @tColumn, @IsDescending
END
--Tidy up
CLOSE ColumnCursor
DEALLOCATE ColumnCursor
--Delete the last comma
SET @Columns = LEFT(@Columns, LEN(@Columns) - 1)
END
--Recreate the constraint
SET @SQL = REPLACE(@SQL, '@Columns', @Columns)
PRINT @SQL
EXEC (@SQL)
PRINT('--Done
')
SET @SQL = ''
--Get the next TableName
FETCH NEXT FROM TableCursor
INTO @TableName
END
--Tidy up
CLOSE TableCursor
DEALLOCATE TableCursor
DROP TABLE #PKBackup
/* Handle exceptional tables here
* Replace indexes and foreign keys that were removed at the start
*/
SET NOCOUNT OFF
``` | From my experience of databases over 30 years, the one constant is the need for continual changes of the structure of any database you are working with, as data requirements change. Furthermore, there are plenty of instances where an auto-increment primary key is not the most appropriate, in particular where you want to ensure that the data remains meaningfully accessible directly through the DBMS (e.g. SQL Server) when the program that used the database is no longer available. One of the great flaws of database management is the usual impenetrability of the database when the program has died - something that runs completely counter to the principle of long-term data management.
Therefore, the inability to easily change the size of a primary key field is NOT because of poor database design, it is because the DBMS and SQL tools to handle the database are grossly inadequate, clearly designed by programmers with a theoretical rather than an actual understanding of the real world. Other examples of such programming flaws are array indexes starting from 0 rather than 1 (the number of errors arising from having to add or subtract 1 to switch from index to count are legion), the inability for numeric variables to natively handle null values, etc. I look forward to the day when database structure modification is seen as a mainstream necessity, rather than arising from so-called poor database design. |
1,440,897 | Recently, I encountered the following integration:
$$\int\_0^1 \sqrt{\int\_0^1 f(x,y)dx}\ dy$$
where $f(x,y)$ is rather complex. We know that with the help of Mathematica it is easy to compute the numerical value of $\int\_0^1 \int\_0^1 f(x,y)dxdy$. However, it becomes useless to handle with the integration I mentioned above. I am wondering if there are any methods that can simplify this integration to the form of $\int\_0^1 \int\_0^1 g(x,y)dxdy$, or can we find any efficient way to compute its numerical value? | 2015/09/18 | [
"https://math.stackexchange.com/questions/1440897",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/58882/"
] | Outline
Use $\sin a\sin b = \frac{1}{2}( \cos(a-b) - \cos(a+b))$.
Expand the summation, it will be a telescoping series. All terms except 2 will cancel out. As n becomes large, one of the terms will tend to 1, the other one will be $\cos a$. The final answer should be $1 - \cos a$ | HINT:
Using Werner's fomrula:
$$2\sin\dfrac a{3^n}\cdot\sin\dfrac{2a}{3^n}=\cos\dfrac{2a-a}{3^n}-\cos\dfrac{2a+a}{3^n}=f(n)-f(n-1)$$
where $f(m)=\cos\dfrac a{3^m}$
which leads to Telescoping Series |
1,440,897 | Recently, I encountered the following integration:
$$\int\_0^1 \sqrt{\int\_0^1 f(x,y)dx}\ dy$$
where $f(x,y)$ is rather complex. We know that with the help of Mathematica it is easy to compute the numerical value of $\int\_0^1 \int\_0^1 f(x,y)dxdy$. However, it becomes useless to handle with the integration I mentioned above. I am wondering if there are any methods that can simplify this integration to the form of $\int\_0^1 \int\_0^1 g(x,y)dxdy$, or can we find any efficient way to compute its numerical value? | 2015/09/18 | [
"https://math.stackexchange.com/questions/1440897",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/58882/"
] | HINT: Notice $$\sum\_{n=1}^{\infty}\sin\left(\frac{a}{3^n}\right)\sin\left(\frac{2a}{3^n}\right)$$
$$=\sum\_{n=1}^{\infty}\frac{1}{2}\left(2\sin\left(\frac{a}{3^n}\right)\sin\left(\frac{2a}{3^n}\right)\right)$$
$$=\sum\_{n=1}^{\infty}\frac{1}{2}\left(\cos\left(\frac{a}{3^n}-\frac{2a}{3^n}\right)-\cos\left(\frac{a}{3^n}+\frac{2a}{3^n}\right)\right)$$
$$=\frac{1}{2}\sum\_{n=1}^{\infty}\left(\cos\left(\frac{a}{3^n}\right)-\cos\left(\frac{a}{3^{n-1}}\right)\right)$$ | Outline
Use $\sin a\sin b = \frac{1}{2}( \cos(a-b) - \cos(a+b))$.
Expand the summation, it will be a telescoping series. All terms except 2 will cancel out. As n becomes large, one of the terms will tend to 1, the other one will be $\cos a$. The final answer should be $1 - \cos a$ |
1,440,897 | Recently, I encountered the following integration:
$$\int\_0^1 \sqrt{\int\_0^1 f(x,y)dx}\ dy$$
where $f(x,y)$ is rather complex. We know that with the help of Mathematica it is easy to compute the numerical value of $\int\_0^1 \int\_0^1 f(x,y)dxdy$. However, it becomes useless to handle with the integration I mentioned above. I am wondering if there are any methods that can simplify this integration to the form of $\int\_0^1 \int\_0^1 g(x,y)dxdy$, or can we find any efficient way to compute its numerical value? | 2015/09/18 | [
"https://math.stackexchange.com/questions/1440897",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/58882/"
] | HINT: Notice $$\sum\_{n=1}^{\infty}\sin\left(\frac{a}{3^n}\right)\sin\left(\frac{2a}{3^n}\right)$$
$$=\sum\_{n=1}^{\infty}\frac{1}{2}\left(2\sin\left(\frac{a}{3^n}\right)\sin\left(\frac{2a}{3^n}\right)\right)$$
$$=\sum\_{n=1}^{\infty}\frac{1}{2}\left(\cos\left(\frac{a}{3^n}-\frac{2a}{3^n}\right)-\cos\left(\frac{a}{3^n}+\frac{2a}{3^n}\right)\right)$$
$$=\frac{1}{2}\sum\_{n=1}^{\infty}\left(\cos\left(\frac{a}{3^n}\right)-\cos\left(\frac{a}{3^{n-1}}\right)\right)$$ | HINT:
Using Werner's fomrula:
$$2\sin\dfrac a{3^n}\cdot\sin\dfrac{2a}{3^n}=\cos\dfrac{2a-a}{3^n}-\cos\dfrac{2a+a}{3^n}=f(n)-f(n-1)$$
where $f(m)=\cos\dfrac a{3^m}$
which leads to Telescoping Series |
16,670,282 | I started working with Ruby on Rails 3 weeks ago, loving it so far but I need some help.
I'm working on an web app that, among others, tracks the location of a user and stores it periodically in the db.
The javascript for getting the location every minute is working but I don't know how to store this location in the db.
The script is defined in the application view. I managed to call an update\_location action defined in the UsersController using ajax with POST. The lat long columns are updated corectly but a page redirect occurs. I want the update process to be async and hidden from the user.
When I tried using a PUT ajax request (POST with \_method=PUT) i get a URL not found for user/:id/location\_update.
I am a complete beginner i RoR and even in Web Dev.
P.S. I am using Rails 4.
Edit: Using $.ajax or $.post with \_method : "PUT" and URL /update\_location triggers the following 500 error
```
ActionView::MissingTemplate (Missing template users/update_location, application/update_location with {:locale=>[:en], :formats=>[...]}. Searched in:
* "/home/.../app/views"
):
```
My update\_location action looks like this
```
def update_location
@car = Car.find(3)
if @car.update_attributes(location_params)
end
end
```
The db is getting updated but I still get that error. | 2013/05/21 | [
"https://Stackoverflow.com/questions/16670282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/966929/"
] | How about something like:
```
class Border
constructor: (@options) ->
class RedBorder extends Border
constructor: (@options) ->
class BlueBorder extends Border
constructor: (@options) ->
borders =
Default: Border
Red: RedBorder
Blue: BlueBorder
$.plugin = (element, options) ->
@mainClass = new borders[@settings.class || 'Default'](@settings)
``` | your second approach will fail as you cant instantiate a "String"
```
@Framer = new @settings['classToUse'](this.$element, this.settings)
```
also there seems to be an error as you are using "type" instead of "classToUse"
The easiest way to would seem to simply put the class-object into the hash that you give to jQuery
```
jQuery('img').myPlugin({classToUse : redBorder});
```
In this example assuming that *redBorder* is the class name. |
18,751,737 | When I try and test my html form, it displays a white screen. Here's my code.
index.html
```
<form name="form1" method="post" action="test.php">
<textarea name="data" cols="100" rows="10">
Facebook:
Twitter:
Instagram:
Website:
Comments:
---------------------------------------------
</textarea>
<br>
<input type="submit" value="Save">
</form>
```
test.php
```
<html>
<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On'); //On or Off
$saving = $_REQUEST['saving'];
if ($saving == 1){
$data = $_POST['data'];
$file = "data.txt";
$fp = fopen($file, "a") or die("Couldn't open $file for writing!");
fwrite($fp, $data) or die("Couldn't write values to file!");
fclose($fp);
echo "Saved to $file successfully!";
}
?>
</html>
```
I can 'view source' on the page, but I just get the code above in the php file. The title of the page is displaying the test.php page. Should it be doing this? PHP newbie. Thanks in advance. | 2013/09/11 | [
"https://Stackoverflow.com/questions/18751737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2692247/"
] | I don't think you are getting into the if code
```
$saving = $_REQUEST['saving'];
if ($saving == 1) {
$data = $_POST['data'];
$file = "data.txt";
$fp = fopen($file, "a") or die("Couldn't open $file for writing!");
fwrite($fp, $data) or die("Couldn't write values to file!");
fclose($fp);
echo "Saved to $file successfully!";
} else {
echo 'Nope!';
}
```
Try adding this ELSE and see if you see 'Nope'.
For starters, what is $\_REQUEST['saving']? It isn't an input on the form so it is probably a nothing.
Do this instead:
```
if ($_POST) {
$data = $_POST['data'];
$file = "data.txt";
$fp = fopen($file, "a") or die("Couldn't open $file for writing!");
fwrite($fp, $data) or die("Couldn't write values to file!");
fclose($fp);
echo "Saved to $file successfully!";
} else {
echo 'Nope!';
}
``` | Change your html:
```
<input type="submit" value="Save" name="saving"/>
```
Also change the php where you are accepting the param:
```
$saving = $_REQUEST['saving'];
if ($saving) { // it is enough to just check if there is a value, the actual value is "Save"
...
}
``` |
18,751,737 | When I try and test my html form, it displays a white screen. Here's my code.
index.html
```
<form name="form1" method="post" action="test.php">
<textarea name="data" cols="100" rows="10">
Facebook:
Twitter:
Instagram:
Website:
Comments:
---------------------------------------------
</textarea>
<br>
<input type="submit" value="Save">
</form>
```
test.php
```
<html>
<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On'); //On or Off
$saving = $_REQUEST['saving'];
if ($saving == 1){
$data = $_POST['data'];
$file = "data.txt";
$fp = fopen($file, "a") or die("Couldn't open $file for writing!");
fwrite($fp, $data) or die("Couldn't write values to file!");
fclose($fp);
echo "Saved to $file successfully!";
}
?>
</html>
```
I can 'view source' on the page, but I just get the code above in the php file. The title of the page is displaying the test.php page. Should it be doing this? PHP newbie. Thanks in advance. | 2013/09/11 | [
"https://Stackoverflow.com/questions/18751737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2692247/"
] | Give this a try, tested. (no white screen)
------------------------------------------
Use both bodies of code as written.
I added a condition in case someone tries to access `test.php` directly.
HTML form
---------
```
<form name="form1" method="post" action="test.php">
<textarea name="data" cols="100" rows="10">
Facebook:
Twitter:
Instagram:
Website:
Comments:
---------------------------------------------
</textarea>
<br>
<input type="submit" name="submit" value="Save">
</form>
```
PHP hander (test.php)
---------------------
```
<html>
<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On'); //On or Off
if(!isset($_REQUEST['data'])) {
echo "You cannot do that from here.";
exit;
}
else {
$data = $_REQUEST['data'];
}
if(isset($_REQUEST['submit'])) {
$file = "data.txt";
chmod($file, 0777);
// chmod($file, 0644); // or use 644 which is safer
$fp = fopen($file, "a") or die("Couldn't open $file for writing!");
fwrite($fp, $data) or die("Couldn't write values to file!");
fclose($fp);
echo "Saved to $file successfully!";
}
else {
echo "Submit not set.";
}
?>
</html>
``` | I don't think you are getting into the if code
```
$saving = $_REQUEST['saving'];
if ($saving == 1) {
$data = $_POST['data'];
$file = "data.txt";
$fp = fopen($file, "a") or die("Couldn't open $file for writing!");
fwrite($fp, $data) or die("Couldn't write values to file!");
fclose($fp);
echo "Saved to $file successfully!";
} else {
echo 'Nope!';
}
```
Try adding this ELSE and see if you see 'Nope'.
For starters, what is $\_REQUEST['saving']? It isn't an input on the form so it is probably a nothing.
Do this instead:
```
if ($_POST) {
$data = $_POST['data'];
$file = "data.txt";
$fp = fopen($file, "a") or die("Couldn't open $file for writing!");
fwrite($fp, $data) or die("Couldn't write values to file!");
fclose($fp);
echo "Saved to $file successfully!";
} else {
echo 'Nope!';
}
``` |
18,751,737 | When I try and test my html form, it displays a white screen. Here's my code.
index.html
```
<form name="form1" method="post" action="test.php">
<textarea name="data" cols="100" rows="10">
Facebook:
Twitter:
Instagram:
Website:
Comments:
---------------------------------------------
</textarea>
<br>
<input type="submit" value="Save">
</form>
```
test.php
```
<html>
<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On'); //On or Off
$saving = $_REQUEST['saving'];
if ($saving == 1){
$data = $_POST['data'];
$file = "data.txt";
$fp = fopen($file, "a") or die("Couldn't open $file for writing!");
fwrite($fp, $data) or die("Couldn't write values to file!");
fclose($fp);
echo "Saved to $file successfully!";
}
?>
</html>
```
I can 'view source' on the page, but I just get the code above in the php file. The title of the page is displaying the test.php page. Should it be doing this? PHP newbie. Thanks in advance. | 2013/09/11 | [
"https://Stackoverflow.com/questions/18751737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2692247/"
] | Give this a try, tested. (no white screen)
------------------------------------------
Use both bodies of code as written.
I added a condition in case someone tries to access `test.php` directly.
HTML form
---------
```
<form name="form1" method="post" action="test.php">
<textarea name="data" cols="100" rows="10">
Facebook:
Twitter:
Instagram:
Website:
Comments:
---------------------------------------------
</textarea>
<br>
<input type="submit" name="submit" value="Save">
</form>
```
PHP hander (test.php)
---------------------
```
<html>
<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On'); //On or Off
if(!isset($_REQUEST['data'])) {
echo "You cannot do that from here.";
exit;
}
else {
$data = $_REQUEST['data'];
}
if(isset($_REQUEST['submit'])) {
$file = "data.txt";
chmod($file, 0777);
// chmod($file, 0644); // or use 644 which is safer
$fp = fopen($file, "a") or die("Couldn't open $file for writing!");
fwrite($fp, $data) or die("Couldn't write values to file!");
fclose($fp);
echo "Saved to $file successfully!";
}
else {
echo "Submit not set.";
}
?>
</html>
``` | Change your html:
```
<input type="submit" value="Save" name="saving"/>
```
Also change the php where you are accepting the param:
```
$saving = $_REQUEST['saving'];
if ($saving) { // it is enough to just check if there is a value, the actual value is "Save"
...
}
``` |
19,167,297 | I want to delete any files older than an hour. This is for automatically cleaning up a tmp uploads directory.
Here is my code:
```
fs.readdir( dirPath, function( err, files ) {
if ( err ) return console.log( err );
files.forEach(function( file ) {
var filePath = dirPath + file;
fs.stat( filePath, function( err, stat ) {
if ( err ) return console.log( err );
var livesUntil = new Date();
livesUntil.setHours(livesUntil.getHours() - 1);
if ( stat.ctime < livesUntil ) {
fs.unlink( filePath, function( err ) {
if ( err ) return console.log( err );
});
}
});
});
});
```
However this just deletes everything in the directory, regardless of whether or not it was uploaded over an hour ago.
Am I misunderstanding how to check the age of the file in Node? | 2013/10/03 | [
"https://Stackoverflow.com/questions/19167297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031947/"
] | I am using [rimraf](https://github.com/isaacs/rimraf) to recursively delete any file/folder that is older than one hour.
According to the [docs](http://nodejs.org/api/fs.html#fs_class_fs_stats), you should use [getTime()](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime) on the ctime [Date](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) object instance in order to compare.
```
var uploadsDir = __dirname + '/uploads';
fs.readdir(uploadsDir, function(err, files) {
files.forEach(function(file, index) {
fs.stat(path.join(uploadsDir, file), function(err, stat) {
var endTime, now;
if (err) {
return console.error(err);
}
now = new Date().getTime();
endTime = new Date(stat.ctime).getTime() + 3600000;
if (now > endTime) {
return rimraf(path.join(uploadsDir, file), function(err) {
if (err) {
return console.error(err);
}
console.log('successfully deleted');
});
}
});
});
});
``` | I tried to create my own function thanks to other response in this topic. It is a *typescript style* using like an Helper in a @NestJs project (used for ExceptionHandling here).
### Dependencies
I'm also using
* [momentJs](https://momentjs.com/) for definig date
* Node js [fs](https://nodejs.org/api/fs.html) package
* and [path](https://nodejs.org/api/path.html)
### Parameter
* *parentDirectory* : the directory where the function will walk through and delete all files older than `60 hours`
```
import * as path from 'path';
import * as fs from 'fs';
import * as moment from 'moment';
import { InternalServerErrorException } from '@nestjs/common';
export default function walk(parentDirectory: string): void {
let list;
let i = 0;
try {
// store list of all file and directory in the current directory
list = fs.readdirSync(parentDirectory);
} catch (e) {
throw new InternalServerErrorException(e.toString());
}
return (function next() {
const file = list[i++];
if (file) {
const filePath = path.resolve(parentDirectory, file);
const stat = fs.statSync(filePath);
if (stat && stat.isDirectory()) {
// if it's a directory, continue walking
walk(filePath);
return next();
} else {
// see stats of the file for its creation date
fs.stat(filePath, (err, stat) => {
if (err) console.error(err);
// using moment.js to compare expiration date
const now = moment();
const endTimeFile = moment(stat.ctimeMs).add(60, 'minutes');
if (now > endTimeFile) {
try {
// delete file if expired
fs.unlinkSync(filePath);
console.log(`successfully deleted ${filePath}`);
} catch (err) {
throw new InternalServerErrorException(
'file not deleted successfully',
);
}
}
});
return next();
}
}
})();
}
``` |
19,167,297 | I want to delete any files older than an hour. This is for automatically cleaning up a tmp uploads directory.
Here is my code:
```
fs.readdir( dirPath, function( err, files ) {
if ( err ) return console.log( err );
files.forEach(function( file ) {
var filePath = dirPath + file;
fs.stat( filePath, function( err, stat ) {
if ( err ) return console.log( err );
var livesUntil = new Date();
livesUntil.setHours(livesUntil.getHours() - 1);
if ( stat.ctime < livesUntil ) {
fs.unlink( filePath, function( err ) {
if ( err ) return console.log( err );
});
}
});
});
});
```
However this just deletes everything in the directory, regardless of whether or not it was uploaded over an hour ago.
Am I misunderstanding how to check the age of the file in Node? | 2013/10/03 | [
"https://Stackoverflow.com/questions/19167297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031947/"
] | I've used [find-remove](https://www.npmjs.com/package/find-remove#delete-all-jpg-files-older-than-one-hour) for a similar usecase.
According to the documentation and what you are trying to do, the code will be:
```
var findRemoveSync = require('find-remove');
findRemoveSync(__dirname + '/uploads', {age: {seconds: 3600}});
```
I'm actually running that every 6 minutes and deleting files older than 1 hour by doing:
```
setInterval(findRemoveSync.bind(this,__dirname + '/uploads', {age: {seconds: 3600}}), 360000)
```
See [this](https://github.com/watson-developer-cloud/document-conversion-nodejs/blob/master/app.js) example on how I'm using find-remove to cleanup the `/uploads` folder. | I tried to create my own function thanks to other response in this topic. It is a *typescript style* using like an Helper in a @NestJs project (used for ExceptionHandling here).
### Dependencies
I'm also using
* [momentJs](https://momentjs.com/) for definig date
* Node js [fs](https://nodejs.org/api/fs.html) package
* and [path](https://nodejs.org/api/path.html)
### Parameter
* *parentDirectory* : the directory where the function will walk through and delete all files older than `60 hours`
```
import * as path from 'path';
import * as fs from 'fs';
import * as moment from 'moment';
import { InternalServerErrorException } from '@nestjs/common';
export default function walk(parentDirectory: string): void {
let list;
let i = 0;
try {
// store list of all file and directory in the current directory
list = fs.readdirSync(parentDirectory);
} catch (e) {
throw new InternalServerErrorException(e.toString());
}
return (function next() {
const file = list[i++];
if (file) {
const filePath = path.resolve(parentDirectory, file);
const stat = fs.statSync(filePath);
if (stat && stat.isDirectory()) {
// if it's a directory, continue walking
walk(filePath);
return next();
} else {
// see stats of the file for its creation date
fs.stat(filePath, (err, stat) => {
if (err) console.error(err);
// using moment.js to compare expiration date
const now = moment();
const endTimeFile = moment(stat.ctimeMs).add(60, 'minutes');
if (now > endTimeFile) {
try {
// delete file if expired
fs.unlinkSync(filePath);
console.log(`successfully deleted ${filePath}`);
} catch (err) {
throw new InternalServerErrorException(
'file not deleted successfully',
);
}
}
});
return next();
}
}
})();
}
``` |
19,167,297 | I want to delete any files older than an hour. This is for automatically cleaning up a tmp uploads directory.
Here is my code:
```
fs.readdir( dirPath, function( err, files ) {
if ( err ) return console.log( err );
files.forEach(function( file ) {
var filePath = dirPath + file;
fs.stat( filePath, function( err, stat ) {
if ( err ) return console.log( err );
var livesUntil = new Date();
livesUntil.setHours(livesUntil.getHours() - 1);
if ( stat.ctime < livesUntil ) {
fs.unlink( filePath, function( err ) {
if ( err ) return console.log( err );
});
}
});
});
});
```
However this just deletes everything in the directory, regardless of whether or not it was uploaded over an hour ago.
Am I misunderstanding how to check the age of the file in Node? | 2013/10/03 | [
"https://Stackoverflow.com/questions/19167297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031947/"
] | I've used [find-remove](https://www.npmjs.com/package/find-remove#delete-all-jpg-files-older-than-one-hour) for a similar usecase.
According to the documentation and what you are trying to do, the code will be:
```
var findRemoveSync = require('find-remove');
findRemoveSync(__dirname + '/uploads', {age: {seconds: 3600}});
```
I'm actually running that every 6 minutes and deleting files older than 1 hour by doing:
```
setInterval(findRemoveSync.bind(this,__dirname + '/uploads', {age: {seconds: 3600}}), 360000)
```
See [this](https://github.com/watson-developer-cloud/document-conversion-nodejs/blob/master/app.js) example on how I'm using find-remove to cleanup the `/uploads` folder. | Here's a plain Node script (for instance name it `cleanlogs.js`), tested on `v18.7.0` using the fs promises api (native module). You really dont need any fancy npm modules:
```js
import * as fs from 'node:fs/promises';
import path from 'path';
/**
* Remove all files in a directory older than the given number of seconds.
* @param {String} directory The directory to look in.
* @param {String[]} extensions The file extensions to match.
* @param {Number} seconds The minimum number of seconds since the creation time of the file.
*/
(async (directory, extensions, seconds) => {
const currentTime = Math.floor(new Date().getTime() / 1000);
const files = Array.from(await fs.readdir(directory)).filter((file) => {
return extensions.indexOf(file.split('.').at(-1)) !== -1;
});
for (const file of files) {
const filePath = path.join(directory, file);
const stats = await fs.stat(filePath);
const birthTime = Math.floor(stats.birthtimeMs / 1000);
if (currentTime - birthTime > seconds) {
fs.rm(filePath);
}
}
})('./logs', ['log'], 60 * 60 * 12);
```
The example removes files in the `./logs` directory for any file with the `log` extension (e.g. `error.log`), older than 12 hours (`60 * 60 * 12` seconds). |
19,167,297 | I want to delete any files older than an hour. This is for automatically cleaning up a tmp uploads directory.
Here is my code:
```
fs.readdir( dirPath, function( err, files ) {
if ( err ) return console.log( err );
files.forEach(function( file ) {
var filePath = dirPath + file;
fs.stat( filePath, function( err, stat ) {
if ( err ) return console.log( err );
var livesUntil = new Date();
livesUntil.setHours(livesUntil.getHours() - 1);
if ( stat.ctime < livesUntil ) {
fs.unlink( filePath, function( err ) {
if ( err ) return console.log( err );
});
}
});
});
});
```
However this just deletes everything in the directory, regardless of whether or not it was uploaded over an hour ago.
Am I misunderstanding how to check the age of the file in Node? | 2013/10/03 | [
"https://Stackoverflow.com/questions/19167297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031947/"
] | I've used [find-remove](https://www.npmjs.com/package/find-remove#delete-all-jpg-files-older-than-one-hour) for a similar usecase.
According to the documentation and what you are trying to do, the code will be:
```
var findRemoveSync = require('find-remove');
findRemoveSync(__dirname + '/uploads', {age: {seconds: 3600}});
```
I'm actually running that every 6 minutes and deleting files older than 1 hour by doing:
```
setInterval(findRemoveSync.bind(this,__dirname + '/uploads', {age: {seconds: 3600}}), 360000)
```
See [this](https://github.com/watson-developer-cloud/document-conversion-nodejs/blob/master/app.js) example on how I'm using find-remove to cleanup the `/uploads` folder. | Simple recursive solution only del all files !dirs run every 5 hours del older files that 1 day
```
const fs = require('fs');
const path = require('path');
setInterval(function() {
walkDir('./tmpimages/', function(filePath) {
fs.stat(filePath, function(err, stat) {
var now = new Date().getTime();
var endTime = new Date(stat.mtime).getTime() + 86400000; // 1days in miliseconds
if (err) { return console.error(err); }
if (now > endTime) {
//console.log('DEL:', filePath);
return fs.unlink(filePath, function(err) {
if (err) return console.error(err);
});
}
})
});
}, 18000000); // every 5 hours
function walkDir(dir, callback) {
fs.readdirSync(dir).forEach( f => {
let dirPath = path.join(dir, f);
let isDirectory = fs.statSync(dirPath).isDirectory();
isDirectory ?
walkDir(dirPath, callback) : callback(path.join(dir, f));
});
};
```
[Source of function](https://medium.com/@allenhwkim/nodejs-walk-directory-f30a2d8f038f) |
19,167,297 | I want to delete any files older than an hour. This is for automatically cleaning up a tmp uploads directory.
Here is my code:
```
fs.readdir( dirPath, function( err, files ) {
if ( err ) return console.log( err );
files.forEach(function( file ) {
var filePath = dirPath + file;
fs.stat( filePath, function( err, stat ) {
if ( err ) return console.log( err );
var livesUntil = new Date();
livesUntil.setHours(livesUntil.getHours() - 1);
if ( stat.ctime < livesUntil ) {
fs.unlink( filePath, function( err ) {
if ( err ) return console.log( err );
});
}
});
});
});
```
However this just deletes everything in the directory, regardless of whether or not it was uploaded over an hour ago.
Am I misunderstanding how to check the age of the file in Node? | 2013/10/03 | [
"https://Stackoverflow.com/questions/19167297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031947/"
] | Simple recursive solution only del all files !dirs run every 5 hours del older files that 1 day
```
const fs = require('fs');
const path = require('path');
setInterval(function() {
walkDir('./tmpimages/', function(filePath) {
fs.stat(filePath, function(err, stat) {
var now = new Date().getTime();
var endTime = new Date(stat.mtime).getTime() + 86400000; // 1days in miliseconds
if (err) { return console.error(err); }
if (now > endTime) {
//console.log('DEL:', filePath);
return fs.unlink(filePath, function(err) {
if (err) return console.error(err);
});
}
})
});
}, 18000000); // every 5 hours
function walkDir(dir, callback) {
fs.readdirSync(dir).forEach( f => {
let dirPath = path.join(dir, f);
let isDirectory = fs.statSync(dirPath).isDirectory();
isDirectory ?
walkDir(dirPath, callback) : callback(path.join(dir, f));
});
};
```
[Source of function](https://medium.com/@allenhwkim/nodejs-walk-directory-f30a2d8f038f) | ```
const path = require('path');
const fs = require('fs');
var uploadsDir = __dirname + '/Test';
let modifiedFiles = [];
var noOfFile = 2;
var files = fs.readdirSync(uploadsDir);
files.forEach((file, index) => {
var stat = fs.statSync(path.join(uploadsDir, file));
modifiedFiles.push({ cTime: stat.ctime.valueOf(), Name: file, Index: index });
console.log(stat);
});
var data = modifiedFiles.sort((a, b) => b.cTime - a.cTime);
var MaxCTime = data[noOfFile - 1].cTime;
data.forEach((v) => {
if (MaxCTime > v.cTime) {
fs.unlink(path.join(uploadsDir, v.Name));
}
});
console.log('older files deleted except last 2 modified');
``` |
19,167,297 | I want to delete any files older than an hour. This is for automatically cleaning up a tmp uploads directory.
Here is my code:
```
fs.readdir( dirPath, function( err, files ) {
if ( err ) return console.log( err );
files.forEach(function( file ) {
var filePath = dirPath + file;
fs.stat( filePath, function( err, stat ) {
if ( err ) return console.log( err );
var livesUntil = new Date();
livesUntil.setHours(livesUntil.getHours() - 1);
if ( stat.ctime < livesUntil ) {
fs.unlink( filePath, function( err ) {
if ( err ) return console.log( err );
});
}
});
});
});
```
However this just deletes everything in the directory, regardless of whether or not it was uploaded over an hour ago.
Am I misunderstanding how to check the age of the file in Node? | 2013/10/03 | [
"https://Stackoverflow.com/questions/19167297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031947/"
] | I've used [find-remove](https://www.npmjs.com/package/find-remove#delete-all-jpg-files-older-than-one-hour) for a similar usecase.
According to the documentation and what you are trying to do, the code will be:
```
var findRemoveSync = require('find-remove');
findRemoveSync(__dirname + '/uploads', {age: {seconds: 3600}});
```
I'm actually running that every 6 minutes and deleting files older than 1 hour by doing:
```
setInterval(findRemoveSync.bind(this,__dirname + '/uploads', {age: {seconds: 3600}}), 360000)
```
See [this](https://github.com/watson-developer-cloud/document-conversion-nodejs/blob/master/app.js) example on how I'm using find-remove to cleanup the `/uploads` folder. | ```
const path = require('path');
const fs = require('fs');
var uploadsDir = __dirname + '/Test';
let modifiedFiles = [];
var noOfFile = 2;
var files = fs.readdirSync(uploadsDir);
files.forEach((file, index) => {
var stat = fs.statSync(path.join(uploadsDir, file));
modifiedFiles.push({ cTime: stat.ctime.valueOf(), Name: file, Index: index });
console.log(stat);
});
var data = modifiedFiles.sort((a, b) => b.cTime - a.cTime);
var MaxCTime = data[noOfFile - 1].cTime;
data.forEach((v) => {
if (MaxCTime > v.cTime) {
fs.unlink(path.join(uploadsDir, v.Name));
}
});
console.log('older files deleted except last 2 modified');
``` |
19,167,297 | I want to delete any files older than an hour. This is for automatically cleaning up a tmp uploads directory.
Here is my code:
```
fs.readdir( dirPath, function( err, files ) {
if ( err ) return console.log( err );
files.forEach(function( file ) {
var filePath = dirPath + file;
fs.stat( filePath, function( err, stat ) {
if ( err ) return console.log( err );
var livesUntil = new Date();
livesUntil.setHours(livesUntil.getHours() - 1);
if ( stat.ctime < livesUntil ) {
fs.unlink( filePath, function( err ) {
if ( err ) return console.log( err );
});
}
});
});
});
```
However this just deletes everything in the directory, regardless of whether or not it was uploaded over an hour ago.
Am I misunderstanding how to check the age of the file in Node? | 2013/10/03 | [
"https://Stackoverflow.com/questions/19167297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031947/"
] | I am using [rimraf](https://github.com/isaacs/rimraf) to recursively delete any file/folder that is older than one hour.
According to the [docs](http://nodejs.org/api/fs.html#fs_class_fs_stats), you should use [getTime()](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime) on the ctime [Date](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) object instance in order to compare.
```
var uploadsDir = __dirname + '/uploads';
fs.readdir(uploadsDir, function(err, files) {
files.forEach(function(file, index) {
fs.stat(path.join(uploadsDir, file), function(err, stat) {
var endTime, now;
if (err) {
return console.error(err);
}
now = new Date().getTime();
endTime = new Date(stat.ctime).getTime() + 3600000;
if (now > endTime) {
return rimraf(path.join(uploadsDir, file), function(err) {
if (err) {
return console.error(err);
}
console.log('successfully deleted');
});
}
});
});
});
``` | ```
const path = require('path');
const fs = require('fs');
var uploadsDir = __dirname + '/Test';
let modifiedFiles = [];
var noOfFile = 2;
var files = fs.readdirSync(uploadsDir);
files.forEach((file, index) => {
var stat = fs.statSync(path.join(uploadsDir, file));
modifiedFiles.push({ cTime: stat.ctime.valueOf(), Name: file, Index: index });
console.log(stat);
});
var data = modifiedFiles.sort((a, b) => b.cTime - a.cTime);
var MaxCTime = data[noOfFile - 1].cTime;
data.forEach((v) => {
if (MaxCTime > v.cTime) {
fs.unlink(path.join(uploadsDir, v.Name));
}
});
console.log('older files deleted except last 2 modified');
``` |
19,167,297 | I want to delete any files older than an hour. This is for automatically cleaning up a tmp uploads directory.
Here is my code:
```
fs.readdir( dirPath, function( err, files ) {
if ( err ) return console.log( err );
files.forEach(function( file ) {
var filePath = dirPath + file;
fs.stat( filePath, function( err, stat ) {
if ( err ) return console.log( err );
var livesUntil = new Date();
livesUntil.setHours(livesUntil.getHours() - 1);
if ( stat.ctime < livesUntil ) {
fs.unlink( filePath, function( err ) {
if ( err ) return console.log( err );
});
}
});
});
});
```
However this just deletes everything in the directory, regardless of whether or not it was uploaded over an hour ago.
Am I misunderstanding how to check the age of the file in Node? | 2013/10/03 | [
"https://Stackoverflow.com/questions/19167297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031947/"
] | Simple recursive solution only del all files !dirs run every 5 hours del older files that 1 day
```
const fs = require('fs');
const path = require('path');
setInterval(function() {
walkDir('./tmpimages/', function(filePath) {
fs.stat(filePath, function(err, stat) {
var now = new Date().getTime();
var endTime = new Date(stat.mtime).getTime() + 86400000; // 1days in miliseconds
if (err) { return console.error(err); }
if (now > endTime) {
//console.log('DEL:', filePath);
return fs.unlink(filePath, function(err) {
if (err) return console.error(err);
});
}
})
});
}, 18000000); // every 5 hours
function walkDir(dir, callback) {
fs.readdirSync(dir).forEach( f => {
let dirPath = path.join(dir, f);
let isDirectory = fs.statSync(dirPath).isDirectory();
isDirectory ?
walkDir(dirPath, callback) : callback(path.join(dir, f));
});
};
```
[Source of function](https://medium.com/@allenhwkim/nodejs-walk-directory-f30a2d8f038f) | It looks like you're comparing whatever "stat.ctime" is to the entire Date object.
```
if ( stat.ctime < livesUntil ) {
```
Shouldn't it read:
```
if ( stat.ctime < livesUntil.getHours() ) {
``` |
19,167,297 | I want to delete any files older than an hour. This is for automatically cleaning up a tmp uploads directory.
Here is my code:
```
fs.readdir( dirPath, function( err, files ) {
if ( err ) return console.log( err );
files.forEach(function( file ) {
var filePath = dirPath + file;
fs.stat( filePath, function( err, stat ) {
if ( err ) return console.log( err );
var livesUntil = new Date();
livesUntil.setHours(livesUntil.getHours() - 1);
if ( stat.ctime < livesUntil ) {
fs.unlink( filePath, function( err ) {
if ( err ) return console.log( err );
});
}
});
});
});
```
However this just deletes everything in the directory, regardless of whether or not it was uploaded over an hour ago.
Am I misunderstanding how to check the age of the file in Node? | 2013/10/03 | [
"https://Stackoverflow.com/questions/19167297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031947/"
] | It looks like you're comparing whatever "stat.ctime" is to the entire Date object.
```
if ( stat.ctime < livesUntil ) {
```
Shouldn't it read:
```
if ( stat.ctime < livesUntil.getHours() ) {
``` | Here's a plain Node script (for instance name it `cleanlogs.js`), tested on `v18.7.0` using the fs promises api (native module). You really dont need any fancy npm modules:
```js
import * as fs from 'node:fs/promises';
import path from 'path';
/**
* Remove all files in a directory older than the given number of seconds.
* @param {String} directory The directory to look in.
* @param {String[]} extensions The file extensions to match.
* @param {Number} seconds The minimum number of seconds since the creation time of the file.
*/
(async (directory, extensions, seconds) => {
const currentTime = Math.floor(new Date().getTime() / 1000);
const files = Array.from(await fs.readdir(directory)).filter((file) => {
return extensions.indexOf(file.split('.').at(-1)) !== -1;
});
for (const file of files) {
const filePath = path.join(directory, file);
const stats = await fs.stat(filePath);
const birthTime = Math.floor(stats.birthtimeMs / 1000);
if (currentTime - birthTime > seconds) {
fs.rm(filePath);
}
}
})('./logs', ['log'], 60 * 60 * 12);
```
The example removes files in the `./logs` directory for any file with the `log` extension (e.g. `error.log`), older than 12 hours (`60 * 60 * 12` seconds). |
19,167,297 | I want to delete any files older than an hour. This is for automatically cleaning up a tmp uploads directory.
Here is my code:
```
fs.readdir( dirPath, function( err, files ) {
if ( err ) return console.log( err );
files.forEach(function( file ) {
var filePath = dirPath + file;
fs.stat( filePath, function( err, stat ) {
if ( err ) return console.log( err );
var livesUntil = new Date();
livesUntil.setHours(livesUntil.getHours() - 1);
if ( stat.ctime < livesUntil ) {
fs.unlink( filePath, function( err ) {
if ( err ) return console.log( err );
});
}
});
});
});
```
However this just deletes everything in the directory, regardless of whether or not it was uploaded over an hour ago.
Am I misunderstanding how to check the age of the file in Node? | 2013/10/03 | [
"https://Stackoverflow.com/questions/19167297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031947/"
] | I am using [rimraf](https://github.com/isaacs/rimraf) to recursively delete any file/folder that is older than one hour.
According to the [docs](http://nodejs.org/api/fs.html#fs_class_fs_stats), you should use [getTime()](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime) on the ctime [Date](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) object instance in order to compare.
```
var uploadsDir = __dirname + '/uploads';
fs.readdir(uploadsDir, function(err, files) {
files.forEach(function(file, index) {
fs.stat(path.join(uploadsDir, file), function(err, stat) {
var endTime, now;
if (err) {
return console.error(err);
}
now = new Date().getTime();
endTime = new Date(stat.ctime).getTime() + 3600000;
if (now > endTime) {
return rimraf(path.join(uploadsDir, file), function(err) {
if (err) {
return console.error(err);
}
console.log('successfully deleted');
});
}
});
});
});
``` | Here's a plain Node script (for instance name it `cleanlogs.js`), tested on `v18.7.0` using the fs promises api (native module). You really dont need any fancy npm modules:
```js
import * as fs from 'node:fs/promises';
import path from 'path';
/**
* Remove all files in a directory older than the given number of seconds.
* @param {String} directory The directory to look in.
* @param {String[]} extensions The file extensions to match.
* @param {Number} seconds The minimum number of seconds since the creation time of the file.
*/
(async (directory, extensions, seconds) => {
const currentTime = Math.floor(new Date().getTime() / 1000);
const files = Array.from(await fs.readdir(directory)).filter((file) => {
return extensions.indexOf(file.split('.').at(-1)) !== -1;
});
for (const file of files) {
const filePath = path.join(directory, file);
const stats = await fs.stat(filePath);
const birthTime = Math.floor(stats.birthtimeMs / 1000);
if (currentTime - birthTime > seconds) {
fs.rm(filePath);
}
}
})('./logs', ['log'], 60 * 60 * 12);
```
The example removes files in the `./logs` directory for any file with the `log` extension (e.g. `error.log`), older than 12 hours (`60 * 60 * 12` seconds). |
173,216 | I am using Gaussian Processes (GP) for regression (via the **gpml** package for MATLAB).
So far, I was optimizing the hyper-parameters by maximizing the log likelihood, but I would like to try a more Bayesian approach by (approximately) marginalizing over the hyper-parameters.
The hard part is that I would also like the training to remain relatively fast.
At the moment the optimization is *very* fast since the likelihood is Gaussian, so everything is analytical (likelihood and gradient). Therefore, maximizing the likelihood with pseudo-Newton methods requires only a handful of function evaluations.
I used MCMC a lot for other projects (e.g., slice sampling) and in my experience it tends to be either slow (i.e., getting *independent* samples might require a lot of time) and/or it requires a lot of careful tuning and checking.
As a middle-ground method (in-between optimization and proper marginalization), I was thinking of using a Laplace approximation combined with importance sampling. The algorithm would be:
* maximize the log likelihood just as I am doing now;
* compute the Hessian analytically at the maximum (as far as I know **gpml** doesn't do it, but it shouldn't be too hard to write it down);
* sample parameters from the multivariate normal distribution centered on the mode and with covariance matrix equal to the inverse Hessian;
* give weights to the samples via importance sampling.
On paper, this method should work pretty quickly (the hyper-parameter space is relatively small so I don't see major problems in computing/inverting the Hessian). Of course if the posterior is not Gaussian it's not as good as a proper marginalization, but the importance sampling bit should account for *some* deviations from normality.
Do you foresee any problem with this?
Alternatively, is there a sampling method which is (almost) as fast as optimization (and with no tuning required)? | 2015/09/19 | [
"https://stats.stackexchange.com/questions/173216",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/80479/"
] | The best reference I could find online so far, and a very fitting one, is Ville Pietiläinen's MSc thesis:
[Approximations for Integration Over the Hyperparameters in Gaussian Processes](http://lib.tkk.fi/Dipl/2010/urn100140.pdf) (2010).
Pietiläinen compares a point estimate approach (so-called MAP-II, since the latent variables are marginalized analytically given a Gaussian likelihood) to three marginalization methods:
1. Grid search (with a "smart" grid)
2. Central composite design (CCD)
3. Quasi-random importance sampling with Student-$t$ proposal distribution
Interestingly, for the case studies considered in the thesis, marginalization of the hyperparameters seems to provide some benefits with respect to optimization only for small datasets (e.g., no more than 50-100 training points). More in general, as Pietiläinen argues, the advantage of marginalization should emerge for test points in regions in which the input density is low (hence prediction uncertainty is high).
The three different marginalization methods perform somewhat similarly, although the comparison in the thesis is not exhaustive. CCD is appealing since it requires many less function evaluations than the other methods.
Another interesting reference is Philip Boyle's PhD thesis:
[Gaussian Processes for Regression and Optimisation](http://researcharchive.vuw.ac.nz/handle/10063/421) (2007).
In particular, chapter 8 is focussed on marginalization over hyperparameters.
In conclusion, I will eventually try and implement the CCD method, although at this point is not a priority as I am not expecting a major gain over optimization. I can probably better spend my time by playing with other factors that have a larger impact on the quality of the prediction (e.g., the choice of covariance function). | You might be interested in the gpml\_extensions repository here:
<https://github.com/rmgarnett/gpml_extensions/>
There is code for computing the Hessian of the log likelihood wrt $\theta$ for both exact inference and the Laplace approximation for approximate GP inference. There is also convenience code for using these to find the Laplace approximation to the hyperparameter posterior $p(\theta \mid \mathbf{X}, \mathbf{y})$ (theta\_posterior\_laplace.m).
Finally, [this paper](http://auai.org/uai2014/proceedings/individuals/152.pdf) from UAI 2014 suggests a fast analytical approximation (called the MGP) to the posterior predictive distribution
$p(f^\ast \mid \mathbf{x}^\ast, \mathbf{X}, \mathbf{y}) = \int p(f^\ast \mid \mathbf{x}^\ast, \mathbf{X}, \mathbf{y}, \theta) p(\theta \mid \mathbf{X}, \mathbf{y}) \, \mathrm{d}\theta$,
under an arbitrary Gaussian approximation to the $\theta$ posterior:
$p(\theta \mid \mathbf{X}, \mathbf{y}) \approx \mathcal{N}(\theta; \hat{\theta}, \mathbf{\Sigma})$.
The Laplace approximation would be one way to derive such an approximation.
There is an implementation of the MGP built atop gpml/gpml\_extensions available from the same user, but I don't have the reputation to post that link. |
28,483,223 | I've got following code for extracting lotto numbers from the web:
```
from BeautifulSoup import BeautifulSoup
from selenium import webdriver
lottonumbers=[]
url="https://www.lotto.de/de/ergebnisse/lotto-6aus49/archiv.html"
driver = webdriver.Firefox()
driver.get(url)
soup = BeautifulSoup(driver.page_source)
for ul in soup.findAll("div", {"class": "winning_numbers boxRow clearfix"}):
n = ','.join(''.join(_ for _ in li if _.isdigit()) for li in ul.text.split())
if n:
print format(n)
```
Returns:`625262728475`
Should be:`6,25,26,27,28,47,5`
The commas are missing. Preferable each number should be written into the list `lottonumbers`.
Can anyone help out? | 2015/02/12 | [
"https://Stackoverflow.com/questions/28483223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2557981/"
] | If someone finds this post and is still looking for an answer:
```
[FIRAuth auth].currentUser.uid;
``` | This ended up being my solution, seems to work fine.
```
A0SimpleKeychain *keychain = [[Application sharedInstance] store];
A0UserProfile *profile = [NSKeyedUnarchiver unarchiveObjectWithData: [keychain dataForKey:@"profile"]];
NSLog(@"user: %@",profile.userId);
``` |
17,333,151 | The following code is adopted from a working sample for angular 1.1.4, only using the new GreenSock api for ng-animate. toggle functionality works, as ng-show behaves as expected, however The AppAnimation functions 'list-in' and 'list-out' are not being called on ng-show.
```
<!DOCTYPE html>
<head>
<style>
.box { color: white; text-align: center; height: 100px; font-size: 86px; }
.on { background-color: green; }
.off { background-color: red; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.9.7/TweenMax.min.js"></script>
<script>
angular.module('AppAnimations', [])
.animation('list-out', ['$window',function($window) {
return {
start : function(element, done) {
console.log('list-out')
TweenMax.set(element, {position:'relative'});
var duration = 1;
//we can use onComplete:done with TweenMax, but lets use
//a delay value for testing purposes
TweenMax.to(element, 1, {opacity:0, width:0});
$window.setTimeout(done, duration * 1000);
}
}
}])
.animation('list-in', ['$window',function($window) {
return {
setup: function(element) {
TweenMax.set(element, {opacity:0, width:0});
},
start : function(element, done) {
console.log('list-in')
var duration = 1;
//we can use onComplete:done with TweenMax, but lets use
//a delay value for testing purposes
TweenMax.to(element, duration, {opacity:1, width:210});
$window.setTimeout(done, duration * 1000);
}
}
}])
angular.module('myApp', ['AppAnimations'])
.controller('MainController', ['$scope', function($scope) {
$scope.toggle = true;
}])
</script>
</head>
<body ng-app="myApp" ng-controller="MainController">
<button ng-click="toggle = !toggle">Toggle!</button>
<div class="box on" ng-show="toggle" ng-animate="{leave:'list-out', enter:'list-in'}">On</div>
<div class="box off" ng-hide="toggle" ng-animate="{leave:'list-out', enter:'list-in'}">Off</div>
</body>
</html>
``` | 2013/06/27 | [
"https://Stackoverflow.com/questions/17333151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2526282/"
] | ```
<div class="box on" ng-show="toggle" ng-animate="{show: 'list-in', hide: 'list-out'}">On</div>
<div class="box off" ng-hide="toggle" ng-animate="{show: 'list-in', hide: 'list-out'}">Off</div>
``` | So I finally solved it.. you are using `leave/enter` and should be using `show/hide`. I updated the names to be more PC correct.
```
<div class="box on" ng-show="toggle" ng-animate="{hide:'list-hide', show:'list-show'}">On</div>
<div class="box off" ng-hide="toggle" ng-animate="{hide:'list-hide', show:'list-show'}">Off</div>
```
---
```
angular.module('AppAnimations', [])
.animation('list-hide', ['$window',function($window) {
...
).animation('list-show', ['$window',function($window) {
```
Working fiddle: <http://jsfiddle.net/ncapito/CTfL8/> |
997,568 | Do to a battery problem when upgrading to Windows 10 I disabled the Appinfo service. The problem I am having now is that I cannot get it re-enabled. I get this message when I try and open regedit, task manager and services to try and fix the problem, "The service cannot be started, either because it is disabled or because it has no enabled devices associated with it." I also got this when I tried installing malwarebytes to run a scan (I don't think it is a virus because this happened as soon as I did the restart after editing appinfo).
My next step was to edit it through command prompt using this line `REG add "HKLM\SYSTEM\CurrentControlSet\services\Appinfo" /v Start /t REG_DWORD /d 3 /f` to which I get, "ERROR: Access is denied".
At this point what I am asking is if anyone knows how to get permission to edit the registry through command prompt or a way to get something working again to edit it the normal way. | 2015/11/08 | [
"https://superuser.com/questions/997568",
"https://superuser.com",
"https://superuser.com/users/406509/"
] | Today I was reminded by a friend that I could probably just boot into safemode(sift+click the restart button on Win10) and re-enable it from there(by going into services and setting it from "disabled" to "manual"), which worked. Although Hysterics suggestion of using a live version of Linux to edit the windows registry would have worked as well. | The only thing i can suggest you to do is run regedit with administration permission or enable the Administration account by using the command line by typing
```
net user Administrator /active: yes
```
But this should get the same permission as when you right click and select run as administrator.
If that isn’t working then my alternative is to boot into a live Linux and edit the windows registry from there.
there was a way to do that i believe
downvoter, **SPEAK** dont run and hide |
997,568 | Do to a battery problem when upgrading to Windows 10 I disabled the Appinfo service. The problem I am having now is that I cannot get it re-enabled. I get this message when I try and open regedit, task manager and services to try and fix the problem, "The service cannot be started, either because it is disabled or because it has no enabled devices associated with it." I also got this when I tried installing malwarebytes to run a scan (I don't think it is a virus because this happened as soon as I did the restart after editing appinfo).
My next step was to edit it through command prompt using this line `REG add "HKLM\SYSTEM\CurrentControlSet\services\Appinfo" /v Start /t REG_DWORD /d 3 /f` to which I get, "ERROR: Access is denied".
At this point what I am asking is if anyone knows how to get permission to edit the registry through command prompt or a way to get something working again to edit it the normal way. | 2015/11/08 | [
"https://superuser.com/questions/997568",
"https://superuser.com",
"https://superuser.com/users/406509/"
] | Today I was reminded by a friend that I could probably just boot into safemode(sift+click the restart button on Win10) and re-enable it from there(by going into services and setting it from "disabled" to "manual"), which worked. Although Hysterics suggestion of using a live version of Linux to edit the windows registry would have worked as well. | I had the same dilemma. I tried to disable as many services I can for a virtual machine, then ended up not able to run anything.
I fixed it by going to the safe mode using the "shift+restart" trick. ( You cannot do this in a RDP session.) The virtual machine goes to a PE environment. There I can run regedit, load the hive from "c:\windows\system32\config\system", edit the entry of "AppInfo", change the "start" from 4 to 3, then unload the hive. After that everything works again. |
23,583,388 | I know I can assign a temporary alias to a column. For example:
```
select foo, length(foo) as bar from my_table
```
And I know that I can use these aliases to get their values:
```
select foo, length(foo) as bar from my_table order by bar asc
```
But sometimes I want to make the results of my queries more readable, and when there is a space within a alias, I cannot use its value in the rest of the query:
```
select foo, length(foo) as "Foo's length" from my_table order by ? asc
```
Is there a way to define one alias for the query and one alias, that will be seen in the results? | 2014/05/10 | [
"https://Stackoverflow.com/questions/23583388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2668681/"
] | It happened the same to me and made me lose some hours. So, just for the record: when the execution stops, Excel processes every pending event in the spreadsheet, which can easely be blocked if you are updating a lot of cells. Adding a "DoEvents" command in key portions of the code solved the problem. It unblocks the spreadsheet and makes everything work "dramatically faster".
I hope this will save time to someone else... | I've seen Excel behave oddly many times so I believe you. Most of the time I do not stop to diagnose but instead chose to code around or quite simply take a different strategy.
However, if I look at your code then perhaps we might be able to tighten it further.
On the line
`.Cells(r, c) = ""`
you are actually allocating a string, even though the string is empty. String allocation does take time. Perhaps you could use
`.Cells(r, c).Clear`
or
`.Cells(r, c) = Empty`
both of these have same impact as your line, i.e. to clear a cell. Will you try these and then see if you still have oddness?
Also you might want to consider clearing contiguous ranges in one statement. So
`Range("B2:D4").Clear`
will clear nine cells in one go, imagine if you could clear hundreds of cells in one go. I realise from your code that have cells that you do not want cleared which you are marking/protecting with the Locked property, but nevertheless I reckon you can write some more complex code to identify blocks of cells that can be cleared in one go.
And finally, it looks like you are constantly recycling your sheets, i.e. populating them and then clearing them down. You might want to instead start with a fresh sheet, put in your labels, lock any cells as necessary and then populate with variable data; actually come to think of it you could use a template sheet, see this link.
<http://office.microsoft.com/en-gb/excel-help/about-excel-templates-HP005229286.aspx> |
265,559 | Our empire gains +1 influence each month, and need ~50 more.
It'll take ~50 months which is a lot of time.
So, what can one do to increase the monthly influence of an empire? | 2016/05/14 | [
"https://gaming.stackexchange.com/questions/265559",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/124887/"
] | Original post:
>
> 1. Tech. There are several social techs providing +1 influence/month. Additionally one of thsoe provides an empire unique building with +1 /
> month.
> 2. Declare rivalries. You can have three rivalries, together they'll grant 2-3 influence per month.
> 3. Complete the mandate. If you play a democratic empire (elections every few years), your elected ruler will declare a mandate (e.g.
> build 4 mining stations), which will grant a significant influence
> boost (lump sum of 80-200)
> 4. Reduce expenses. Empire Edicts and frontier outposts cost 1 influence per month. There is also tech to reduce this cost.
> 5. Some anomalies and events may also grant influence.
>
>
>
Update 2019:
Since release the ways of generating influence significantly changed. The [wiki](https://stellaris.paradoxwikis.com/Economy#Influence) provides a comprehensive list. Additionally, the factions in your empire play a major part in generating influence for you.
Addendum to the old points:
1. Techs are severly reduced. Autonomous agents (for gestalt conciousness) grants +1 influence and living state (for all other races) grants +1 max influence from factions. Interstellar campaigns and galactic campaigns reduce the influence cost of claims. That's all influence related tech left. The empire capital complex building also no longer exists.
2. Rivalries are still there, but only grant 0.5 influence per rivalry.
3. Mandates are still in the game, but now grant Unity, not influence.
4. Empire edicts no longer cost influence per month, but a lump sum to activate for a 10 year period (baseline), outposts are now needed much more frequently than in the release version, they also cost a lump sum of influence based on the distance to your territory and have no influence upkeep.
5. remains unchanged | I have found an additional way:
The building "Empire Capital-Complex" that can only be built once provides +1 influence.
**But!** If you conquer a planet which already has one, it doesn't get destroyed, and you also get +1 influence from it.
So in short; conquer a planet with an "Empire Capital-Complex" on it.
I've found these to mostly occur on capital worlds. |
265,559 | Our empire gains +1 influence each month, and need ~50 more.
It'll take ~50 months which is a lot of time.
So, what can one do to increase the monthly influence of an empire? | 2016/05/14 | [
"https://gaming.stackexchange.com/questions/265559",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/124887/"
] | Original post:
>
> 1. Tech. There are several social techs providing +1 influence/month. Additionally one of thsoe provides an empire unique building with +1 /
> month.
> 2. Declare rivalries. You can have three rivalries, together they'll grant 2-3 influence per month.
> 3. Complete the mandate. If you play a democratic empire (elections every few years), your elected ruler will declare a mandate (e.g.
> build 4 mining stations), which will grant a significant influence
> boost (lump sum of 80-200)
> 4. Reduce expenses. Empire Edicts and frontier outposts cost 1 influence per month. There is also tech to reduce this cost.
> 5. Some anomalies and events may also grant influence.
>
>
>
Update 2019:
Since release the ways of generating influence significantly changed. The [wiki](https://stellaris.paradoxwikis.com/Economy#Influence) provides a comprehensive list. Additionally, the factions in your empire play a major part in generating influence for you.
Addendum to the old points:
1. Techs are severly reduced. Autonomous agents (for gestalt conciousness) grants +1 influence and living state (for all other races) grants +1 max influence from factions. Interstellar campaigns and galactic campaigns reduce the influence cost of claims. That's all influence related tech left. The empire capital complex building also no longer exists.
2. Rivalries are still there, but only grant 0.5 influence per rivalry.
3. Mandates are still in the game, but now grant Unity, not influence.
4. Empire edicts no longer cost influence per month, but a lump sum to activate for a 10 year period (baseline), outposts are now needed much more frequently than in the release version, they also cost a lump sum of influence based on the distance to your territory and have no influence upkeep.
5. remains unchanged | One thing no one else has mentioned is at least in the updated versions you can gain influence by getting factions over 60% happiness |
265,559 | Our empire gains +1 influence each month, and need ~50 more.
It'll take ~50 months which is a lot of time.
So, what can one do to increase the monthly influence of an empire? | 2016/05/14 | [
"https://gaming.stackexchange.com/questions/265559",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/124887/"
] | Original post:
>
> 1. Tech. There are several social techs providing +1 influence/month. Additionally one of thsoe provides an empire unique building with +1 /
> month.
> 2. Declare rivalries. You can have three rivalries, together they'll grant 2-3 influence per month.
> 3. Complete the mandate. If you play a democratic empire (elections every few years), your elected ruler will declare a mandate (e.g.
> build 4 mining stations), which will grant a significant influence
> boost (lump sum of 80-200)
> 4. Reduce expenses. Empire Edicts and frontier outposts cost 1 influence per month. There is also tech to reduce this cost.
> 5. Some anomalies and events may also grant influence.
>
>
>
Update 2019:
Since release the ways of generating influence significantly changed. The [wiki](https://stellaris.paradoxwikis.com/Economy#Influence) provides a comprehensive list. Additionally, the factions in your empire play a major part in generating influence for you.
Addendum to the old points:
1. Techs are severly reduced. Autonomous agents (for gestalt conciousness) grants +1 influence and living state (for all other races) grants +1 max influence from factions. Interstellar campaigns and galactic campaigns reduce the influence cost of claims. That's all influence related tech left. The empire capital complex building also no longer exists.
2. Rivalries are still there, but only grant 0.5 influence per rivalry.
3. Mandates are still in the game, but now grant Unity, not influence.
4. Empire edicts no longer cost influence per month, but a lump sum to activate for a 10 year period (baseline), outposts are now needed much more frequently than in the release version, they also cost a lump sum of influence based on the distance to your territory and have no influence upkeep.
5. remains unchanged | If you're running low on influence try removing border stations (or however they're called in english) the ones you use to expand your empire without colonization. |
265,559 | Our empire gains +1 influence each month, and need ~50 more.
It'll take ~50 months which is a lot of time.
So, what can one do to increase the monthly influence of an empire? | 2016/05/14 | [
"https://gaming.stackexchange.com/questions/265559",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/124887/"
] | One thing no one else has mentioned is at least in the updated versions you can gain influence by getting factions over 60% happiness | I have found an additional way:
The building "Empire Capital-Complex" that can only be built once provides +1 influence.
**But!** If you conquer a planet which already has one, it doesn't get destroyed, and you also get +1 influence from it.
So in short; conquer a planet with an "Empire Capital-Complex" on it.
I've found these to mostly occur on capital worlds. |
265,559 | Our empire gains +1 influence each month, and need ~50 more.
It'll take ~50 months which is a lot of time.
So, what can one do to increase the monthly influence of an empire? | 2016/05/14 | [
"https://gaming.stackexchange.com/questions/265559",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/124887/"
] | I have found an additional way:
The building "Empire Capital-Complex" that can only be built once provides +1 influence.
**But!** If you conquer a planet which already has one, it doesn't get destroyed, and you also get +1 influence from it.
So in short; conquer a planet with an "Empire Capital-Complex" on it.
I've found these to mostly occur on capital worlds. | If you're running low on influence try removing border stations (or however they're called in english) the ones you use to expand your empire without colonization. |
265,559 | Our empire gains +1 influence each month, and need ~50 more.
It'll take ~50 months which is a lot of time.
So, what can one do to increase the monthly influence of an empire? | 2016/05/14 | [
"https://gaming.stackexchange.com/questions/265559",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/124887/"
] | One thing no one else has mentioned is at least in the updated versions you can gain influence by getting factions over 60% happiness | If you're running low on influence try removing border stations (or however they're called in english) the ones you use to expand your empire without colonization. |
230,845 | I'm trying to install the faience theme in ubuntu 12.10 with unity. I installed it from the ppa, then tried to use Unsettings to apply it.
I can apply all of the themes except for the window themes. The GTK and icon themes work fine.
Anybody have this problem? | 2012/12/20 | [
"https://askubuntu.com/questions/230845",
"https://askubuntu.com",
"https://askubuntu.com/users/91176/"
] | A comment on the [deviantART theme page](http://tiheum.deviantart.com/art/GTK3-Gnome-Shell-Faience-255097456?) explains how to fix this. It appears to be caused by the file `metacity-1/metacity-theme-2.xml`. You can either remove it or rename it:
```
cd /usr/share/themes/Faience/metacity-1 # Or ~/.themes/Faience/metacity-1 if you installed it by hand
sudo mv metacity-theme-2.xml metacity-theme-2.xml-OLD
```
This will allow you to set the Faience window theme. | I am having the same issue.
It's been fine up until now - I expect something broke in the latest release.
I would report any issues here:
<http://tiheum.deviantart.com/art/GTK3-Gnome-Shell-Faience-255097456>
Update:
Just discovered. It works if you select 'Faience-Ocre' as your theme, rather than if you select 'Faience' it works properly. |
67,072,847 | I have an API on nodejs and a flutter application. I want to run my flutter application and have access into the API but I don't know the correct ip.
The nodejs runs on localhost:3000 with localhost:3000 also to my project, I don't have access.
Any idea how to solve and get access ?
Thank you very much! | 2021/04/13 | [
"https://Stackoverflow.com/questions/67072847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10986977/"
] | Use [`np.r_`](https://numpy.org/doc/stable/reference/generated/numpy.r_.html) for join slicers, python counts from `0`, so for third column need `2` and from `5th` column need `4:`:
```
df = df.iloc[:, np.r_[0, 2, 4:len(df.columns)]]
print (df)
a c e f g h
0 1 one 4 7 7 7
1 2 two 5 8 8 8
2 3 three 6 9 9 9
``` | You can also do this by flatten a list of list with [any methods](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists) you like.
```py
from pandas.core.common import flatten
df1 = df.iloc[:, list(flatten([[0, 2], range(4, len(df.columns))]))]
df2 = df.iloc[:, np.concatenate([[0, 2], range(4, len(df.columns))])]
``` |
10,544 | With the upcoming re-release of The Phantom Menace in 3D Lucas has again gone and changed his movies.
Is there such a thing as ‘public domain’ for movies?
If so when will Star Wars reach that point, and will the original un-changed version then be available so that we can all go back to the way some people think it should be? | 2012/02/06 | [
"https://scifi.stackexchange.com/questions/10544",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/4023/"
] | As per <http://copyright.cornell.edu/resources/publicdomain.cfm>:
```
Published Copyright term Ergo, public in Episodes
===========================================================================
1964-1977 95 years after pub date 1977 + 95 = 2072 IV
1978-3/1/1989 70 years after author dies ???? + 70 = >2082+ V, VI
1978-3/1/1989 95 years from publication 1980 + 95 = 2075 V, VI
if corporate or 120 years from creation,
authorship whichever expires first
```
Therefore, **Episode IV will be 2072**.
I am not sure if **Episodes V, VI** are "corporate authorship", if so, they would expire into public domain either in **2075 or 2078** (if "authored" by LucasFilm), or 70 years after Lucas dies, which means **100% sure after 2082.**
The rest of the years after 1989 fall under the same rules as the corporate authorship for pre-1989, therefore Episodes 1-3 will expire 2094, 2099 and 2102.
Please be aware that I'm using year of release as "publication", therefore that may be off by a year or two if the precise definition of publication for movies for the copyright purposes is different.
---
As a side note, copyright laws **have been changed before, with retroactive effects**, specifically with the goal of lengthening the expiration period for works about to expire (I'm looking at you, Disney).
So it's QUITE possible they will be changed again before 2075 to make these dates much further into the future. | It's very unlikely these works will ever be in the public domain for our lifetime.
For Episode IV, [published in 1977, the original copyright lasts until 2072](http://copyright.cornell.edu/resources/publicdomain.cfm) at the very earliest. Similarly for the other movies, copyright lasts at least [95 years from the date of publication](http://en.wikipedia.org/wiki/Copyright_law_of_the_United_States#Duration_of_copyright). This is the minimum term, and the history of copyright shows that it keeps getting [extended retroactively for longer and longer terms](http://en.wikipedia.org/wiki/Sonny_Bono_Copyright_Term_Extension_Act). |