问:
What does the following Array initialization syntax actually create?
What does the following actually create?

I ask because it cannot be enumerated with Array#foreach and it is represented (misleadingly?) in Chrome console as [undefined x 10].

```<code>const arr = new Array(10);
</code>```

答:
The Array object has three different possible constructor actions:

new Array()

new Array(<multiple arguments)

new Array(<one argument>) (placed as last because of its nature - see further)

The behavior of the constructor depends of the arguments provided to that constructor. All those three actions uses ArrayCreate during the constructor action. From the link:

The abstract operation ArrayCreate with argument length (a positive integer) and optional argument proto is used to specify the creation of new Array exotic objects.

This function accepts two arguments: len (length) and proto which is used to create an array object. (I won't go deeper here because it would be more complex). The len argument is more important in this situation. When we are looking to the constructor actions individually, you have

new Array()

Here, an object is constructed by ArrayCreate(0, proto), thus an empty array with .length = 0.

new Array(<multiple arguments>)

Here, an object is constructed by ArrayCreate(#of args, proto). If you provide 3 arguments, then you get an array with .length = 3. This array is then populated with the provided arguments. Do you give 5 arguments? You get .length = 5. So the .length property depends of the number of the arguments.

new Array(<one argument>)

This one is quite different. It has two cases. At init, an array object is created with ArrayCreate(0, proto) like if you're using new Array(). Still we have an argument here to use.

If the argument is a non-numeric value, then the effect is same as point 2. This argument is being added to the constructed object (like a .push() operation. So new Array('hello') or new Array('10') gives you an array object with .length = 1

Now, the thing is very different when you give a numeric argument new Array(10), which gives in Chrome [undefined x 10]. Why? Because when the argument is numeric (and valid), this function is being called: Set(O,P,V,Throw). This "magic" function sets the property P of object O with the value V. (The Throw is a flag to indicate " throw error or not? " question).

If the argument is a length, set(<constructed array>, 'length', <argument>, true) is being executed. So the .length property returns the argument value while there is nothing being preserved in the memory. End result: you have an object with a fake .length property... A side-effect of this is that using .push adds an element to the 10th index (if .length was 10). Now you have an array with 11 elements: 10 "empty" slots and an element that you've just pushed.

So what does the browsers do with an array with a "fake" .length property? They cannot iterate it correctly. So they provide a failsafe way: display "has 10 elements but are empty" like chrome does with [undefined x 10] or firefox: Array [ <10 empty slots>]

If you ask me why this is being standardized in the specs, then I would respond with "I don't know". It is one of the weirdest decision (among other ones that I have encountered) that is being standardized in ECMAScript.

Body:
What does the following actually create?

I ask because it cannot be enumerated with Array#foreach and it is represented (misleadingly?) in Chrome console as [undefined x 10].

const arr = new Array(10);


来源: stackexchange

问:
Multi module maven project not being deployed on OpenShift (S2I)
I'm working on a maven multi module application, which consists of two modules:

Common

Webapp
My project structure is as follow:

```<code>-(root)pom
    -Common
    -Webapp
</code>```

We're using openshift web console with S2I (source to image) deploy. The image that we choose is Jboss Eap. After providing git repository, Openshift starts to create required resources. It successfully compile and install our modules using maven, however it does not deploy it on standalone folder for Jboss. Looking at the build log, we can check all dependencies being retrieve and BUILD SUCCESS at end of log. But no artifact deployed on image jboss folder. We can confirm this either by looking at the log or using console to check pod files.

This project is on bitbucket

Root pom.xml

```<code>    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.test.parent</groupId>
        <artifactId>parent</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <packaging>pom</packaging>

        <name>:: Parent ::</name>
        <description>Parent POM for some app</description>

        <modules>
            <module>Common</module>
            <module>Webapp</module>
        </modules>

    </project>
</code>```

Common pom:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>

        <parent>
            <groupId>com.test.parent</groupId>
            <artifactId>parent</artifactId>
            <version>1.0.0-SNAPSHOT</version>
        </parent>

        <groupId>com.test.common</groupId>
        <artifactId>Common</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <packaging>jar</packaging>

        <name>Common module</name>
        <description>Module for common elements that exist between projects</description>

        <build>
            <finalName>${project.artifactId}</finalName>
            <plugins>
                <!-- Compiler plugin enforces Java 1.8 compatibility and activates annotation
                    processors -->
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.3</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>

        <dependencies>
            ...
        </dependencies>

    </project>
</code>```

And finally, the web pom:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>

        <parent>
            <groupId>com.test.parent</groupId>
            <artifactId>parent</artifactId>
            <version>1.0.0-SNAPSHOT</version>
        </parent>

        <groupId>com.test.external</groupId>
        <artifactId>Webapp</artifactId>
        <version>1.0-SNAPSHOT</version>
        <packaging>war</packaging>

        <name> Web</name>
        <description>web module</description>

        <properties>
            <!-- Explicitly declaring the source encoding eliminates the following
                message: -->
            <!-- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered
                resources, i.e. build is platform dependent! -->
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

            <!-- JBoss dependency versions -->

            <version.wildfly.maven.plugin>1.0.2.Final</version.wildfly.maven.plugin>

            <version.jboss.spec.javaee.7.0>1.0.3.Final</version.jboss.spec.javaee.7.0>

            <!-- other plug-in versions -->
            <version.war.plugin>2.1.1</version.war.plugin>

            <!-- maven-compiler-plugin -->
            <maven.compiler.target>1.8</maven.compiler.target>
            <maven.compiler.source>1.8</maven.compiler.source>
        </properties>

        <build>
            <!-- Set the name of the WAR, used as the context root when the app
                is deployed -->
            <finalName>${project.artifactId}</finalName>
            <plugins>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>${version.war.plugin}</version>
                    <configuration>
                        <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
                    </configuration>
                </plugin>
            </plugins>
        </build>

        <dependencies>
            ...
            <dependency>
                <groupId>com.test.common</groupId>
                <artifactId>Common</artifactId>
                <version>1.0.0-SNAPSHOT</version>
                <type>jar</type>
            </dependency>

        </dependencies>

    </project>
</code>```

Does anyone manage to achieve this?

答:
I end up using maven-antrun-plugin to copy war into jboss standalone folder.</p>

```<code>    <profile>
        <id>openshift</id>
            <properties>
                <axis2.repo.path>/opt/eap/custom_modules</axis2.repo.path>
                <ssl.cacerts.java.path>${java.home}/lib/security/cacerts</ssl.cacerts.java.path>
            </properties>
        <build>
            <resources>
                <resource>
                    <directory>/src/webapp/resources</directory>
                    <filtering>true</filtering>
                </resource>
            </resources>
            <plugins>
                <plugin>
                    <artifactId>maven-antrun-plugin</artifactId>
                    <executions>
                        <execution>
                            <phase>install</phase>
                            <goals>
                                <goal>run</goal>
                            </goals>
                            <configuration>
                                <tasks>
                                    <copy todir="${jboss.deploy.path}">
                                        <fileset dir="${compiled.war.location}"/>
                                    </copy>
                                    <echo>war copied to ${jboss.deploy.path}</echo>

                                </tasks>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm working on a maven multi module application, which consists of two modules:

Common

Webapp
My project structure is as follow:

-(root)pom
    -Common
    -Webapp

We're using openshift web console with S2I (source to image) deploy. The image that we choose is Jboss Eap. After providing git repository, Openshift starts to create required resources. It successfully compile and install our modules using maven, however it does not deploy it on standalone folder for Jboss. Looking at the build log, we can check all dependencies being retrieve and BUILD SUCCESS at end of log. But no artifact deployed on image jboss folder. We can confirm this either by looking at the log or using console to check pod files.

This project is on bitbucket

Root pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.test.parent</groupId>
        <artifactId>parent</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <packaging>pom</packaging>

        <name>:: Parent ::</name>
        <description>Parent POM for some app</description>

        <modules>
            <module>Common</module>
            <module>Webapp</module>
        </modules>

    </project>

Common pom:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>

        <parent>
            <groupId>com.test.parent</groupId>
            <artifactId>parent</artifactId>
            <version>1.0.0-SNAPSHOT</version>
        </parent>

        <groupId>com.test.common</groupId>
        <artifactId>Common</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <packaging>jar</packaging>

        <name>Common module</name>
        <description>Module for common elements that exist between projects</description>

        <build>
            <finalName>${project.artifactId}</finalName>
            <plugins>

                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.3</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>

        <dependencies>
            ...
        </dependencies>

    </project>

And finally, the web pom:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>

        <parent>
            <groupId>com.test.parent</groupId>
            <artifactId>parent</artifactId>
            <version>1.0.0-SNAPSHOT</version>
        </parent>

        <groupId>com.test.external</groupId>
        <artifactId>Webapp</artifactId>
        <version>1.0-SNAPSHOT</version>
        <packaging>war</packaging>

        <name> Web</name>
        <description>web module</description>

        <properties>

            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

            <version.wildfly.maven.plugin>1.0.2.Final</version.wildfly.maven.plugin>

            <version.jboss.spec.javaee.7.0>1.0.3.Final</version.jboss.spec.javaee.7.0>

            <version.war.plugin>2.1.1</version.war.plugin>

            <maven.compiler.target>1.8</maven.compiler.target>
            <maven.compiler.source>1.8</maven.compiler.source>
        </properties>

        <build>

            <finalName>${project.artifactId}</finalName>
            <plugins>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>${version.war.plugin}</version>
                    <configuration>
                        <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
                    </configuration>
                </plugin>
            </plugins>
        </build>

        <dependencies>
            ...
            <dependency>
                <groupId>com.test.common</groupId>
                <artifactId>Common</artifactId>
                <version>1.0.0-SNAPSHOT</version>
                <type>jar</type>
            </dependency>

        </dependencies>

    </project>

Does anyone manage to achieve this?

Body:
I end up using maven-antrun-plugin to copy war into jboss standalone folder.

    <profile>
        <id>openshift</id>
            <properties>
                <axis2.repo.path>/opt/eap/custom_modules</axis2.repo.path>
                <ssl.cacerts.java.path>${java.home}/lib/security/cacerts</ssl.cacerts.java.path>
            </properties>
        <build>
            <resources>
                <resource>
                    <directory>/src/webapp/resources</directory>
                    <filtering>true</filtering>
                </resource>
            </resources>
            <plugins>
                <plugin>
                    <artifactId>maven-antrun-plugin</artifactId>
                    <executions>
                        <execution>
                            <phase>install</phase>
                            <goals>
                                <goal>run</goal>
                            </goals>
                            <configuration>
                                <tasks>
                                    <copy todir="${jboss.deploy.path}">
                                        <fileset dir="${compiled.war.location}"/>
                                    </copy>
                                    <echo>war copied to ${jboss.deploy.path}</echo>

                                </tasks>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>


问:
Reverse a string without using reversed() or [::-1]?
I came across a strange Codecademy exercise that required a function that would take a string as input and return it in reverse order. The only problem was you could not use the reversed method or the common answer here on stackoverflow, [::-1].

Obviously in the real world of programming, one would most likely go with the extended slice method, or even using the reversed function but perhaps there is some case where this would not work?

I present a solution below in Q&A style, in case it is helpful for people in the future.

答:
You can simply use the pop as suggested.
Here are one liners fot that</p>

```<code>chaine = 'qwertyuiop'
''.join([chaine[-(x + 1)] for x in range(len(chaine))])
'poiuytrewq'
gg = list(chaine)
''.join([gg.pop() for _ in range(len(gg))])
'poiuytrewq'
</code>```

Body:
You can simply use the pop as suggested.
Here are one liners fot that

chaine = 'qwertyuiop'
''.join([chaine[-(x + 1)] for x in range(len(chaine))])
'poiuytrewq'
gg = list(chaine)
''.join([gg.pop() for _ in range(len(gg))])
'poiuytrewq'


问:
C: read in more than one file
Hey guys using POSIX API system calls read, write, open, etc. I can open, read, write to a file  and copy its contents to an output file. How would I go about copying more than one file to an output file using related system calls only?

I currently have:

```<code>filein = open(argv[1],O_RDONLY,0);
</code>```

to open one file.(which is argv1 but I'd like to know how to do argv2 and argv3 etc.)

I tried :

```<code>j=0;
filein = open(argv[j],O_RDONLY,0);
</code>```

but that prints out contents of argv0 into my outputfile.

I am stuck on the next stage to do more than one file. (I also have an EOF loop so after 1 file it exits-How would I make this continue for the next file).

Please could you help me with how to approach the next stage? Thanks.

答:
Background

argv[0] is the name of the program.

argv[1] is the 1st command line parameter.

argv[2] is the 2nd command line parameter.

etc.

So:

Start your loop at 1, instead of 0 (i.e., j=0 is incorrect).

Be sure to close the file immediately after reading it and before opening the next file.

Algorithm

Think about the algorithm before writing the code.

Set counter to the index of the first argument.

Open the file.

Assign a handle to the open file.

Read the file contents.

Write (if required) the file contents.

Close the file using the handle.

Increment the counter.

Loop until there are no more command line arguments.

Now you can write the code.

You might get bonus points if you include error handling. (What happens when the file is missing, is not readable, the file system is corrupt, or the machine has run out of memory or disk space?)

Concatenating Files

If you want to concatenate two file names to a third, you need to rethink the algorithm, and what you need. There is a difference between "read the first two files given on the command line and write them to the third file" and "append all the files given on the command line to the last file given."

Read Two, Write One

The algorithm:

Make sure that there are exactly three parameters.

Create a file handle variable for the third file (output).

Create a file handle variable for the first file (input).

Create a file handle variable for the second file (input).

Open the first file for reading.

Open the second file for reading.

Open the third file for writing.

Read the contents of the first file and write them to the third file.

Read the contents of the second file and write them to the third file.

Close the third file.

Close the second file.

Close the first file.

You will notice a lot of redundancy at this point.

Read N, Write One

This algorithm is a bit more challenging, but removes the redundancy.

Make sure there are at least two parameters.

Open the last file for writing.

Loop over every file name up to, but not including, the last file name given:

Open the input file for reading.

Write the contents of the file to the last file.

Close the input file.

Close the output file.

For this you will need to understand argc and its relationship with argv. In pseudo-code:

```<code>if number_of_arguments < 2 then
  print "This program concatenates files; two or more file names are required."
  exit
end

int outfile = open arguments[ number_of_arguments ] for writing
int j = 1

while j < number_of_arguments do
  int infile = open arguments[ j ] for reading
  string contents = read infile
  write contents to outfile
  close infile
  increment j
end

close outfile
</code>```

Tutorials

If you are having trouble with C syntax, search for tutorials. For example:

http://www.cprogramming.com/tutorial/c/lesson3.html

ContentLicense: CC BY-SA 2.5

Title: C: read in more than one file

Body:
Hey guys using POSIX API system calls read, write, open, etc. I can open, read, write to a file  and copy its contents to an output file. How would I go about copying more than one file to an output file using related system calls only?

I currently have:

filein = open(argv[1],O_RDONLY,0);

to open one file.(which is argv1 but I'd like to know how to do argv2 and argv3 etc.)

I tried :

j=0;
filein = open(argv[j],O_RDONLY,0);

but that prints out contents of argv0 into my outputfile.

I am stuck on the next stage to do more than one file. (I also have an EOF loop so after 1 file it exits-How would I make this continue for the next file).

Please could you help me with how to approach the next stage? Thanks.

Body:
Background

argv[0] is the name of the program.

argv[1] is the 1st command line parameter.

argv[2] is the 2nd command line parameter.

etc.

So:

Start your loop at 1, instead of 0 (i.e., j=0 is incorrect).

Be sure to close the file immediately after reading it and before opening the next file.

Algorithm

Think about the algorithm before writing the code.

Set counter to the index of the first argument.

Open the file.

Assign a handle to the open file.

Read the file contents.

Write (if required) the file contents.

Close the file using the handle.

Increment the counter.

Loop until there are no more command line arguments.

Now you can write the code.

You might get bonus points if you include error handling. (What happens when the file is missing, is not readable, the file system is corrupt, or the machine has run out of memory or disk space?)

Concatenating Files

If you want to concatenate two file names to a third, you need to rethink the algorithm, and what you need. There is a difference between "read the first two files given on the command line and write them to the third file" and "append all the files given on the command line to the last file given."

Read Two, Write One

The algorithm:

Make sure that there are exactly three parameters.

Create a file handle variable for the third file (output).

Create a file handle variable for the first file (input).

Create a file handle variable for the second file (input).

Open the first file for reading.

Open the second file for reading.

Open the third file for writing.

Read the contents of the first file and write them to the third file.

Read the contents of the second file and write them to the third file.

Close the third file.

Close the second file.

Close the first file.

You will notice a lot of redundancy at this point.

Read N, Write One

This algorithm is a bit more challenging, but removes the redundancy.

Make sure there are at least two parameters.

Open the last file for writing.

Loop over every file name up to, but not including, the last file name given:

Open the input file for reading.

Write the contents of the file to the last file.

Close the input file.

Close the output file.

For this you will need to understand argc and its relationship with argv. In pseudo-code:

if number_of_arguments < 2 then
  print "This program concatenates files; two or more file names are required."
  exit
end

int outfile = open arguments[ number_of_arguments ] for writing
int j = 1

while j < number_of_arguments do
  int infile = open arguments[ j ] for reading
  string contents = read infile
  write contents to outfile
  close infile
  increment j
end

close outfile

Tutorials

If you are having trouble with C syntax, search for tutorials. For example:

http://www.cprogramming.com/tutorial/c/lesson3.html


问:
Converting relative time from CSV file into absolute time
```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import Rbf, InterpolatedUnivariateSpline
data = np.genfromtxt('FTIR Data.csv',  skip_header=1, delimiter=',', usecols=(1,2,3), names=['Time','Peakat2188cm1', 'water']  )

x=data['Time']
y1=data['Peakat2188cm1']
y2=data['water']

fig=plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

ius=InterpolatedUnivariateSpline
xs = np.linspace(x.min(), x.max(), 100)
s1=ius(x,y1)
s2=ius(x,y2)
ys1 = s1(xs)
ys2 = s2(xs)

ax2.plot(xs,ys1)
ax2.plot(xs,ys2)
ax1.set_ylabel('Peak at 2188 cm-1')
ax2.set_ylabel('water')
ax1.set_xlabel('RT (mins)')
plt.title('RT Vs Conc')
</code>```

This is my code for reading data from a csv file which is an export data from my instrument. In excel file, i have manually converted the relative time into Time in minutes and got the right plot. But i want to convert the relative time directly in matplotlib when reading the relative time column in csv file.  I have tried from different examples but couldnt get through. I am very new to python so can anyone please help  with editing in my code. My actual data is in the following format. (this code is used to plot absolute time i.e. Time, which i already converted in excel before ploting in matplotlib)[enter image description here][1]

```<code>Relative Time,Peak at 2188 cm-1,water
00:00:51,0.572157,0.179023
00:02:51,0.520037,0.171217
00:04:51,0.551843,0.221285
00:06:50,0.566279,0.209182
00:09:26,0.022696,0.0161351
00:10:51,-0.00344509,0.0141303
00:12:51,0.555898,0.21082
00:14:51,0.519753,0.179563
00:16:51,0.503512,0.150133
00:18:51,0.498554,0.154512
00:20:51,0.00128343,-0.0129148
00:22:51,0.349077,0.0414234
00:24:50,0.360565,0.0522027
00:26:51,0.403705,0.0667703
</code>```

Plot

答:
At this moment, the Time column is still a string. You will have to convert this to minutes in some way

pandas.to_timedelta

```<code>import pandas as pd

column_names = ['Time','Peakat2188cm1', 'water']
df_orig = pd.read_csv(filename, sep=',')
df_orig.columns = column_names

time_in_minutes = pd.to_timedelta(df_orig['Time']).dt.total_seconds() / 60
</code>```

semi-manually

```<code>time_in_minutes = [sum(int(x) * 60**i for i, x in enumerate(reversed(t.split(':')), -1)) for t in data['Time']]
</code>```

explanation

This is the same as:

```<code>time_in_minutes = []

for t in data['Time']:
    minutes = 0
    # t = '00:00:51'
    h_m_s = t.split(':')
    # h_m_s = ['00', '00', '51']
    s_m_h = list(enumerate(reversed(h_m_s), -1))
    # s_m_h = [(-1, '51'), (0, '00'), (1, '00')]
    for i, x in s_m_h:
        # i = -1
        # x = '51'
        minutes += int(x) * 60 ** i
        # minutes = 0.85
    time_in_minutes.append(minutes)
</code>```

Body:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import Rbf, InterpolatedUnivariateSpline
data = np.genfromtxt('FTIR Data.csv',  skip_header=1, delimiter=',', usecols=(1,2,3), names=['Time','Peakat2188cm1', 'water']  )

x=data['Time']
y1=data['Peakat2188cm1']
y2=data['water']

fig=plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

ius=InterpolatedUnivariateSpline
xs = np.linspace(x.min(), x.max(), 100)
s1=ius(x,y1)
s2=ius(x,y2)
ys1 = s1(xs)
ys2 = s2(xs)

ax2.plot(xs,ys1)
ax2.plot(xs,ys2)
ax1.set_ylabel('Peak at 2188 cm-1')
ax2.set_ylabel('water')
ax1.set_xlabel('RT (mins)')
plt.title('RT Vs Conc')

This is my code for reading data from a csv file which is an export data from my instrument. In excel file, i have manually converted the relative time into Time in minutes and got the right plot. But i want to convert the relative time directly in matplotlib when reading the relative time column in csv file.  I have tried from different examples but couldnt get through. I am very new to python so can anyone please help  with editing in my code. My actual data is in the following format. (this code is used to plot absolute time i.e. Time, which i already converted in excel before ploting in matplotlib)[enter image description here][1]

Relative Time,Peak at 2188 cm-1,water
00:00:51,0.572157,0.179023
00:02:51,0.520037,0.171217
00:04:51,0.551843,0.221285
00:06:50,0.566279,0.209182
00:09:26,0.022696,0.0161351
00:10:51,-0.00344509,0.0141303
00:12:51,0.555898,0.21082
00:14:51,0.519753,0.179563
00:16:51,0.503512,0.150133
00:18:51,0.498554,0.154512
00:20:51,0.00128343,-0.0129148
00:22:51,0.349077,0.0414234
00:24:50,0.360565,0.0522027
00:26:51,0.403705,0.0667703

Plot

Body:
At this moment, the Time column is still a string. You will have to convert this to minutes in some way

pandas.to_timedelta

import pandas as pd

column_names = ['Time','Peakat2188cm1', 'water']
df_orig = pd.read_csv(filename, sep=',')
df_orig.columns = column_names

time_in_minutes = pd.to_timedelta(df_orig['Time']).dt.total_seconds() / 60

semi-manually

time_in_minutes = [sum(int(x) * 60**i for i, x in enumerate(reversed(t.split(':')), -1)) for t in data['Time']]

explanation

This is the same as:

time_in_minutes = []

for t in data['Time']:
    minutes = 0
    # t = '00:00:51'
    h_m_s = t.split(':')
    # h_m_s = ['00', '00', '51']
    s_m_h = list(enumerate(reversed(h_m_s), -1))
    # s_m_h = [(-1, '51'), (0, '00'), (1, '00')]
    for i, x in s_m_h:
        # i = -1
        # x = '51'
        minutes += int(x) * 60 ** i
        # minutes = 0.85
    time_in_minutes.append(minutes)


问:
How to create a trigger that wont hold the entire transaction till it complete?
There is a procedure which have insert operation in middle for a table. The table contain a trigger and because of that the entire transaction getting hold. Is there are anyway to make trigger run on separate session and after insert operation procedure runs without waiting for the trigger to complete.

Both procedure and the trigger are

```<code>PRAGMA AUTONOMOUS_TRANSACTION
</code>```

答: If Trigger is based on insert operation, it will hold the current session, until that trigger action is completed. This is required to maintain integrity at database side. It may be possible to design a procedure & trigger in a better way if the requirements are known.</p>

Body:
There is a procedure which have insert operation in middle for a table. The table contain a trigger and because of that the entire transaction getting hold. Is there are anyway to make trigger run on separate session and after insert operation procedure runs without waiting for the trigger to complete.

Both procedure and the trigger are

PRAGMA AUTONOMOUS_TRANSACTION


问:
Can the compiler exploit empty base optimisation if the class contains a member of the base class?
Consider

```<code>struct base {};
struct child : base {};
</code>```

It's well-known that sizeof(child) can be 1 by application of the empty base optimisation.

Now however, consider

```<code>struct base {};
struct child : base {base b;};
</code>```

Can the compiler apply the empty base optimisation now, or must sizeof(child) be at least 2?

Reference: http://en.cppreference.com/w/cpp/language/ebo

答:
No, it cannot. From the same reference:

Empty base optimization is prohibited if one of the empty base classes
  is also the type or the base of the type of the first non-static data
  member

Thus sizeof(child) >= 2.

Body:
Consider

struct base {};
struct child : base {};

It's well-known that sizeof(child) can be 1 by application of the empty base optimisation.

Now however, consider

struct base {};
struct child : base {base b;};

Can the compiler apply the empty base optimisation now, or must sizeof(child) be at least 2?

Reference: http://en.cppreference.com/w/cpp/language/ebo


问:
Progressive Web App: How to detect and handle when connection is up again
With a PWA, we can handle when the device connection is down with offline mode. But how do we detect a fixed network connection and automatically reload/re-activate the application?</p>

答: Be careful with the online event, that only tells the device if connected. It can be connected to a WiFi hotspot without actual Internet connectivity (because of credentials for example).

ContentLicense: CC BY-SA 4.0


问:
Understanding GroupBY
I have a table in SQL Server where personal entries and exits are recorded.
There are multiple hours of entry or exit on the same day. What I need is to recover the first entry and the last exit of the day.

```<code>Date       hour   Clock
------------------------
01/01/2017 09:00  1
01/01/2017 11:30  2
01/01/2017 17:00  2
02/01/2017  7:59  1
02/01/2017 16:00  1
</code>```

I have this SQL query that works correctly.

```<code>SELECT
    d.Date,
    MIN(d.hour) as Entry,
    MAX(dt.hour) as Exit
FROM
    #temp1 AS d
LEFT JOIN
    #temp1 AS dt ON d.Date = dt.Date
GROUP BY
    d.Date
ORDER BY
    Date DESC
</code>```

BUT if I add 2 more columns to the query

```<code>SELECT
    d.Date,
    d.clock as ClockEntry,       -- Aggregated column to display
    MIN(d.hour) as Entry,
    dt.clock as ClockExit,       -- Aggregated column to display
    MAX(dt.hour) as Exit
FROM
    #temp1 AS d
LEFT JOIN
    #temp1 AS dt ON d.Date = dt.Date
GROUP BY
    d.Date
ORDER BY
    Date DESC
</code>```

I get this error:

Column '# temp1.clock' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I just need to group by the field "date", I do not want to add more conditions to the GROUP BY.. How could I solve it?

I want this result

```<code>DATE        ClockEntry     Entry    ClockExit    Exit
-------------------------------------------------------
01/01/2017     1           09:00        2        17:00
02/01/2017     1            7:59        1        16:00
</code>```

答:
So there is an easy way to do this - use 2 ranking functions:

Partitioned by date, Ordered by the hour ascending

Partitioned by date, Ordered by the hour descending

At that point the rows can be joined where they both have a value of 1, and the dates match.

I tend to use a CTE for this:

```<code>with temp2 (MinId, MaxId, Date, Hour, Clock)
AS
(
    select ROW_NUMBER() Over (partition by date order by hour),
     ROW_NUMBER() Over (partition by date order by hour desc),
    *
    from temp1
)
select distinct
       d1.Date,
       d1.Clock,
       d1.Hour,
       d2.Clock,
       d2.Hour
FROM temp2 d1
LEFT JOIN temp2 d2
    ON d1.Date = d2.Date  -- dates match
    AND d1.MinId=d2.MaxId -- minId=earliest record MaxId=latest record
WHERE d1.MinId=1
</code>```

Title: Understanding GroupBY

Body:
I have a table in SQL Server where personal entries and exits are recorded.
There are multiple hours of entry or exit on the same day. What I need is to recover the first entry and the last exit of the day.

Date       hour   Clock
------------------------
01/01/2017 09:00  1
01/01/2017 11:30  2
01/01/2017 17:00  2
02/01/2017  7:59  1
02/01/2017 16:00  1

I have this SQL query that works correctly.

SELECT
    d.Date,
    MIN(d.hour) as Entry,
    MAX(dt.hour) as Exit
FROM
    #temp1 AS d
LEFT JOIN
    #temp1 AS dt ON d.Date = dt.Date
GROUP BY
    d.Date
ORDER BY
    Date DESC

BUT if I add 2 more columns to the query

SELECT
    d.Date,
    d.clock as ClockEntry,       -- Aggregated column to display
    MIN(d.hour) as Entry,
    dt.clock as ClockExit,       -- Aggregated column to display
    MAX(dt.hour) as Exit
FROM
    #temp1 AS d
LEFT JOIN
    #temp1 AS dt ON d.Date = dt.Date
GROUP BY
    d.Date
ORDER BY
    Date DESC

I get this error:

Column '# temp1.clock' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I just need to group by the field "date", I do not want to add more conditions to the GROUP BY.. How could I solve it?

I want this result

DATE        ClockEntry     Entry    ClockExit    Exit
-------------------------------------------------------
01/01/2017     1           09:00        2        17:00
02/01/2017     1            7:59        1        16:00

Body:
So there is an easy way to do this - use 2 ranking functions:

Partitioned by date, Ordered by the hour ascending

Partitioned by date, Ordered by the hour descending

At that point the rows can be joined where they both have a value of 1, and the dates match.

I tend to use a CTE for this:

with temp2 (MinId, MaxId, Date, Hour, Clock)
AS
(
    select ROW_NUMBER() Over (partition by date order by hour),
     ROW_NUMBER() Over (partition by date order by hour desc),
    *
    from temp1
)
select distinct
       d1.Date,
       d1.Clock,
       d1.Hour,
       d2.Clock,
       d2.Hour
FROM temp2 d1
LEFT JOIN temp2 d2
    ON d1.Date = d2.Date  -- dates match
    AND d1.MinId=d2.MaxId -- minId=earliest record MaxId=latest record
WHERE d1.MinId=1


问:
Can Oracle golden gate adapter read trail file which generated by Extract or Pump process?
I am researching OGG, Can Oracle golden gate adapter read trail file which generated by Extract or Pump process? Most example I can find is OGG adapter works for replication process on delivery server, I just wanna apply the adapter whatever via plat file, jms or java api on extract or pump process directly.</p>

答:
The trail file is just an intermediate internal Oracle GoldenGate format which is used to store the data. The source is processed by the Extract process.

The Extract process can read the data from:

a database transaction log,

a JMS Queue or a flat file (through GoldenGate for Application Adapters)

The Extract process produces as output:

trail files (to be processed by Replicat processes)

XML files

SQL files

If you set a Trail file as the output, then the trail can be processed by:

another Extract (called Data Pump) to transfer the trail files to another location

a replicat Process - to apply the transactions to a destination

Later on the Replicat process can read the trails (produced by Extract) and apply the transactions to:

a database,

a JMS Queue or flat file (through GoldenGate for Application Adapters),

Hadoop, target (through GoldenGate for BigData)

The trail files have internal Oracle proprietary format and can not be produced by non-Oracle programs. You can read their content using the logdump program.


问:
SumIf returns value of 0 when using worksheet.function SumIf
I have created a sumif function using excel's worksheetfunction, please see below

```<code>Public Function sumif(Range As Variant, criteria As Variant, sum_range As Variant)
On Error Resume Next
sumif = WorksheetFunction.sumif(Range, criteria, sum_range)
If IsError(sumif) Then
sumif = ""
End If
End Function
</code>```

With this public function I am attempting to sum the number of hours certain locations are logged onto a specific system. I have included what I am trying to do below

```<code>Private Sub lookupWLDetails()
Dim lngLastRow As Long
Dim vntSiteID As Variant
Dim lngRow As Long
Dim rngDS As Range

With Sheet3
lngLastRow = lastRowInCol(.Columns("B"), 11)
Set rngDS = .Range(.Cells(11, "B"), _
.Cells(lngLastRow, "X"))
End With
</code>```

there is nothing wrong with lastrowinCol function this has been successfully used several times in same excel document so no need to paste that

```<code>With Sheet9
lngLastRow = lastRowInCol(.Columns("B"), 2)
For lngRow = 2 To lngLastRow
vntSiteID = .Cells(lngRow, "B")
.Cells(lngRow, "C") = sumif(rngDS.Columns(3), vntSiteID, rngDS.Columns(7))
.Cells(lngRow, "D") = sumif(rngDS.Columns(3), vntSiteID, rngDS.Columns(8))
Next lngRow
End With
End Sub
</code>```

The top piece of Code is separate from the bottom 2 pieces of code

The bottom 2 pieces of code are part of the same sub

The purpose of this bit of code is to loop through col B on sheet 9 (this holds a list of each site on the report) and then sum all values in each requested column within sheet 3 so long as the site held on sheet 3 col D matches siteID from sheet 9

I am not receiving any errors I just get the value 0 returned from all my sumif attempts

Any help anyone can provide would be much appreciated

Thanks

答:
I have managed to find the answer to my own question in the end but thought I'd share it on her in case anyone wishes to use and adapt this code or is having the same issue I was having.

the only issue with the SumIf function was the declaration of the first range

```<code>.Cells(lngRow, "C") = sumif(rngDS.Columns(3), vntSiteID, rngDS.Columns(7))
.Cells(lngRow, "D") = sumif(rngDS.Columns(3), vntSiteID, rngDS.Columns(8))
</code>```

These should show

```<code>.Cells(lngRow, "C") = sumif(rngDS, vntSiteID, rngDS.Columns(7))
.Cells(lngRow, "D") = sumif(rngDS, vntSiteID, rngDS.Columns(8))
</code>```

Body:
I have created a sumif function using excel's worksheetfunction, please see below

Public Function sumif(Range As Variant, criteria As Variant, sum_range As Variant)
On Error Resume Next
sumif = WorksheetFunction.sumif(Range, criteria, sum_range)
If IsError(sumif) Then
sumif = ""
End If
End Function

With this public function I am attempting to sum the number of hours certain locations are logged onto a specific system. I have included what I am trying to do below

Private Sub lookupWLDetails()
Dim lngLastRow As Long
Dim vntSiteID As Variant
Dim lngRow As Long
Dim rngDS As Range

With Sheet3
lngLastRow = lastRowInCol(.Columns("B"), 11)
Set rngDS = .Range(.Cells(11, "B"), _
.Cells(lngLastRow, "X"))
End With

there is nothing wrong with lastrowinCol function this has been successfully used several times in same excel document so no need to paste that

With Sheet9
lngLastRow = lastRowInCol(.Columns("B"), 2)
For lngRow = 2 To lngLastRow
vntSiteID = .Cells(lngRow, "B")
.Cells(lngRow, "C") = sumif(rngDS.Columns(3), vntSiteID, rngDS.Columns(7))
.Cells(lngRow, "D") = sumif(rngDS.Columns(3), vntSiteID, rngDS.Columns(8))
Next lngRow
End With
End Sub

The top piece of Code is separate from the bottom 2 pieces of code

The bottom 2 pieces of code are part of the same sub

The purpose of this bit of code is to loop through col B on sheet 9 (this holds a list of each site on the report) and then sum all values in each requested column within sheet 3 so long as the site held on sheet 3 col D matches siteID from sheet 9

I am not receiving any errors I just get the value 0 returned from all my sumif attempts

Any help anyone can provide would be much appreciated

Thanks

Body:
I have managed to find the answer to my own question in the end but thought I'd share it on her in case anyone wishes to use and adapt this code or is having the same issue I was having.

the only issue with the SumIf function was the declaration of the first range

.Cells(lngRow, "C") = sumif(rngDS.Columns(3), vntSiteID, rngDS.Columns(7))
.Cells(lngRow, "D") = sumif(rngDS.Columns(3), vntSiteID, rngDS.Columns(8))

These should show

.Cells(lngRow, "C") = sumif(rngDS, vntSiteID, rngDS.Columns(7))
.Cells(lngRow, "D") = sumif(rngDS, vntSiteID, rngDS.Columns(8))


问:
List the names of people that have never scored above 3
From a table like this:

```<code>Name   | Score
------ | ------
Bill   | 1
Bill   | 2
Bill   | 1
Steve  | 1
Steve  | 4
Steve  | 1
</code>```

Return the names of people that have never scored above 3

Answer would be:

```<code>Name   |
------ |
Bill   |
</code>```

答:
one solution would be:</p>

```<code>SELECT DISTINCT name
  FROM mytable
 WHERE Name NOT IN
        ( SELECT Name
            FROM mytable
           WHERE score > 3
        )
</code>```

Body:
From a table like this:

Name   | Score
------ | ------
Bill   | 1
Bill   | 2
Bill   | 1
Steve  | 1
Steve  | 4
Steve  | 1

Return the names of people that have never scored above 3

Answer would be:

Name   |
------ |
Bill   |

Body:
one solution would be:

SELECT DISTINCT name
  FROM mytable
 WHERE Name NOT IN
        ( SELECT Name
            FROM mytable
           WHERE score > 3
        )


问:
Order concatenated left join results
I have following tables:

```<code>Table: person
 id  |  name
  1  |  John
  2  |  Ana
  3  |  Thomas

Table: fruit
 id  |  name
  1  |  orange
  2  |  banana
  3  |  grapefruit
  4  |  lemon
  5  |  apricot

Table: person_fruit
person_id | fruit_id
    1     |     1
    1     |     3
    2     |     1
    2     |     2
    1     |     5
</code>```

As you guessed, the person_fruit table serves as the many to many relation.

I'm doing a query for listing all the persons and their favourite fruits concatenated in a string. My problem is that I cannot display their favourite fruits ordered by fruit name like:

```<code>John   | apricot, grapefruit, orange
Ana    | banana, orange
Thomas | NULL
</code>```

My current MySQL query looks like:

```<code>SELECT
  p.name,
  GROUP_CONCAT(f.name SEPARATOR ', ') fruit
FROM
  person p
LEFT JOIN person_fruit pf
  ON p.id = pf.person_id
LEFT JOIN `fruit` `f`
  ON f.id = pf.fruit_id
GROUP BY
  p.id
</code>```

how can you sort the concatenated left join results?

答:
You can use ORDER BY inside the GROUP_CONCAT.

Also p.name should be in GROUP BY clause

```<code>SELECT
  p.name,
  GROUP_CONCAT(f.name  ORDER by f.name ASC SEPARATOR ',') fruit
FROM
  person p
LEFT JOIN person_fruit pf
  ON p.id = pf.person_id
LEFT JOIN `fruit` `f`
  ON f.id = pf.fruit_id
GROUP BY
  p.name
</code>```

Title: Order concatenated left join results

Body:
I have following tables:

Table: person
 id  |  name
  1  |  John
  2  |  Ana
  3  |  Thomas

Table: fruit
 id  |  name
  1  |  orange
  2  |  banana
  3  |  grapefruit
  4  |  lemon
  5  |  apricot

Table: person_fruit
person_id | fruit_id
    1     |     1
    1     |     3
    2     |     1
    2     |     2
    1     |     5

As you guessed, the person_fruit table serves as the many to many relation.

I'm doing a query for listing all the persons and their favourite fruits concatenated in a string. My problem is that I cannot display their favourite fruits ordered by fruit name like:

John   | apricot, grapefruit, orange
Ana    | banana, orange
Thomas | NULL

My current MySQL query looks like:

SELECT
  p.name,
  GROUP_CONCAT(f.name SEPARATOR ', ') fruit
FROM
  person p
LEFT JOIN person_fruit pf
  ON p.id = pf.person_id
LEFT JOIN `fruit` `f`
  ON f.id = pf.fruit_id
GROUP BY
  p.id

how can you sort the concatenated left join results?

Body:
You can use ORDER BY inside the GROUP_CONCAT.

Also p.name should be in GROUP BY clause

SELECT
  p.name,
  GROUP_CONCAT(f.name  ORDER by f.name ASC SEPARATOR ',') fruit
FROM
  person p
LEFT JOIN person_fruit pf
  ON p.id = pf.person_id
LEFT JOIN `fruit` `f`
  ON f.id = pf.fruit_id
GROUP BY
  p.name


问:
Node.js http.get xml is returned 'escaped'
I am working on a simple AWS Lambda function in Javascript (Node 6.x) which should 'proxy' an RSS of an italian news provider.

This is the code of the function:

```<code>var http = require("http")

exports.handler = (event, context, callback) => {
    http.get("http://www.milanotoday.it/rss/", (response) => {
        response.setEncoding("utf8")

        let xml = ""
        response.on("data", (chunk) => { xml += chunk })
        response.on("end", () => { callback(null, xml) })
    })
}
</code>```

It works, or at least it loads the response inside the xml variable.
I can't get why the string is something like this:

```<code>"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\" xmlns:content=\"http://purl.org/rss/1.0/modules/content/\"...
</code>```

It seems to be sort of 'escaped'.

Can somebody help me?
Thank you in advance...

答: Double quotes have to be escaped inside a double quoted string (Makes sense, right?). Now you just have to parse the XML, using for instance xml2js</p>

Body:
I am working on a simple AWS Lambda function in Javascript (Node 6.x) which should 'proxy' an RSS of an italian news provider.

This is the code of the function:

var http = require("http")

exports.handler = (event, context, callback) => {
    http.get("http://www.milanotoday.it/rss/", (response) => {
        response.setEncoding("utf8")

        let xml = ""
        response.on("data", (chunk) => { xml += chunk })
        response.on("end", () => { callback(null, xml) })
    })
}

It works, or at least it loads the response inside the xml variable.
I can't get why the string is something like this:

"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\" xmlns:content=\"http://purl.org/rss/1.0/modules/content/\"...

It seems to be sort of 'escaped'.

Can somebody help me?
Thank you in advance...


问:
Getting NullPointerException when running Spark Code in Zeppelin 0.7.1
I have installed Zeppelin 0.7.1. When I tried to execute the Example spark program(which was available with Zeppelin Tutorial notebook), I am getting the following error

```<code>java.lang.NullPointerException
    at org.apache.zeppelin.spark.Utils.invokeMethod(Utils.java:38)
    at org.apache.zeppelin.spark.Utils.invokeMethod(Utils.java:33)
    at org.apache.zeppelin.spark.SparkInterpreter.createSparkContext_2(SparkInterpreter.java:391)
    at org.apache.zeppelin.spark.SparkInterpreter.createSparkContext(SparkInterpreter.java:380)
    at org.apache.zeppelin.spark.SparkInterpreter.getSparkContext(SparkInterpreter.java:146)
    at org.apache.zeppelin.spark.SparkInterpreter.open(SparkInterpreter.java:828)
    at org.apache.zeppelin.interpreter.LazyOpenInterpreter.open(LazyOpenInterpreter.java:70)
    at org.apache.zeppelin.interpreter.remote.RemoteInterpreterServer$InterpretJob.jobRun(RemoteInterpreterServer.java:483)
    at org.apache.zeppelin.scheduler.Job.run(Job.java:175)
    at org.apache.zeppelin.scheduler.FIFOScheduler$1.run(FIFOScheduler.java:139)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
</code>```

I have also setup the config file(zeppelin-env.sh) to point to my Spark installation & Hadoop configuration directory

```<code>export SPARK_HOME="/${homedir}/sk"
export HADOOP_CONF_DIR="/${homedir}/hp/etc/hadoop"
</code>```

The Spark version I am using is 2.1.0 & Hadoop is 2.7.3

Also I am using the default Spark Interpreter Configuration(so Spark is set to run in Local mode)

Am I missing something here?

PS : I am able to connect to spark from the Terminal using spark-shell

答: Seems to be bug in Zeppelin 0.7.1.  Works fine in 0.7.2.</p>

Body:
I have installed Zeppelin 0.7.1. When I tried to execute the Example spark program(which was available with Zeppelin Tutorial notebook), I am getting the following error

java.lang.NullPointerException
    at org.apache.zeppelin.spark.Utils.invokeMethod(Utils.java:38)
    at org.apache.zeppelin.spark.Utils.invokeMethod(Utils.java:33)
    at org.apache.zeppelin.spark.SparkInterpreter.createSparkContext_2(SparkInterpreter.java:391)
    at org.apache.zeppelin.spark.SparkInterpreter.createSparkContext(SparkInterpreter.java:380)
    at org.apache.zeppelin.spark.SparkInterpreter.getSparkContext(SparkInterpreter.java:146)
    at org.apache.zeppelin.spark.SparkInterpreter.open(SparkInterpreter.java:828)
    at org.apache.zeppelin.interpreter.LazyOpenInterpreter.open(LazyOpenInterpreter.java:70)
    at org.apache.zeppelin.interpreter.remote.RemoteInterpreterServer$InterpretJob.jobRun(RemoteInterpreterServer.java:483)
    at org.apache.zeppelin.scheduler.Job.run(Job.java:175)
    at org.apache.zeppelin.scheduler.FIFOScheduler$1.run(FIFOScheduler.java:139)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

I have also setup the config file(zeppelin-env.sh) to point to my Spark installation & Hadoop configuration directory

export SPARK_HOME="/${homedir}/sk"
export HADOOP_CONF_DIR="/${homedir}/hp/etc/hadoop"

The Spark version I am using is 2.1.0 & Hadoop is 2.7.3

Also I am using the default Spark Interpreter Configuration(so Spark is set to run in Local mode)

Am I missing something here?

PS : I am able to connect to spark from the Terminal using spark-shell


问:
Recieve JSON Object with 2 Arrays
im literally new at working with JSON and I have a problem with my Web Service. With normal JSON Objects i no problems. I want to get two Arrays from the Web Service (String and Integer), so i tried to put them into two JSON Array´s and this two into a JSON Object. Now i want them to get into my Android application, but im just getting errors.

```<code>public static String constructJSON(Integer[] array, String[] array2) {
    JSONObject mainObj = new JSONObject();
    try {
    JSONObject firstArray = new JSONObject();
    firstArray.put("array0", array[0]);
    firstArray.put("array1", array[1]);
    firstArray.put("array2", array[2]);
    firstArray.put("array3", array[3]);
    firstArray.put("array4", array[4]);

    JSONObject secondArray = new JSONObject();
    secondArray.put("sArray0", array2[0]);
    secondArray.put("sArray1", array2[1]);
    secondArray.put("sArray2", array2[2]);
    secondArray.put("sArray3", array2[3]);
    secondArray.put("sArray4", array2[4]);

    JSONArray JArr = new JSONArray();
    JArr.put(firstArray);
    JArr.put(secondArray);

    mainObj.put("arrays", JArr);
    } catch (JSONException e) {
    }
    return mainObj.toString();
}
</code>```

And now the method in Android Studio:

```<code>private void getBW(String krankheit) {
        RequestParams params = new RequestParams();
        params.put("krankheit", krankheit);
        // Invoke RESTful Web Service with Http parameters
        AsyncHttpClient client = new AsyncHttpClient();
        client.get(url, params, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(String response) {
                try {
                    // JSON Object
                    JSONObject obj = new JSONObject(response);
                    JSONArray firstJsonArr= obj.getJSONArray("array1");
                    JSONArray secondJsonArr= obj.getJSONArray("array2");
                    for (int k = 0; k < 5; k++) {
                        Bewertung1[k] = (Integer) firstJsonArr.get(k);

                    }
                    for (int j = 0; j < 5; j++) {
                        medikament[j] = (String) secondJsonArr.get(j);

                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                    e.printStackTrace();

                }

            }
        });

        }
</code>```

I tried different solution´s, but none of them worked for me. I hope you guys can help me.

答:
I would recommend you to use gson library for android. Its provides simple function to parse from and to json object.
Have a look at this library : https://github.com/google/gson</p>

Title: Recieve JSON Object with 2 Arrays

Body:
im literally new at working with JSON and I have a problem with my Web Service. With normal JSON Objects i no problems. I want to get two Arrays from the Web Service (String and Integer), so i tried to put them into two JSON Array´s and this two into a JSON Object. Now i want them to get into my Android application, but im just getting errors.

public static String constructJSON(Integer[] array, String[] array2) {
    JSONObject mainObj = new JSONObject();
    try {
    JSONObject firstArray = new JSONObject();
    firstArray.put("array0", array[0]);
    firstArray.put("array1", array[1]);
    firstArray.put("array2", array[2]);
    firstArray.put("array3", array[3]);
    firstArray.put("array4", array[4]);

    JSONObject secondArray = new JSONObject();
    secondArray.put("sArray0", array2[0]);
    secondArray.put("sArray1", array2[1]);
    secondArray.put("sArray2", array2[2]);
    secondArray.put("sArray3", array2[3]);
    secondArray.put("sArray4", array2[4]);

    JSONArray JArr = new JSONArray();
    JArr.put(firstArray);
    JArr.put(secondArray);

    mainObj.put("arrays", JArr);
    } catch (JSONException e) {
    }
    return mainObj.toString();
}

And now the method in Android Studio:

private void getBW(String krankheit) {
        RequestParams params = new RequestParams();
        params.put("krankheit", krankheit);
        // Invoke RESTful Web Service with Http parameters
        AsyncHttpClient client = new AsyncHttpClient();
        client.get(url, params, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(String response) {
                try {
                    // JSON Object
                    JSONObject obj = new JSONObject(response);
                    JSONArray firstJsonArr= obj.getJSONArray("array1");
                    JSONArray secondJsonArr= obj.getJSONArray("array2");
                    for (int k = 0; k < 5; k++) {
                        Bewertung1[k] = (Integer) firstJsonArr.get(k);

                    }
                    for (int j = 0; j < 5; j++) {
                        medikament[j] = (String) secondJsonArr.get(j);

                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                    e.printStackTrace();

                }

            }
        });

        }

I tried different solution´s, but none of them worked for me. I hope you guys can help me.


问:
Excel vba custom lookup function: fast when used manually, slow in macros
I had to write my own lookup function, but its performance differs dramatically depending whether or not I call it by hand on worksheet itself (through '=') or through macros. My macros does the following:

```<code>Function betterSearch(searchCell As Range, aCol As Range, bCol As Range)
        For Each cell In aCol
            If LCase(cell.Value) = LCase(searchCell.Value) Then
                    betterSearch = bCol.Cells(cell.row, 1)
                    Exit For
            End If
            betterSearch = "Not found"
        Next
End Function
</code>```

So the macros opens resultsWorkbook and dataWorkbook and then performs a search of the four values in column A from resultWorkbook in dataWorkbook and returns corresponding data from some other column of dataWorkbook.

```<code>'...opening resultWorkbook and dataWorkbook
For aRow = 6 To 9
            resultWorkbook.Worksheets("B3").Cells(aRow, 125).Value = _
                betterSearch(resultWorkbook.Worksheets("B3").Cells(aRow, 1) _
                , dataWorkbook.Worksheets("page 1").Range("A:A") _
                , dataWorkbook.Worksheets("page 1").Range("Z:Z"))

             resultWorkbook.Worksheets("B3").Cells(aRow, 126).Value = _
                betterSearch(resultWorkbook.Worksheets("B3").Cells(aRow, 1) _
                , dataWorkbook.Worksheets("page 1").Range("A:A") _
                , dataWorkbook.Worksheets("page 1").Range("I:I"))
Next aRow
</code>```

It's really slow - takes minutes for 1 file. But when I open that file manually and just type in the formula and hit Enter it calculates instantly.

What is wrong here? Where does this behaviour come from?

答:
It might be slow if it attempts to search through the entire columns A:A, I:I (1+ million cells)

Try updating your betterSearch to this:

```<code>Function betterSearch(searchCell As Range, aCol As Range, bCol As Range)
    Dim itm As String, col1 As Variant, col2 As Variant, r As Long

    With ActiveSheet
        col1 = .UsedRange.Columns(aCol.Column)
        col2 = .UsedRange.Columns(bCol.Column)
    End With

    betterSearch = "Not found"
    itm = LCase(searchCell.Value2)

    For r = 1 To UBound(col1)
        If Len(col1(r, 1)) > 0 Then
            If LCase(col1(r, 1)) = itm Then
                betterSearch = col2(r, 1)
                Exit Function
            End If
        End If
    Next
End Function
</code>```

Body:
I had to write my own lookup function, but its performance differs dramatically depending whether or not I call it by hand on worksheet itself (through '=') or through macros. My macros does the following:

Function betterSearch(searchCell As Range, aCol As Range, bCol As Range)
        For Each cell In aCol
            If LCase(cell.Value) = LCase(searchCell.Value) Then
                    betterSearch = bCol.Cells(cell.row, 1)
                    Exit For
            End If
            betterSearch = "Not found"
        Next
End Function

So the macros opens resultsWorkbook and dataWorkbook and then performs a search of the four values in column A from resultWorkbook in dataWorkbook and returns corresponding data from some other column of dataWorkbook.

'...opening resultWorkbook and dataWorkbook
For aRow = 6 To 9
            resultWorkbook.Worksheets("B3").Cells(aRow, 125).Value = _
                betterSearch(resultWorkbook.Worksheets("B3").Cells(aRow, 1) _
                , dataWorkbook.Worksheets("page 1").Range("A:A") _
                , dataWorkbook.Worksheets("page 1").Range("Z:Z"))

             resultWorkbook.Worksheets("B3").Cells(aRow, 126).Value = _
                betterSearch(resultWorkbook.Worksheets("B3").Cells(aRow, 1) _
                , dataWorkbook.Worksheets("page 1").Range("A:A") _
                , dataWorkbook.Worksheets("page 1").Range("I:I"))
Next aRow

It's really slow - takes minutes for 1 file. But when I open that file manually and just type in the formula and hit Enter it calculates instantly.

What is wrong here? Where does this behaviour come from?

Body:
It might be slow if it attempts to search through the entire columns A:A, I:I (1+ million cells)

Try updating your betterSearch to this:

Function betterSearch(searchCell As Range, aCol As Range, bCol As Range)
    Dim itm As String, col1 As Variant, col2 As Variant, r As Long

    With ActiveSheet
        col1 = .UsedRange.Columns(aCol.Column)
        col2 = .UsedRange.Columns(bCol.Column)
    End With

    betterSearch = "Not found"
    itm = LCase(searchCell.Value2)

    For r = 1 To UBound(col1)
        If Len(col1(r, 1)) > 0 Then
            If LCase(col1(r, 1)) = itm Then
                betterSearch = col2(r, 1)
                Exit Function
            End If
        End If
    Next
End Function


问:
How do I write to a text file in MATLAB?
I need to remove 'index.html' string from every line of my index.html files....

I need this to be done in MATLAB.

Here is what I have so far...

I don't know how to write the line, after I've modified it, back over the same line in the html file.

```<code>fid=fopen('index.html');

while ~feof(fid)

    tline=fgetl(fid);

if ~isempty(strfind(tline,'index.html'))
    remline=strrep( tline ,'index.html','');

**% fprintf(fid,remline);
%  fprintf('\n')**

end

end
</code>```

Update

This solution worked for me:

```<code>function WriteToFile(filename)

fid = fopen(filename, 'r+');
fid2 = fopen('index.txt', 'w');

while ~feof(fid)

    tline=fgetl(fid);

    if ~isempty(strfind(tline,'index.html'))
        remline=strrep(tline,'index.html','');

        fprintf(fid2, '%s\r\n', remline);
    else
        fprintf(fid2, '%s\r\n', tline);
    end
end

fclose(fid);
fclose(fid2);

delete(filename)
keyboard
movefile('index.txt','index.html')
</code>```

答:
Modifying Niko's answer (replacing %d with %s) to put actual text into the file a1.m:

```<code>fid = fopen('a1.m','w');%open file for writing
fprintf(fid, '%s\n', 'some_text');%write a line of text
fclose(fid);%close file
</code>```

Body:
I need to remove 'index.html' string from every line of my index.html files....

I need this to be done in MATLAB.

Here is what I have so far...

I don't know how to write the line, after I've modified it, back over the same line in the html file.

fid=fopen('index.html');

while ~feof(fid)

    tline=fgetl(fid);

if ~isempty(strfind(tline,'index.html'))
    remline=strrep( tline ,'index.html','');

**% fprintf(fid,remline);
%  fprintf('\n')**

end

end

Update

This solution worked for me:

function WriteToFile(filename)

fid = fopen(filename, 'r+');
fid2 = fopen('index.txt', 'w');

while ~feof(fid)

    tline=fgetl(fid);

    if ~isempty(strfind(tline,'index.html'))
        remline=strrep(tline,'index.html','');

        fprintf(fid2, '%s\r\n', remline);
    else
        fprintf(fid2, '%s\r\n', tline);
    end
end

fclose(fid);
fclose(fid2);

delete(filename)
keyboard
movefile('index.txt','index.html')

Body:
Modifying Niko's answer (replacing %d with %s) to put actual text into the file a1.m:

fid = fopen('a1.m','w');%open file for writing
fprintf(fid, '%s\n', 'some_text');%write a line of text
fclose(fid);%close file


答:
sample table :

```<code>DECLARE @Table1  TABLE
    (Name varchar(5), Score int)
;

INSERT INTO @Table1
    (Name, Score)
VALUES
    ('Bill', 1),
    ('Bill', 2),
    ('Bill', 1),
    ('Steve', 1),
    ('Steve', 4),
    ('Steve', 1)
;
</code>```

Script :

```<code>;with CTE AS (
select Name,Score from @Table1
GROUP BY Name,Score
HAVING (Score) > 3 )
Select
NAME,
Score
from  @Table1 T
where not EXISTS
(select name from CTE
        where name = T.Name )
</code>```

Result :

```<code>NAME    Score
Bill    1
Bill    2
Bill    1
</code>```

Title: List the names of people that have never scored above 3

Body:
sample table :

DECLARE @Table1  TABLE
    (Name varchar(5), Score int)
;

INSERT INTO @Table1
    (Name, Score)
VALUES
    ('Bill', 1),
    ('Bill', 2),
    ('Bill', 1),
    ('Steve', 1),
    ('Steve', 4),
    ('Steve', 1)
;

Script :

;with CTE AS (
select Name,Score from @Table1
GROUP BY Name,Score
HAVING (Score) > 3 )
Select
NAME,
Score
from  @Table1 T
where not EXISTS
(select name from CTE
        where name = T.Name )

Result :

NAME    Score
Bill    1
Bill    2
Bill    1


问:
angular2 help and clarification
I'm in the process of reading Beginning Angular2 with TypeScript by Greg Lim.

I'm up to chapter 4 and up until now I was doing well, however I just seem to be a bit lost at the min. In app.module I have the following declarations

```<code>    AppComponent,
    ProductsComponents,
    RatingComponent,
    ProductComponent
</code>```

and in app.components I have

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `<h1>{{title}}</h1>
        <products></products>`
})
export class AppComponent {
    title: string = 'app works!!!';
}
</code>```

and in my products.components I have

```<code>import { ProductService } from './product.service'

@Component({
    selector: 'products',
    template: `<h2>Products</h2>
         <div *ngFor="let product of products">
          <product [data]="product"></product>
          </div>`,
    providers: [ProductService]
})

export class ProductsComponents {
    products;
    constructor(productService: ProductService) {
    this.products = productService.getProducts();
    }
}
</code>```

In rating.component I have

```<code>import { Component, Input } from '@angular/core'

@Component({
    selector: "rating",
    templateUrl: 'rating.component.html',
    styles: [`
        .glyphicon-star { color:orange; }
        `]
})

export class RatingComponent {
    @Input('rating-value') rating = 0;
    @Input() numOfReviews = 0;
    onClick(ratingValue) {
    this.rating = ratingValue;
    }
}
</code>```

In product.component I have

```<code>import { Component, Input } from '@angular/core';

@Component({
    selector: 'product',
    template: `<div class="media">
          <div class="media-left">
            <a href="#">
              <img class="media-object" src="{{data.imageUrl}}" alt="...">
            </a>
          </div>
        <div class="media-body">
          <h4 class="media-heading">{{data.productName}}</h4>
          {{data.releasedDate}}
          <rating
            [rating-value]="data.rating"
            [numOfReviews]="data.numOfReviews">
          </rating>
          <br />
          {{data.description}}
        </div>
          </div>
      `,
    styles: [`
      .media {
      margin-bottom:20px;
      }
    `]
})

export class ProductComponent {
    @Input() data;
}
</code>```

and lastly in product.service I have

```<code>export class ProductService {
    getProducts() {
    return [
        {
        imageUrl: "http://loremflickr.com/150/150?random=1",
        productName: "Product 1",
        releasedDate: "May 31, 2016",
        description: "Product description for product 1",
        rating: 2,
        numOfReviews: 5
        },
        {
        imageUrl: "http://loremflickr.com/150/150?random=2",
        productName: "Product 2",
        releasedDate: "May 31, 2016",
        description: "Product description for product 2",
        rating: 4,
        numOfReviews: 6
        },
        {
        imageUrl: "http://loremflickr.com/150/150?random=3",
        productName: "Product 3",
        releasedDate: "May 31, 2016",
        description: "Product description for product 3",
        rating: 1,
        numOfReviews: 5
        },
        {
        imageUrl: "http://loremflickr.com/150/150?random=4",
        productName: "Product 4",
        releasedDate: "May 31, 2016",
        description: "Product description for product 4",
        rating: 5,
        numOfReviews: 1
        }
    ];
    }
}
</code>```

All of which is working fine.

I understand that in products.components is is populating the array that it then passes into the ngFor, but I can't work out how rating.component and product.component are pulled into that for loop.

Can someone explain?

Thanks

答:
that is what ngFor does:

```<code><h2>Products</h2>
     <div *ngFor="let product of products">
      <product [data]="product"></product>
      </div>
</code>```

gets rendered into:

```<code><h2>Products</h2>
     <div>
      <product [data]="product1"></product>
      </div>

     <div>
      <product [data]="product2"></product>
      </div>

      <div>
      <product [data]="product3"></product>
      </div>
...
</code>```

then your each product component contains rating component and feeds it with its particular product (that came from array).

[UPDATE]

your products.component has this template:

```<code>template: `<h2>Products</h2>
         <div *ngFor="let product of products">
          <product [data]="product"></product>
          </div>`,
</code>```

and in your product.component you have set selector:

```<code>selector: 'product'
</code>```

Notice <product> element in your template. That is, at the same time, selector for product.component so angular knows that it should run product.component whenever element <product> is used in template.

Title: angular2 help and clarification

Body:
I'm in the process of reading Beginning Angular2 with TypeScript by Greg Lim.

I'm up to chapter 4 and up until now I was doing well, however I just seem to be a bit lost at the min. In app.module I have the following declarations

    AppComponent,
    ProductsComponents,
    RatingComponent,
    ProductComponent

and in app.components I have

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
{{title}}

        <products></products>`
})
export class AppComponent {
    title: string = 'app works!!!';
}

and in my products.components I have

import { ProductService } from './product.service'

@Component({
    selector: 'products',
    template: `
Products

          <product [data]="product"></product>

`,
    providers: [ProductService]
})

export class ProductsComponents {
    products;
    constructor(productService: ProductService) {
    this.products = productService.getProducts();
    }
}

In rating.component I have

import { Component, Input } from '@angular/core'

@Component({
    selector: "rating",
    templateUrl: 'rating.component.html',
    styles: [`
        .glyphicon-star { color:orange; }
        `]
})

export class RatingComponent {
    @Input('rating-value') rating = 0;
    @Input() numOfReviews = 0;
    onClick(ratingValue) {
    this.rating = ratingValue;
    }
}

In product.component I have

import { Component, Input } from '@angular/core';

@Component({
    selector: 'product',
    template: `

{{data.productName}}

          {{data.releasedDate}}
          <rating
            [rating-value]="data.rating"
            [numOfReviews]="data.numOfReviews">
          </rating>

          {{data.description}}

      `,
    styles: [`
      .media {
      margin-bottom:20px;
      }
    `]
})

export class ProductComponent {
    @Input() data;
}

and lastly in product.service I have

export class ProductService {
    getProducts() {
    return [
        {
        imageUrl: "http://loremflickr.com/150/150?random=1",
        productName: "Product 1",
        releasedDate: "May 31, 2016",
        description: "Product description for product 1",
        rating: 2,
        numOfReviews: 5
        },
        {
        imageUrl: "http://loremflickr.com/150/150?random=2",
        productName: "Product 2",
        releasedDate: "May 31, 2016",
        description: "Product description for product 2",
        rating: 4,
        numOfReviews: 6
        },
        {
        imageUrl: "http://loremflickr.com/150/150?random=3",
        productName: "Product 3",
        releasedDate: "May 31, 2016",
        description: "Product description for product 3",
        rating: 1,
        numOfReviews: 5
        },
        {
        imageUrl: "http://loremflickr.com/150/150?random=4",
        productName: "Product 4",
        releasedDate: "May 31, 2016",
        description: "Product description for product 4",
        rating: 5,
        numOfReviews: 1
        }
    ];
    }
}

All of which is working fine.

I understand that in products.components is is populating the array that it then passes into the ngFor, but I can't work out how rating.component and product.component are pulled into that for loop.

Can someone explain?

Thanks

Body:
that is what ngFor does:

<h2>Products</h2>
     <div *ngFor="let product of products">
      <product [data]="product"></product>
      </div>

gets rendered into:

<h2>Products</h2>
     <div>
      <product [data]="product1"></product>
      </div>

     <div>
      <product [data]="product2"></product>
      </div>

      <div>
      <product [data]="product3"></product>
      </div>
...

then your each product component contains rating component and feeds it with its particular product (that came from array).

[UPDATE]

your products.component has this template:

template: `<h2>Products</h2>
         <div *ngFor="let product of products">
          <product [data]="product"></product>
          </div>`,

and in your product.component you have set selector:

selector: 'product'

Notice <product> element in your template. That is, at the same time, selector for product.component so angular knows that it should run product.component whenever element <product> is used in template.


问:
Query one table, to get name from another table
I have 3 tables in my database, Categories,Subcategories and Articles.
My Articles table contains columns caled CategoryID and SubcategoryID, which are foreign keys of the table Categories and Subcategories.

My question is, how can I get the name of the Category and Subcategory stored only as ID's in my Articles Table.

I think I need a kind of subquery or join.

Here is what I have:

```<code>SELECT ArticleTitle
      ,CategoryID
      ,SubcategoryID
  FROM Articles
 WHERE SubcategoryID =
        (SELECT SubcategoryName
           FROM Subcategories
          WHERE SubcategoryName = 'info'
         )
</code>```

When I execute this code in mysql, there are no erros, but I receive 0 results. All tables are containing some data.

答:
change this:

```<code>where SubcategoryID = (select SubcategoryName from Subcategories
</code>```

to this

```<code>where SubcategoryID in (select SubcategoryID from Subcategories
</code>```

the changes were

the equal sign is now the word in.

the subquery is selecting SubcategoryID instead of SubCategoryName

Body:
I have 3 tables in my database, Categories,Subcategories and Articles.
My Articles table contains columns caled CategoryID and SubcategoryID, which are foreign keys of the table Categories and Subcategories.

My question is, how can I get the name of the Category and Subcategory stored only as ID's in my Articles Table.

I think I need a kind of subquery or join.

Here is what I have:

SELECT ArticleTitle
      ,CategoryID
      ,SubcategoryID
  FROM Articles
 WHERE SubcategoryID =
        (SELECT SubcategoryName
           FROM Subcategories
          WHERE SubcategoryName = 'info'
         )

When I execute this code in mysql, there are no erros, but I receive 0 results. All tables are containing some data.

Body:
change this:

where SubcategoryID = (select SubcategoryName from Subcategories

to this

where SubcategoryID in (select SubcategoryID from Subcategories

the changes were

the equal sign is now the word in.

the subquery is selecting SubcategoryID instead of SubCategoryName


问:
How to display limited data using Angular.js?
I have seen enough examples on how to display the limited results using limitTo. But unfortunately it isn't working as expected. Currently, it is displaying the entire list but I want to limit it to only 8 key,value items in 4/4 blocks.

Here is the plnkr.

```<code>  <ul>
      <li ng-repeat="(key,value) in stocks |limitTo :8">
            {{key +" "+ value}}
      </li>
  </ul>

 <script>
    var app = angular.module('smallcaseApp', []);
    app.controller('stockCtrl', function($scope, $http) {
    $http.get("data.json").then(function(response) {
        $scope.stocks = response.data.price;
      });
    });
 </script>
</code>```

答:
First of all your plunkr is not working, angular js link should be above any other js (your app js).

You are iterating in a Object, for using limitTo here there's already a working good example, please take a look SO Link

Body:
I have seen enough examples on how to display the limited results using limitTo. But unfortunately it isn't working as expected. Currently, it is displaying the entire list but I want to limit it to only 8 key,value items in 4/4 blocks.

Here is the plnkr.

            {{key +" "+ value}}


问:
How to declare resource before Window in XAML?
My code:

```<code><Window ...
    Title="Notification" Height="90" Width="300" ResizeMode="NoResize" WindowStyle="None" DataContext="{Binding Notification, Source={StaticResource Locator}}" Opacity="{Binding TransitionOpacity}" Left="{Binding LeftMargin}" Top="{Binding TopMargin}"  Visibility="{Binding IsVisible, Converter={StaticResource BoolToVisibility}}">
<Window.Resources>
    <local:BoolToVisibleOrHidden x:Key="BoolToVisibility" />
</Window.Resources>
    <Grid Background="#FF3C4759">
    ...
</Window>
</code>```

While compiling I get exception System.Windows.Markup.XamlParseException and after change code to

```<code><Window ...
    Title="Notification" Height="90" Width="300" ResizeMode="NoResize" WindowStyle="None" DataContext="{Binding Notification, Source={StaticResource Locator}}" Opacity="{Binding TransitionOpacity}"  Left="{Binding LeftMargin}" Top="{Binding TopMargin}" >
<Window.Resources>
    <local:BoolToVisibleOrHidden x:Key="BoolToVisibility" />
</Window.Resources>
    <Grid Background="#FF3C4759" Visibility="{Binding IsVisible, Converter={StaticResource BoolToVisibility}}">
    ...
</Window>
</code>```

it works but I want to set Window visibility instead of Grid.

答:
Binding window visibility might be not a good idea in this case. If you have a notification which you want to hide after some time - just close it (Close()) instead of hiding.

If however you still want to do this - put converter into your application ( App.xaml file). Then you will be able to use it in Window.Visibility binding. As of now - window Visibility property is set before Window.Resources are initialized, so you cannot use converter created inside Window.Resources.

Alternative way is to set Visibility like this:

```<code><Window.Resources>
    <local:BoolToVisibleOrHidden x:Key="BoolToVisibility" />
</Window.Resources>
<Window.Visibility>
    <Binding Path="IsVisible" Converter="{StaticResource BoolToVisibility}" />
</Window.Visibility>
</code>```

Body:
My code:

<Window ...
    Title="Notification" Height="90" Width="300" ResizeMode="NoResize" WindowStyle="None" DataContext="{Binding Notification, Source={StaticResource Locator}}" Opacity="{Binding TransitionOpacity}" Left="{Binding LeftMargin}" Top="{Binding TopMargin}"  Visibility="{Binding IsVisible, Converter={StaticResource BoolToVisibility}}">
<Window.Resources>
    <local:BoolToVisibleOrHidden x:Key="BoolToVisibility" />
</Window.Resources>
    <Grid Background="#FF3C4759">
    ...
</Window>

While compiling I get exception System.Windows.Markup.XamlParseException and after change code to

<Window ...
    Title="Notification" Height="90" Width="300" ResizeMode="NoResize" WindowStyle="None" DataContext="{Binding Notification, Source={StaticResource Locator}}" Opacity="{Binding TransitionOpacity}"  Left="{Binding LeftMargin}" Top="{Binding TopMargin}" >
<Window.Resources>
    <local:BoolToVisibleOrHidden x:Key="BoolToVisibility" />
</Window.Resources>
    <Grid Background="#FF3C4759" Visibility="{Binding IsVisible, Converter={StaticResource BoolToVisibility}}">
    ...
</Window>

it works but I want to set Window visibility instead of Grid.

Body:
Binding window visibility might be not a good idea in this case. If you have a notification which you want to hide after some time - just close it (Close()) instead of hiding.

If however you still want to do this - put converter into your application ( App.xaml file). Then you will be able to use it in Window.Visibility binding. As of now - window Visibility property is set before Window.Resources are initialized, so you cannot use converter created inside Window.Resources.

Alternative way is to set Visibility like this:

<Window.Resources>
    <local:BoolToVisibleOrHidden x:Key="BoolToVisibility" />
</Window.Resources>
<Window.Visibility>
    <Binding Path="IsVisible" Converter="{StaticResource BoolToVisibility}" />
</Window.Visibility>


问:
avoiding if else statement
I have the following ifelse statement:

```<code>Years=c(2016, 2021, 2026, 2031, 2035)
if (Year == Years[1]){OD = subset(data,data$YEAR>=Years[1] & data$YEAR <= Years[1]+2)}
if (Year == Years[2]){OD = subset(data,data$YEAR>=Years[2]-2 & data$YEAR <= Years[2]+2)}
if (Year == Years[3]){OD = subset(data,data$YEAR>=Years[3]-2 & data$YEAR <= Years[3]+2)}
if (Year == Years[4]){OD = subset(data,data$YEAR>=Years[4]-2 & data$YEAR <= Years[4]+2)}
if (Year == Years[5]){OD = subset(data,data$YEAR>=Years[5]-1 & data$YEAR <= Years[5])}
</code>```

And I would like an efficient way to write this without ifelse statement.

答:
I'm not sure what the rules are for defining the lower and upper bounds of the years, but how about first creating vectors defining the lower and upper bounds:

```<code>Years <- c(2016, 2021, 2026, 2031, 2035)
Years.lower <- c(2016, 2021-2, 2026-2, 2031-2, 2035-1)
Years.upper <- c(2016+2, 2021+2, 2026+2, 2031+2, 2035)
</code>```

Then subset data according to which of the Years the object Year corresponds to:

```<code>OD <- subset(data, data$YEAR>=Years.lower[which(Years==Year)] & data$YEAR <= Years.upper[which(Years==Year)])
</code>```

Title: avoiding if else statement

Body:
I have the following ifelse statement:

Years=c(2016, 2021, 2026, 2031, 2035)
if (Year == Years[1]){OD = subset(data,data$YEAR>=Years[1] & data$YEAR <= Years[1]+2)}
if (Year == Years[2]){OD = subset(data,data$YEAR>=Years[2]-2 & data$YEAR <= Years[2]+2)}
if (Year == Years[3]){OD = subset(data,data$YEAR>=Years[3]-2 & data$YEAR <= Years[3]+2)}
if (Year == Years[4]){OD = subset(data,data$YEAR>=Years[4]-2 & data$YEAR <= Years[4]+2)}
if (Year == Years[5]){OD = subset(data,data$YEAR>=Years[5]-1 & data$YEAR <= Years[5])}

And I would like an efficient way to write this without ifelse statement.

Body:
I'm not sure what the rules are for defining the lower and upper bounds of the years, but how about first creating vectors defining the lower and upper bounds:

Years <- c(2016, 2021, 2026, 2031, 2035)
Years.lower <- c(2016, 2021-2, 2026-2, 2031-2, 2035-1)
Years.upper <- c(2016+2, 2021+2, 2026+2, 2031+2, 2035)

Then subset data according to which of the Years the object Year corresponds to:

OD <- subset(data, data$YEAR>=Years.lower[which(Years==Year)] & data$YEAR <= Years.upper[which(Years==Year)])


问:
Shell equivalent to PHP's preg_replace()
Greetz folks.

I'm looking for a way to do the same stuff than PHP's preg_replace() does (search text matching a regular expression and replace it) in a shell script.

So, consider the following file.

```<code><a href="http://example.com/">Website #1</a>
<a href="http://example.net/">Website #2</a>
<a href="http://example.org/">Website #3</a>
</code>```

And I want to get this:

```<code>http://example.com/
http://example.net/
http://example.org/
</code>```

Is there a way to do this? Thanks.

答:
You can use sed as:

```<code>sed -r 's/.*href="([^"]*)".*/\1/' file
</code>```

See it

Body:
Greetz folks.

I'm looking for a way to do the same stuff than PHP's preg_replace() does (search text matching a regular expression and replace it) in a shell script.

So, consider the following file.

Website #1
Website #2
Website #3

And I want to get this:

http://example.com/
http://example.net/
http://example.org/

Is there a way to do this? Thanks.

Body:
You can use sed as:

sed -r 's/.*href="([^"]*)".*/\1/' file

See it


问:
Convert long number into abbreviated string in JavaScript, with a special shortness requirement
In JavaScript, how would one write a function that converts a given [edit: positive integer] number (below 100 billion) into a 3-letter abbreviation -- where 0-9 and a-z/A-Z are counting as a letter, but the dot (as it's so tiny in many proportional fonts) would not, and would be ignored in terms of the letter limit?

This question is related to this helpful thread, but it's not the same; for instance, where that function would turn e.g. "123456 -> 1.23k" ("123.5k" being 5 letters) I am looking for something that does "123456 -> 0.1m" ("0[.]1m" being 3 letters). For instance, this would be the output of hoped function (left original, right ideal return value):

```<code>0                      "0"
12                    "12"
123                  "123"
1234                "1.2k"
12345                "12k"
123456              "0.1m"
1234567             "1.2m"
12345678             "12m"
123456789           "0.1b"
1234567899          "1.2b"
12345678999          "12b"
</code>```

Thanks!

Update: Thanks! An answer is in and works per the requirements when the following amendments are made:

```<code>function abbreviateNumber(value) {
    var newValue = value;
    if (value >= 1000) {
        var suffixes = ["", "k", "m", "b","t"];
        var suffixNum = Math.floor( (""+value).length/3 );
        var shortValue = '';
        for (var precision = 2; precision >= 1; precision--) {
            shortValue = parseFloat( (suffixNum != 0 ? (value / Math.pow(1000,suffixNum) ) : value).toPrecision(precision));
            var dotLessShortValue = (shortValue + '').replace(/[^a-zA-Z 0-9]+/g,'');
            if (dotLessShortValue.length <= 2) { break; }
        }
        if (shortValue % 1 != 0)  shortValue = shortValue.toFixed(1);
        newValue = shortValue+suffixes[suffixNum];
    }
    return newValue;
}
</code>```

答:
Intl is the Javascript standard 'package' for implemented internationalized behaviours. Intl.NumberFormatter is specifically the localized number formatter. So this code actually respects your locally configured thousands and decimal separators.

```<code>intlFormat(num) {
    return new Intl.NumberFormat().format(Math.round(num*10)/10);
}

abbreviateNumber(value) {
    let num = Math.floor(value);
    if(num >= 1000000000)
        return this.intlFormat(num/1000000000)+'B';
    if(num >= 1000000)
        return this.intlFormat(num/1000000)+'M';
    if(num >= 1000)
        return this.intlFormat(num/1000)+'k';
    return this.intlFormat(num);
}
</code>```

abbreviateNumber(999999999999)    // Gives 999B

Related question: Abbreviate a localized number in JavaScript for thousands (1k) and millions (1m)

Body:
In JavaScript, how would one write a function that converts a given [edit: positive integer] number (below 100 billion) into a 3-letter abbreviation -- where 0-9 and a-z/A-Z are counting as a letter, but the dot (as it's so tiny in many proportional fonts) would not, and would be ignored in terms of the letter limit?

This question is related to this helpful thread, but it's not the same; for instance, where that function would turn e.g. "123456 -> 1.23k" ("123.5k" being 5 letters) I am looking for something that does "123456 -> 0.1m" ("0[.]1m" being 3 letters). For instance, this would be the output of hoped function (left original, right ideal return value):

0                      "0"
12                    "12"
123                  "123"
1234                "1.2k"
12345                "12k"
123456              "0.1m"
1234567             "1.2m"
12345678             "12m"
123456789           "0.1b"
1234567899          "1.2b"
12345678999          "12b"

Thanks!

Update: Thanks! An answer is in and works per the requirements when the following amendments are made:

function abbreviateNumber(value) {
    var newValue = value;
    if (value >= 1000) {
        var suffixes = ["", "k", "m", "b","t"];
        var suffixNum = Math.floor( (""+value).length/3 );
        var shortValue = '';
        for (var precision = 2; precision >= 1; precision--) {
            shortValue = parseFloat( (suffixNum != 0 ? (value / Math.pow(1000,suffixNum) ) : value).toPrecision(precision));
            var dotLessShortValue = (shortValue + '').replace(/[^a-zA-Z 0-9]+/g,'');
            if (dotLessShortValue.length <= 2) { break; }
        }
        if (shortValue % 1 != 0)  shortValue = shortValue.toFixed(1);
        newValue = shortValue+suffixes[suffixNum];
    }
    return newValue;
}

Body:
Intl is the Javascript standard 'package' for implemented internationalized behaviours. Intl.NumberFormatter is specifically the localized number formatter. So this code actually respects your locally configured thousands and decimal separators.

intlFormat(num) {
    return new Intl.NumberFormat().format(Math.round(num*10)/10);
}

abbreviateNumber(value) {
    let num = Math.floor(value);
    if(num >= 1000000000)
        return this.intlFormat(num/1000000000)+'B';
    if(num >= 1000000)
        return this.intlFormat(num/1000000)+'M';
    if(num >= 1000)
        return this.intlFormat(num/1000)+'k';
    return this.intlFormat(num);
}

abbreviateNumber(999999999999)    // Gives 999B

Related question: Abbreviate a localized number in JavaScript for thousands (1k) and millions (1m)


问:
Git: "+refs/heads/<branch>:refs/remotes/origin/<branch>"
Jenkins Git plugin generated the below command in console output based on my ref spec

What's the difference between below 2 commands? Their output looks little different. I have given their output below:

Command 1:

git fetch --no-tags --progress repo.git +refs/heads/qa:refs/remotes/origin/qa --depth=1

Output:

```<code>From <repo>
 * [new branch]      qa         -> origin/qa
</code>```

Command 2:

git fetch --no-tags --progress repo.git refs/heads/qa --depth=1

Output:

```<code>From <repo>
 * branch            qa         -> FETCH_HEAD
</code>```

What does FETCH_HEAD here mean?

I believe refs/heads/qa is local working copy of 'qa' branch and refs/remotes/origin/qa is remote 'qa' branch. But, what does this convention imply?

+refs/heads/qa:refs/remotes/origin/qa

答:
The syntax with two references separated by a colon, with the whole thing optionally prefixed with a plus sign, is a refspec.  Refspecs may also omit the colon and contain only one reference, in which case the plus sign may (depending on the use of this degenerate refspec) be functionless.  For more on refspecs, see, e.g., What is the difference between these `git fetch` syntaxes?

Taking the questions themselves in reverse order, though:

Item 3 is just plain wrong.  The name refs/heads/qa is the branch name; it's simply spelled out in full, as it should be in a refspec.  It's not a "working copy" at all: it's just a name.  Git uses names—references—to map from human-readable strings like master and qa to Git's internal hash IDs.  The word reference is a generalization of branches, tags, remote-tracking branches, and other such names.

Similarly, refs/remotes/origin/qa is the fully-spelled-out reference that is your remote-tracking branch normally shortened to origin/qa.  Just as with the branch whose full name is refs/heads/qa, Git uses this name to map from the human-readable string origin/qa to hash ID.

The name FETCH_HEAD refers to a file in the .git directory, .git/FETCH_HEAD.  When you use the very ancient form of git fetch, from before the invention of remote-tracking branches, Git has to store all the fetched name-and-ID values somewhere.  That "somewhere" is this file.  Other Git commands can then fish out each name-and-ID pair.

Back in the Dim Time, before 2007 or so, this was the only way you could use git fetch.  Remote-tracking branch names were invented because it is nice to have your own Git remember these names for much longer periods—each new git fetch overwrites old data1 unless you use -a—and in ways that are easier to use.

For item 1 (what's the difference), see the other answer.

1If you only ever fetch from one remote (e.g., from origin), and you always fetch all names, this is actually perfectly reasonable behavior: overwrite the old, stale information with new, correct information.  It breaks down when you fetch from more than one remote and/or when you fetch items piecemeal.  Remote-tracking branch names, despite their not-so-great-in-retrospect name, are really quite an improvement.

Body:
Jenkins Git plugin generated the below command in console output based on my ref spec

What's the difference between below 2 commands? Their output looks little different. I have given their output below:

Command 1:

git fetch --no-tags --progress repo.git +refs/heads/qa:refs/remotes/origin/qa --depth=1

Output:

From <repo>
 * [new branch]      qa         -> origin/qa

Command 2:

git fetch --no-tags --progress repo.git refs/heads/qa --depth=1

Output:

From <repo>
 * branch            qa         -> FETCH_HEAD

What does FETCH_HEAD here mean?

I believe refs/heads/qa is local working copy of 'qa' branch and refs/remotes/origin/qa is remote 'qa' branch. But, what does this convention imply?

+refs/heads/qa:refs/remotes/origin/qa