问:
InputSimulator works while debugging but not when program is built
In my project im using inputsimulator and it works great when visual studio is ran as an administrator, but when i build it into a .exe it doesn't work even when i run it as administrator. here's my code

```<code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    AutoSaveTimer.Enabled = True

    Try
        System.Threading.Thread.Sleep(50)
        GameConnection.SendKeyTo(Keys.OemSemicolon)
        System.Threading.Thread.Sleep(2000)
        GameConnection.SendKeyTo(Keys.K)
        System.Threading.Thread.Sleep(50)
        GameConnection.SendKeyTo(Keys.Enter)

    Catch AutoSaveExeption As GameException
        If AutoSaveExeption.GameErrorCode = GameError.GAME_ERR_SENDMSG Then
            ' Send message error - connection to Game lost.
            '
            MessageBox.Show("cant make a connection.... can't autosave sadly", AppTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            SimConnectionBar.BackColor = Color.Red
        End If
    End Try
End Sub
</code>```

it does send focus to the window i specify but it doesn't send the keystrokes

答:
Try using SetForegroundWindow before sending any input to ensure your game does in fact have focus.The call to SetForegroundWindow should be made in your method just before sending the input.</p>

```<code>    <DllImport("user32.dll")> _
Public Shared Function SetForegroundWindow(hWnd As IntPtr) As Boolean
End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click `
AutoSaveTimer.Enabled = True
Try
    'Find the handle to the game. This can do it by searching for the process.
        Dim p As System.Diagnostics.Process() = System.Diagnostics.Process.GetProcessesByName("notepad")
        'search for process notepad
        If p.Length > 0 Then
            'check if window was found
            'bring notepad to foreground
            SetForegroundWindow(p(0).MainWindowHandle)
        End If

        System.Threading.Thread.Sleep(50)
        GameConnection.SendKeyTo(Keys.OemSemicolon)
        System.Threading.Thread.Sleep(2000)
        GameConnection.SendKeyTo(Keys.K)
        System.Threading.Thread.Sleep(50)
        GameConnection.SendKeyTo(Keys.Enter)

    Catch AutoSaveExeption As GameException
        If AutoSaveExeption.GameErrorCode = GameError.GAME_ERR_SENDMSG Then
            ' Send message error - connection to Game lost.
            '
            MessageBox.Show("cant make a connection.... can't autosave sadly", AppTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            SimConnectionBar.BackColor = Color.Red
        End If
    End Try
end sub
</code>```

Body:
In my project im using inputsimulator and it works great when visual studio is ran as an administrator, but when i build it into a .exe it doesn't work even when i run it as administrator. here's my code

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    AutoSaveTimer.Enabled = True

    Try
        System.Threading.Thread.Sleep(50)
        GameConnection.SendKeyTo(Keys.OemSemicolon)
        System.Threading.Thread.Sleep(2000)
        GameConnection.SendKeyTo(Keys.K)
        System.Threading.Thread.Sleep(50)
        GameConnection.SendKeyTo(Keys.Enter)

    Catch AutoSaveExeption As GameException
        If AutoSaveExeption.GameErrorCode = GameError.GAME_ERR_SENDMSG Then
            ' Send message error - connection to Game lost.
            '
            MessageBox.Show("cant make a connection.... can't autosave sadly", AppTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            SimConnectionBar.BackColor = Color.Red
        End If
    End Try
End Sub

it does send focus to the window i specify but it doesn't send the keystrokes

Body:
Try using SetForegroundWindow before sending any input to ensure your game does in fact have focus.The call to SetForegroundWindow should be made in your method just before sending the input.

    <DllImport("user32.dll")> _
Public Shared Function SetForegroundWindow(hWnd As IntPtr) As Boolean
End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click `
AutoSaveTimer.Enabled = True
Try
    'Find the handle to the game. This can do it by searching for the process.
        Dim p As System.Diagnostics.Process() = System.Diagnostics.Process.GetProcessesByName("notepad")
        'search for process notepad
        If p.Length > 0 Then
            'check if window was found
            'bring notepad to foreground
            SetForegroundWindow(p(0).MainWindowHandle)
        End If

        System.Threading.Thread.Sleep(50)
        GameConnection.SendKeyTo(Keys.OemSemicolon)
        System.Threading.Thread.Sleep(2000)
        GameConnection.SendKeyTo(Keys.K)
        System.Threading.Thread.Sleep(50)
        GameConnection.SendKeyTo(Keys.Enter)

    Catch AutoSaveExeption As GameException
        If AutoSaveExeption.GameErrorCode = GameError.GAME_ERR_SENDMSG Then
            ' Send message error - connection to Game lost.
            '
            MessageBox.Show("cant make a connection.... can't autosave sadly", AppTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            SimConnectionBar.BackColor = Color.Red
        End If
    End Try
end sub


来源: stackexchange

问:
Request parameters in Freemarker on Spring 2.5
I am trying to get request parameters on freemarker page. But I can't figure out how to setup implicit variables like RequestParameters or so.

Here is a thread http://forum.springsource.org/showthread.php?t=32846 but I don't where he setup that RequestParameters object.

The only thing I found in docs (more in source code), that it is FreemarkerServlet which can place that variable. But I don't have it in my application. All configurations are done via Spring, i.e. View Resolver.

Can anybody help me?

答:
Spring boot 1.5 based in anotation into class will be something like:</p>

```<code>package com.openkm.config;

import java.io.IOException;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

import freemarker.cache.TemplateLoader;
import freemarker.template.TemplateException;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("/static/").setCachePeriod(604800); // One week
    }

    @Bean(name = "freeMarkerViewResolver")
    public FreeMarkerViewResolver getFreeMarkerViewResolver() {
        FreeMarkerViewResolver viewResolver = new FreeMarkerViewResolver();
        viewResolver.setExposeSpringMacroHelpers(true);
        viewResolver.setExposeRequestAttributes(true);
        viewResolver.setExposeSessionAttributes(true);
        viewResolver.setPrefix("/WEB-INF/ftl/");
        viewResolver.setSuffix(".ftl");
        viewResolver.setOrder(0);
        viewResolver.setContentType("text/html; charset=UTF-8");
        viewResolver.setCache(false);
        viewResolver.setRequestContextAttribute("request");
        return viewResolver;
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Spring boot 1.5 based in anotation into class will be something like:

package com.openkm.config;

import java.io.IOException;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

import freemarker.cache.TemplateLoader;
import freemarker.template.TemplateException;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("/static/").setCachePeriod(604800); // One week
    }

    @Bean(name = "freeMarkerViewResolver")
    public FreeMarkerViewResolver getFreeMarkerViewResolver() {
        FreeMarkerViewResolver viewResolver = new FreeMarkerViewResolver();
        viewResolver.setExposeSpringMacroHelpers(true);
        viewResolver.setExposeRequestAttributes(true);
        viewResolver.setExposeSessionAttributes(true);
        viewResolver.setPrefix("/WEB-INF/ftl/");
        viewResolver.setSuffix(".ftl");
        viewResolver.setOrder(0);
        viewResolver.setContentType("text/html; charset=UTF-8");
        viewResolver.setCache(false);
        viewResolver.setRequestContextAttribute("request");
        return viewResolver;
    }
}

ContentLicense: CC BY-SA 3.0


问:
Scala Doubles, and Precision
Is there a function that can truncate or round a Double?  At one point in my code I would like a number like: 1.23456789 to be rounded to 1.23

答:
A bit strange but nice. I use String and not BigDecimal</p>

```<code>def round(x: Double)(p: Int): Double = {
    var A = x.toString().split('.')
    (A(0) + "." + A(1).substring(0, if (p > A(1).length()) A(1).length() else p)).toDouble
}
</code>```

Title: Scala Doubles, and Precision

Body:
A bit strange but nice. I use String and not BigDecimal

def round(x: Double)(p: Int): Double = {
    var A = x.toString().split('.')
    (A(0) + "." + A(1).substring(0, if (p > A(1).length()) A(1).length() else p)).toDouble
}


问:
Concatenate CSV files with pandas
l have csv files to concatenate. l have three files l want to concatenate. The number of columns is the same so the desired output will have also the same columns

file1.csv

```<code>id                                       ocr    raw_value   manual_raw_value
2a909d6e-5eb2-49a1-b6e8-171bf01dafdc    ABBYY   7,20         7,20
0c93bc55-2c42-4afb-8428-c12736b0a86e    ABBYY   44            44
12973bd0-72c7-4333-ac8d-ab0f18e33cb0    OMNIPAGE    4578     4578
2ccbeb11-ed0d-49a3-a321-a1c583764e3d    ABBYY        1             1
f78636d7-c22f-4a85-bb34-fd8757352ec5    ABBYY   8040.56     8040.56
2d1c5869-1f87-4b47-bbf4-c2f31b122c0b    OMNIPAGE    6        6
2d914f73-39d9-4108-8467-4d7a28933aa6    OMNIPAGE    0         0
</code>```

File2

```<code>id                                        ocr   raw_value   manual_raw_value
bfa6c9f1-89c0-486b-a85c-a97a370a92c4    OMNIPAGE    35470       35470
213e1e1e-29df-44c2-acee-79f7fefa7ba9    OMNIPAGE    Echeance    Ech√©ance
1ebecadc-056b-41c8-8426-446fff6bad71    OMNIPAGE    Etoblissemenls  Etablissements
35c1b736-f504-487d-a531-3b133045139e    OMNIPAGE    :               :
009ee382-c1f2-4194-92e1-9b9fffd387d2    OMNIPAGE    1087         1087
35dd36a6-7c9c-4f81-b3f7-db6533bd159f    OMNIPAGE    1              1
218f6860-b6aa-4bba-b64a-c2cc0b40812b    OMNIPAGE    HT               HT
</code>```

File3

```<code>id                                        ocr   raw_value   manual_raw_value
4a82a357-99e7-49e6-85b6-b2f6a27b8d5f    OMNIPAGE    Terms   Terms
8b549fef-0cda-4af5-8239-35153c33ffbc    OMNIPAGE    price   price
52ffe66a-b1ab-4b22-9b26-c298d53c951c    OMNIPAGE    Renseignements
 Renseignements
507a0d96-9481-4b3f-8c35-f16588bedc0b    OMNIPAGE    pour    pour
52e171dc-8d22-4162-b748-692b2fc11659    OMNIPAGE    Client  Client
c40a7e9f-1ec4-4cac-87e8-02ed0f335fe9    OMNIPAGE    5   5
4a936ed7-c082-4f46-9fa1-761a1525e2df    OMNIPAGE    SAS SAS
4b78130e-b099-400c-b7bf-6470e0519783    OMNIPAGE    des des
4d5c6297-1c79-42f9-b4ea-929a9abfb3f7    OMNIPAGE    431 431
829d8bf5-b251-4bb1-82d8-0e912ab64e8e    OMNIPAGE    59  59
</code>```

Desired output

```<code>         id                                      ocr    raw_value   manual_raw_value

        2a909d6e-5eb2-49a1-b6e8-171bf01dafdc    ABBYY   7,20         7,20
        0c93bc55-2c42-4afb-8428-c12736b0a86e    ABBYY   44            44
        12973bd0-72c7-4333-ac8d-ab0f18e33cb0    OMNIPAGE    4578     4578
        2ccbeb11-ed0d-49a3-a321-a1c583764e3d    ABBYY        1             1
        f78636d7-c22f-4a85-bb34-fd8757352ec5    ABBYY   8040.56     8040.56
        2d1c5869-1f87-4b47-bbf4-c2f31b122c0b    OMNIPAGE    6        6
        2d914f73-39d9-4108-8467-4d7a28933aa6    OMNIPAGE    0         0

        bfa6c9f1-89c0-486b-a85c-a97a370a92c4    OMNIPAGE    35470       35470
        213e1e1e-29df-44c2-acee-79f7fefa7ba9    OMNIPAGE    Echeance    Ech√©ance
        1ebecadc-056b-41c8-8426-446fff6bad71    OMNIPAGE    Etoblissemenls  Etablissements
        35c1b736-f504-487d-a531-3b133045139e    OMNIPAGE    :               :
        009ee382-c1f2-4194-92e1-9b9fffd387d2    OMNIPAGE    1087         1087
        35dd36a6-7c9c-4f81-b3f7-db6533bd159f    OMNIPAGE    1              1
        218f6860-b6aa-4bba-b64a-c2cc0b40812b    OMNIPAGE    HT               HT
        4a82a357-99e7-49e6-85b6-b2f6a27b8d5f    OMNIPAGE    Terms   Terms
        8b549fef-0cda-4af5-8239-35153c33ffbc    OMNIPAGE    price   price
        52ffe66a-b1ab-4b22-9b26-c298d53c951c    OMNIPAGE    Renseignements
         Renseignements
        507a0d96-9481-4b3f-8c35-f16588bedc0b    OMNIPAGE    pour    pour
        52e171dc-8d22-4162-b748-692b2fc11659    OMNIPAGE    Client  Client
        c40a7e9f-1ec4-4cac-87e8-02ed0f335fe9    OMNIPAGE    5   5
        4a936ed7-c082-4f46-9fa1-761a1525e2df    OMNIPAGE    SAS SAS
        4b78130e-b099-400c-b7bf-6470e0519783    OMNIPAGE    des des
        4d5c6297-1c79-42f9-b4ea-929a9abfb3f7    OMNIPAGE    431 431
        829d8bf5-b251-4bb1-82d8-0e912ab64e8e    OMNIPAGE    59  59
</code>```

Here is my code

```<code>import os
import glob
import pandas

def concatenate(indir,outputfile):
    os.chdir(indir)
    fileList=glob.glob("*.csv")
    dfList=[]
    colnames=["id","ocr","raw_value","manual_raw_value"]
    for filename in fileList:
        print(filename)
        df=pandas.read_csv(input,header=None)
        dfList.append(df)
    concatenateDF=pandas.concat(dfList,axis=0)
    concatenateDF.columns=colnames
    concatenateDF.to_save(outputfile,index=None)

if __name__ == "__main__":
    input="/files"
    output="files/concatenated.csv"
    concatenate(input,output)
</code>```

l get the following error :

```<code>Traceback (most recent call last):
  File "/home/ahmed/crnn/concatenate_files.py", line 21, in <module>
    concatenate(input,output)
  File "/home/ahmed/crnn/concatenate_files.py", line 12, in concatenate
    df=pandas.read_csv(input,header=None)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 646, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 389, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 730, in __init__
    self._make_engine(self.engine)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 923, in _make_engine
    self._engine = CParserWrapper(self.f, **self.options)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 1390, in __init__
words2.csv
    self._reader = _parser.TextReader(src, **kwds)
  File "pandas/parser.pyx", line 538, in pandas.parser.TextReader.__cinit__ (pandas/parser.c:6171)
pandas.io.common.EmptyDataError: No columns to parse from file
</code>```

What's wrong with my code ?

How can l solve that?

Thank you

答:
Your csv has uneven spacing. This can be handled easily. When reading in your data, set delim_whitespace=True.

```<code>In [1335]: list_ = []
      ...: for file in glob.glob('*.csv'):
      ...:     df = pd.read_csv(file, index_col=None, header=0, delim_whitespace=True)
      ...:     print('Size:', len(df))
      ...:     list_.append(df)
      ...:
Size: 7
Size: 7
Size: 10
</code>```

The size of each dataframe has been printed. Next, we'll concatenate them as you have done and then assign columns at the end:

```<code>In [1336]: df = pd.concat(list_, axis=0)

In [1337]: df.columns = ["id", "ocr", "raw_value", "manual_raw_value"]

In [1338]: df.head()
Out[1338]:
                                     id       ocr raw_value manual_raw_value
0  2a909d6e-5eb2-49a1-b6e8-171bf01dafdc     ABBYY      7,20             7,20
1  0c93bc55-2c42-4afb-8428-c12736b0a86e     ABBYY        44               44
2  12973bd0-72c7-4333-ac8d-ab0f18e33cb0  OMNIPAGE      4578             4578
3  2ccbeb11-ed0d-49a3-a321-a1c583764e3d     ABBYY         1                1
4  f78636d7-c22f-4a85-bb34-fd8757352ec5     ABBYY   8040.56          8040.56
</code>```

Confirm they have been concatenated properly:

```<code>In [1339]: len(df)
Out[1339]: 24
</code>```

24 = 7 + 7 + 10, so you're good to go.

Title: Concatenate CSV files with pandas

Body:
l have csv files to concatenate. l have three files l want to concatenate. The number of columns is the same so the desired output will have also the same columns

file1.csv

id                                       ocr    raw_value   manual_raw_value
2a909d6e-5eb2-49a1-b6e8-171bf01dafdc    ABBYY   7,20         7,20
0c93bc55-2c42-4afb-8428-c12736b0a86e    ABBYY   44            44
12973bd0-72c7-4333-ac8d-ab0f18e33cb0    OMNIPAGE    4578     4578
2ccbeb11-ed0d-49a3-a321-a1c583764e3d    ABBYY        1             1
f78636d7-c22f-4a85-bb34-fd8757352ec5    ABBYY   8040.56     8040.56
2d1c5869-1f87-4b47-bbf4-c2f31b122c0b    OMNIPAGE    6        6
2d914f73-39d9-4108-8467-4d7a28933aa6    OMNIPAGE    0         0

File2

id                                        ocr   raw_value   manual_raw_value
bfa6c9f1-89c0-486b-a85c-a97a370a92c4    OMNIPAGE    35470       35470
213e1e1e-29df-44c2-acee-79f7fefa7ba9    OMNIPAGE    Echeance    Ech√©ance
1ebecadc-056b-41c8-8426-446fff6bad71    OMNIPAGE    Etoblissemenls  Etablissements
35c1b736-f504-487d-a531-3b133045139e    OMNIPAGE    :               :
009ee382-c1f2-4194-92e1-9b9fffd387d2    OMNIPAGE    1087         1087
35dd36a6-7c9c-4f81-b3f7-db6533bd159f    OMNIPAGE    1              1
218f6860-b6aa-4bba-b64a-c2cc0b40812b    OMNIPAGE    HT               HT

File3

id                                        ocr   raw_value   manual_raw_value
4a82a357-99e7-49e6-85b6-b2f6a27b8d5f    OMNIPAGE    Terms   Terms
8b549fef-0cda-4af5-8239-35153c33ffbc    OMNIPAGE    price   price
52ffe66a-b1ab-4b22-9b26-c298d53c951c    OMNIPAGE    Renseignements
 Renseignements
507a0d96-9481-4b3f-8c35-f16588bedc0b    OMNIPAGE    pour    pour
52e171dc-8d22-4162-b748-692b2fc11659    OMNIPAGE    Client  Client
c40a7e9f-1ec4-4cac-87e8-02ed0f335fe9    OMNIPAGE    5   5
4a936ed7-c082-4f46-9fa1-761a1525e2df    OMNIPAGE    SAS SAS
4b78130e-b099-400c-b7bf-6470e0519783    OMNIPAGE    des des
4d5c6297-1c79-42f9-b4ea-929a9abfb3f7    OMNIPAGE    431 431
829d8bf5-b251-4bb1-82d8-0e912ab64e8e    OMNIPAGE    59  59

Desired output

         id                                      ocr    raw_value   manual_raw_value

        2a909d6e-5eb2-49a1-b6e8-171bf01dafdc    ABBYY   7,20         7,20
        0c93bc55-2c42-4afb-8428-c12736b0a86e    ABBYY   44            44
        12973bd0-72c7-4333-ac8d-ab0f18e33cb0    OMNIPAGE    4578     4578
        2ccbeb11-ed0d-49a3-a321-a1c583764e3d    ABBYY        1             1
        f78636d7-c22f-4a85-bb34-fd8757352ec5    ABBYY   8040.56     8040.56
        2d1c5869-1f87-4b47-bbf4-c2f31b122c0b    OMNIPAGE    6        6
        2d914f73-39d9-4108-8467-4d7a28933aa6    OMNIPAGE    0         0

        bfa6c9f1-89c0-486b-a85c-a97a370a92c4    OMNIPAGE    35470       35470
        213e1e1e-29df-44c2-acee-79f7fefa7ba9    OMNIPAGE    Echeance    Ech√©ance
        1ebecadc-056b-41c8-8426-446fff6bad71    OMNIPAGE    Etoblissemenls  Etablissements
        35c1b736-f504-487d-a531-3b133045139e    OMNIPAGE    :               :
        009ee382-c1f2-4194-92e1-9b9fffd387d2    OMNIPAGE    1087         1087
        35dd36a6-7c9c-4f81-b3f7-db6533bd159f    OMNIPAGE    1              1
        218f6860-b6aa-4bba-b64a-c2cc0b40812b    OMNIPAGE    HT               HT
        4a82a357-99e7-49e6-85b6-b2f6a27b8d5f    OMNIPAGE    Terms   Terms
        8b549fef-0cda-4af5-8239-35153c33ffbc    OMNIPAGE    price   price
        52ffe66a-b1ab-4b22-9b26-c298d53c951c    OMNIPAGE    Renseignements
         Renseignements
        507a0d96-9481-4b3f-8c35-f16588bedc0b    OMNIPAGE    pour    pour
        52e171dc-8d22-4162-b748-692b2fc11659    OMNIPAGE    Client  Client
        c40a7e9f-1ec4-4cac-87e8-02ed0f335fe9    OMNIPAGE    5   5
        4a936ed7-c082-4f46-9fa1-761a1525e2df    OMNIPAGE    SAS SAS
        4b78130e-b099-400c-b7bf-6470e0519783    OMNIPAGE    des des
        4d5c6297-1c79-42f9-b4ea-929a9abfb3f7    OMNIPAGE    431 431
        829d8bf5-b251-4bb1-82d8-0e912ab64e8e    OMNIPAGE    59  59

Here is my code

import os
import glob
import pandas

def concatenate(indir,outputfile):
    os.chdir(indir)
    fileList=glob.glob("*.csv")
    dfList=[]
    colnames=["id","ocr","raw_value","manual_raw_value"]
    for filename in fileList:
        print(filename)
        df=pandas.read_csv(input,header=None)
        dfList.append(df)
    concatenateDF=pandas.concat(dfList,axis=0)
    concatenateDF.columns=colnames
    concatenateDF.to_save(outputfile,index=None)

if __name__ == "__main__":
    input="/files"
    output="files/concatenated.csv"
    concatenate(input,output)

l get the following error :

Traceback (most recent call last):
  File "/home/ahmed/crnn/concatenate_files.py", line 21, in <module>
    concatenate(input,output)
  File "/home/ahmed/crnn/concatenate_files.py", line 12, in concatenate
    df=pandas.read_csv(input,header=None)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 646, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 389, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 730, in __init__
    self._make_engine(self.engine)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 923, in _make_engine
    self._engine = CParserWrapper(self.f, **self.options)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 1390, in __init__
words2.csv
    self._reader = _parser.TextReader(src, **kwds)
  File "pandas/parser.pyx", line 538, in pandas.parser.TextReader.__cinit__ (pandas/parser.c:6171)
pandas.io.common.EmptyDataError: No columns to parse from file

What's wrong with my code ?

How can l solve that?

Thank you

Body:
Your csv has uneven spacing. This can be handled easily. When reading in your data, set delim_whitespace=True.

In [1335]: list_ = []
      ...: for file in glob.glob('*.csv'):
      ...:     df = pd.read_csv(file, index_col=None, header=0, delim_whitespace=True)
      ...:     print('Size:', len(df))
      ...:     list_.append(df)
      ...:
Size: 7
Size: 7
Size: 10

The size of each dataframe has been printed. Next, we'll concatenate them as you have done and then assign columns at the end:

In [1336]: df = pd.concat(list_, axis=0)

In [1337]: df.columns = ["id", "ocr", "raw_value", "manual_raw_value"]

In [1338]: df.head()
Out[1338]:
                                     id       ocr raw_value manual_raw_value
0  2a909d6e-5eb2-49a1-b6e8-171bf01dafdc     ABBYY      7,20             7,20
1  0c93bc55-2c42-4afb-8428-c12736b0a86e     ABBYY        44               44
2  12973bd0-72c7-4333-ac8d-ab0f18e33cb0  OMNIPAGE      4578             4578
3  2ccbeb11-ed0d-49a3-a321-a1c583764e3d     ABBYY         1                1
4  f78636d7-c22f-4a85-bb34-fd8757352ec5     ABBYY   8040.56          8040.56

Confirm they have been concatenated properly:

In [1339]: len(df)
Out[1339]: 24

24 = 7 + 7 + 10, so you're good to go.


问:
Sieve of Eratosthenes problem: handling really big numbers
I'm solving Sphere's Online Judge Prime Generator using the Sieve of Eratosthenes.

My code works for the test case provided. But.. as the problem clearly states:

The input begins with the number t of
  test cases in a single line (t<=10).
  In each of the next t lines there are
  two numbers m and n (1 <= m <= n <=
  1000000000, n-m<=100000) separated by
  a space.

I know that the method Integer.parseInt() throws an Exception when handling really big numbers and the online judge was indicating that an Exception was being thrown, so I changed every case of parseInt to parseLong in my code.

Well, the thing is running fine on Netbeans 6.5 with small values for m and n.

```<code>package sphere;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main{

public static void runEratosthenesSieve(long lowerBound, long upperBound) {

      long upperBoundSquareRoot = (long) Math.sqrt(upperBound);

      boolean[] isComposite = new boolean[(int)upperBound + 1];

      for (int m = 2 /*int m = lowerBound*/; m <= upperBoundSquareRoot; m++) {

            if (!isComposite[m]) {

                if (m>=lowerBound) {System.out.println(m);}

                  for (int k = m * m; k <= upperBound; k += m)

                        isComposite[k] = true;

            }

      }

      for (int m = (int)upperBoundSquareRoot; m <= upperBound; m++)

            if (!isComposite[m])

                 if (m>=lowerBound){ System.out.println(m);}

}

public static void main(String args[]) throws java.lang.Exception{

       BufferedReader r = new BufferedReader(new InputStreamReader(System.in));

       String l = r.readLine();

       int testCases = Integer.parseInt(l);

       for (int i =0; i<testCases; i++){
       String s =r.readLine();

       String []splitted=s.split(" ");

       long lowerBound = Long.parseLong (splitted[0]);
       long upperBound = Long.parseLong(splitted[1]);

       runEratosthenesSieve (lowerBound,upperBound);

       System.out.println("");
       }
}

}
</code>```

Input+Output:

```<code>run:
2
1 10
2
3
3
5
7

3 5
3
5

BUILD SUCCESSFUL (total time: 11 seconds)
</code>```

But JCreator LE is saying this:

```<code>2
1 10
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Long.parseLong(Long.java:424)
    at java.lang.Long.parseLong(Long.java:461)
    at sphere.Main.main(Main.java:51)

Process completed.
</code>```

Here I don't have an integer overflow, but why would jcreator complain?

Considering the borderline testcase, the program implodes on Netbeans too:

```<code>run:
2
999900000 1000000000
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        at sphere.Main.runEratosthenesSieve(Main.java:13)
        at sphere.Main.main(Main.java:55)
Java Result: 1
</code>```

How can I deal with those huge-ish integers of the problem statement?

Edit: By suggestion I have changed the boolean array for a BitSet, but I'm still getting an OutOFMemoryError:

```<code>package sphere;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.BitSet;

public class Main{

public static void runEratosthenesSieve(long lowerBound, long upperBound) {

      long upperBoundSquareRoot = (long) Math.sqrt(upperBound);

      //boolean[] isComposite = new boolean[(int)upperBound + 1];

      BitSet isComposite = new BitSet((int)upperBound+1);

      for (int m = 2 /*int m = lowerBound*/; m <= upperBoundSquareRoot; m++) {

            if (!isComposite.get(m)) {

                if (m>=lowerBound) {System.out.println(m);}

                  for (int k = m * m; k <= upperBound; k += m)

                        isComposite.set(m);

            }

      }

      for (int m = (int)upperBoundSquareRoot; m <= upperBound; m++)

            if (!isComposite.get(m))

                 if (m>=lowerBound){ System.out.println(m);}

}

public static void main(String args[]) throws java.lang.Exception{

       BufferedReader r = new BufferedReader(new InputStreamReader(System.in));

       String l = r.readLine();

       int testCases = Integer.parseInt(l);

       for (int i =0; i<testCases; i++){
       String s =r.readLine();

       String []splitted=s.split(" ");

       long lowerBound = Long.parseLong (splitted[0]);
       long upperBound = Long.parseLong(splitted[1]);

       runEratosthenesSieve (lowerBound,upperBound);

       System.out.println("");
       }
}

}
</code>```

Input-Output:

```<code>run:
1
999900000 1000000000
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        at java.util.BitSet.initWords(BitSet.java:144)
        at java.util.BitSet.<init>(BitSet.java:139)
        at sphere.Main.runEratosthenesSieve(Main.java:16)
        at sphere.Main.main(Main.java:58)
Java Result: 1
BUILD SUCCESSFUL (total time: 14 seconds)
</code>```

答:
I had faced similar issues due the limitations on Java Heap Size. Instead of using high memory Integer, shifting to boolean solved the problem.
Find the attached code:</p>

```<code>public ArrayList<Integer> sieve(int A) {
    boolean prime [] = new boolean[A + 1];
    Arrays.fill(prime, true);
    prime[0] = prime[1] = false;

    for (int i = 2; i <= A; i++) {
        if (!prime[i])
            continue;

        for (long j = 1L * i * i; j <= (long) A; j += i)
            prime[(int) j] = false;
    }

    ArrayList<Integer> res = new ArrayList<>();

    for (int i = 0; i <= A; i++) {
        if (prime[i])
            res.add(i);
    }

    return res;
}
</code>```

Body:
I'm solving Sphere's Online Judge Prime Generator using the Sieve of Eratosthenes.

My code works for the test case provided. But.. as the problem clearly states:

The input begins with the number t of
  test cases in a single line (t<=10).
  In each of the next t lines there are
  two numbers m and n (1 <= m <= n <=
  1000000000, n-m<=100000) separated by
  a space.

I know that the method Integer.parseInt() throws an Exception when handling really big numbers and the online judge was indicating that an Exception was being thrown, so I changed every case of parseInt to parseLong in my code.

Well, the thing is running fine on Netbeans 6.5 with small values for m and n.

package sphere;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main{

public static void runEratosthenesSieve(long lowerBound, long upperBound) {

      long upperBoundSquareRoot = (long) Math.sqrt(upperBound);

      boolean[] isComposite = new boolean[(int)upperBound + 1];

      for (int m = 2 /*int m = lowerBound*/; m <= upperBoundSquareRoot; m++) {

            if (!isComposite[m]) {

                if (m>=lowerBound) {System.out.println(m);}

                  for (int k = m * m; k <= upperBound; k += m)

                        isComposite[k] = true;

            }

      }

      for (int m = (int)upperBoundSquareRoot; m <= upperBound; m++)

            if (!isComposite[m])

                 if (m>=lowerBound){ System.out.println(m);}

}

public static void main(String args[]) throws java.lang.Exception{

       BufferedReader r = new BufferedReader(new InputStreamReader(System.in));

       String l = r.readLine();

       int testCases = Integer.parseInt(l);

       for (int i =0; i<testCases; i++){
       String s =r.readLine();

       String []splitted=s.split(" ");

       long lowerBound = Long.parseLong (splitted[0]);
       long upperBound = Long.parseLong(splitted[1]);

       runEratosthenesSieve (lowerBound,upperBound);

       System.out.println("");
       }
}

}

Input+Output:

run:
2
1 10
2
3
3
5
7

3 5
3
5

BUILD SUCCESSFUL (total time: 11 seconds)

But JCreator LE is saying this:

2
1 10
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Long.parseLong(Long.java:424)
    at java.lang.Long.parseLong(Long.java:461)
    at sphere.Main.main(Main.java:51)

Process completed.

Here I don't have an integer overflow, but why would jcreator complain?

Considering the borderline testcase, the program implodes on Netbeans too:

run:
2
999900000 1000000000
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        at sphere.Main.runEratosthenesSieve(Main.java:13)
        at sphere.Main.main(Main.java:55)
Java Result: 1

How can I deal with those huge-ish integers of the problem statement?

Edit: By suggestion I have changed the boolean array for a BitSet, but I'm still getting an OutOFMemoryError:

package sphere;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.BitSet;

public class Main{

public static void runEratosthenesSieve(long lowerBound, long upperBound) {

      long upperBoundSquareRoot = (long) Math.sqrt(upperBound);

      //boolean[] isComposite = new boolean[(int)upperBound + 1];

      BitSet isComposite = new BitSet((int)upperBound+1);

      for (int m = 2 /*int m = lowerBound*/; m <= upperBoundSquareRoot; m++) {

            if (!isComposite.get(m)) {

                if (m>=lowerBound) {System.out.println(m);}

                  for (int k = m * m; k <= upperBound; k += m)

                        isComposite.set(m);

            }

      }

      for (int m = (int)upperBoundSquareRoot; m <= upperBound; m++)

            if (!isComposite.get(m))

                 if (m>=lowerBound){ System.out.println(m);}

}

public static void main(String args[]) throws java.lang.Exception{

       BufferedReader r = new BufferedReader(new InputStreamReader(System.in));

       String l = r.readLine();

       int testCases = Integer.parseInt(l);

       for (int i =0; i<testCases; i++){
       String s =r.readLine();

       String []splitted=s.split(" ");

       long lowerBound = Long.parseLong (splitted[0]);
       long upperBound = Long.parseLong(splitted[1]);

       runEratosthenesSieve (lowerBound,upperBound);

       System.out.println("");
       }
}

}

Input-Output:

run:
1
999900000 1000000000
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        at java.util.BitSet.initWords(BitSet.java:144)
        at java.util.BitSet.<init>(BitSet.java:139)
        at sphere.Main.runEratosthenesSieve(Main.java:16)
        at sphere.Main.main(Main.java:58)
Java Result: 1
BUILD SUCCESSFUL (total time: 14 seconds)

Body:
I had faced similar issues due the limitations on Java Heap Size. Instead of using high memory Integer, shifting to boolean solved the problem.
Find the attached code:

public ArrayList<Integer> sieve(int A) {
    boolean prime [] = new boolean[A + 1];
    Arrays.fill(prime, true);
    prime[0] = prime[1] = false;

    for (int i = 2; i <= A; i++) {
        if (!prime[i])
            continue;

        for (long j = 1L * i * i; j <= (long) A; j += i)
            prime[(int) j] = false;
    }

    ArrayList<Integer> res = new ArrayList<>();

    for (int i = 0; i <= A; i++) {
        if (prime[i])
            res.add(i);
    }

    return res;
}


问:
Why doesn't "load" or "DOMContentLoaded" stop a prompt from firing before a page is loaded?
Problem: Javascript fired before my page loaded

Solution: Wrapped Javascript in a function and called it after the page loaded.

Unfortunately it didn't work.  Here is my example.

I have a simple 2 page test site.  The first page has a blue background and a link to the second page. When I click the link on the first page the prompt from the script on the second page appears over the first page before the second page has loaded.  load or DOMContentLoaded don't appear to change this.  I'm sure I'm doing something wrong but I can't spot it.

page 1

```<code><body style="background-color:blue">
    <a href="page_2.htm">Click this link.</a>
</body>
</code>```

page 2

```<code><script>
    function globalFunction() {
        prompt("input a number");
    }
</script>
</code>```

I added this code above the function on the 2nd page but the prompt continued to pop up early above the first page before the 2nd page loaded.

```<code>document.addEventListener("DOMContentLoaded", globalFunction);
</code>```

Then I tried this but got the same result.

```<code>window.addEventListener("load", globalFunction);
</code>```

答:
This is typical behavior when the browser creates a UI element that is not part of the document itself. The browser is a multi-threaded piece of software and a call for a prompt() or an alert() is handled in a different thread than the JavaScript code is running in. The browser is able to update the UI (in this case with a modal dialog that blocks the JS runtime from continuting) before the browser is able to display the second page.

A solution is to make sure the script doesn't even get initiated until the second page has loaded and defer the prompt just enough so that the browser can update the page display to show it.

In your second file, change the code to:

```<code><script>
    window.addEventListener("DOMContentLoaded", function(){
      setTimeout(function globalFunction() {
                 prompt("input a number");
      }, 20);
    });
</script>
</code>```

This will defer the function from running for 20 milliseconds, which should be enough time to see the second page.

Body:
Problem: Javascript fired before my page loaded

Solution: Wrapped Javascript in a function and called it after the page loaded.

Unfortunately it didn't work.  Here is my example.

I have a simple 2 page test site.  The first page has a blue background and a link to the second page. When I click the link on the first page the prompt from the script on the second page appears over the first page before the second page has loaded.  load or DOMContentLoaded don't appear to change this.  I'm sure I'm doing something wrong but I can't spot it.

page 1

    Click this link.

page 2

I added this code above the function on the 2nd page but the prompt continued to pop up early above the first page before the 2nd page loaded.

document.addEventListener("DOMContentLoaded", globalFunction);

Then I tried this but got the same result.

window.addEventListener("load", globalFunction);

Body:
This is typical behavior when the browser creates a UI element that is not part of the document itself. The browser is a multi-threaded piece of software and a call for a prompt() or an alert() is handled in a different thread than the JavaScript code is running in. The browser is able to update the UI (in this case with a modal dialog that blocks the JS runtime from continuting) before the browser is able to display the second page.

A solution is to make sure the script doesn't even get initiated until the second page has loaded and defer the prompt just enough so that the browser can update the page display to show it.

In your second file, change the code to:

<script>
    window.addEventListener("DOMContentLoaded", function(){
      setTimeout(function globalFunction() {
                 prompt("input a number");
      }, 20);
    });
</script>

This will defer the function from running for 20 milliseconds, which should be enough time to see the second page.


问:
PHP Mail Function
Is it possible to send a mail in PHP without any external packages or tools? If so, is there

any requirement to configure the php.ini file?

Its as follows:

```<code>$to = $row->EMail_ID;
$subject = "Reset your password";
$body = "Hi ".$row->Username.", \n\t\t\tA request to reset your  password was received from you. \n\n\n";
$headers = "From: admin@admin.com\r\n"."X-Mailer: php/";
mail($to, $subject, $body, $headers);
</code>```

The error i get:

```<code>Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25,
verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in F:\wamp\www\pwd.php on line 20
</code>```

答:
Yes it is possible with mail function which is an internal function.

No you don't have to configure the php.ini

```<code><?php
// The message
$message = "Line 1\nLine 2\nLine 3";

// Send
mail('caffinated@example.com', 'My Subject', $message);
?>
</code>```

If you want to check this on a local server you have to install a mail server.

Title: PHP Mail Function

Body:
Is it possible to send a mail in PHP without any external packages or tools? If so, is there

any requirement to configure the php.ini file?

Its as follows:

$to = $row->EMail_ID;
$subject = "Reset your password";
$body = "Hi ".$row->Username.", \n\t\t\tA request to reset your  password was received from you. \n\n\n";
$headers = "From: admin@admin.com\r\n"."X-Mailer: php/";
mail($to, $subject, $body, $headers);

The error i get:

Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25,
verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in F:\wamp\www\pwd.php on line 20

Body:
Yes it is possible with mail function which is an internal function.

No you don't have to configure the php.ini

<?php
// The message
$message = "Line 1\nLine 2\nLine 3";

// Send
mail('caffinated@example.com', 'My Subject', $message);
?>

If you want to check this on a local server you have to install a mail server.


问:
Haskell nested algebraic data type
I'm trying to model the following simple Scala ADT in Haskell:

```<code>sealed trait Value

sealed trait Literal < Value
case object Null extends Literal
case class IntLiteral(value: Int) extends Literal

case class Variable(name: String) < Value
</code>```

I model the Literal trait:

```<code>Prelude> data Literal = Null | IntLiteral Int deriving (Show, Eq)
</code>```

So far so good:

```<code>Prelude> Null
Null
Prelude> Null == IntLiteral 3
False
Prelude> IntLiteral 3 == IntLiteral 3
True
</code>```

Now I try to introduce Variable:

```<code>data Value = Literal | Variable String deriving (Show, Eq)
</code>```

Why doesn't this work?

```<code>Prelude> Null == Variable "foo"

<interactive>:3:9: error:
    • Couldn't match expected type ‘Literal’ with actual type ‘Value’
    • In the second argument of ‘(==)’, namely ‘Variable "foo"’
      In the expression: Null == Variable "foo"
      In an equation for ‘it’: it = Null == Variable "foo"
</code>```

答:
Null is of type Literal, Variable "foo" is of type Value. There can also be a data constructor Literal, unrelated to the type with the same name. These are just different things, living in separate namespaces, in Haskell. If you write

```<code>data Value = Literal Literal | ...
</code>```

then, the first Literal is a name of a data constructor (creates values of type Value, in that case), the second is a name of a type.

Title: Haskell nested algebraic data type

Body:
I'm trying to model the following simple Scala ADT in Haskell:

sealed trait Value

sealed trait Literal < Value
case object Null extends Literal
case class IntLiteral(value: Int) extends Literal

case class Variable(name: String) < Value

I model the Literal trait:

Prelude> data Literal = Null | IntLiteral Int deriving (Show, Eq)

So far so good:

Prelude> Null
Null
Prelude> Null == IntLiteral 3
False
Prelude> IntLiteral 3 == IntLiteral 3
True

Now I try to introduce Variable:

data Value = Literal | Variable String deriving (Show, Eq)

Why doesn't this work?

Prelude> Null == Variable "foo"

<interactive>:3:9: error:
    • Couldn't match expected type ‘Literal’ with actual type ‘Value’
    • In the second argument of ‘(==)’, namely ‘Variable "foo"’
      In the expression: Null == Variable "foo"
      In an equation for ‘it’: it = Null == Variable "foo"

Body:
Null is of type Literal, Variable "foo" is of type Value. There can also be a data constructor Literal, unrelated to the type with the same name. These are just different things, living in separate namespaces, in Haskell. If you write

data Value = Literal Literal | ...

then, the first Literal is a name of a data constructor (creates values of type Value, in that case), the second is a name of a type.


问:
Pull an IP from the landing page and compare to known users
I am trying to create a working sql query that will give an accurate FLAG for a known or unknown IP address in our database upon hitting our landing page. I use this

```<code>// get the IP of the user on this landing page
$ip_address=$_SERVER['REMOTE_ADDR'];
echo $ip_address. ' ip address<br/>';

// see if we know this user..
$search_first="SELECT COUNT(DISTINCT(ip_address)) FROM `qb_sessions` WHERE `ip_address` = '$ip_address' ";
$has_ips = mysql_query($search_first);
$has_ip = mysql_num_rows($has_ips);
echo $has_ip. ' has IP<br/>'; // should show count in table
</code>```

Using this snippet does not provide the result that I need.  If the table is empty, (no match to this IP), I still get a '1' as the echo of $has_ip. I really need '0' if there is no match, and anything '&gt 1' if this IP has been recorded in qb_sessions table before. The purpose of this snippet is to identify a new, non-registered hit on this landing page and later to redirect them to another page, like join a newsletter, get a discount coupon, etc.

I have tried various combinations of the sql to no avail, including escaping the (') $ip_address quotes.

Thank you in advance for any help.

答:
... If the table is empty, (no match to this IP), I still get a '1' as the echo of $has_ip.

That's because of MySQL's COUNT() function. Whether the table contains 1 row or n rows SELECT COUNT(...) ... will still return exactly one row containing a number which shows the number of rows returned from the SELECT query.

Since you're using PHP's mysql_num_rows() function anyway to count number of rows, drop COUNT() from your SELECT query.

```<code>$search_first="SELECT DISTINCT(ip_address) FROM `qb_sessions` ...
</code>```

Sidenote: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.

Body:
I am trying to create a working sql query that will give an accurate FLAG for a known or unknown IP address in our database upon hitting our landing page. I use this

// get the IP of the user on this landing page
$ip_address=$_SERVER['REMOTE_ADDR'];
echo $ip_address. ' ip address
';

// see if we know this user..
$search_first="SELECT COUNT(DISTINCT(ip_address)) FROM `qb_sessions` WHERE `ip_address` = '$ip_address' ";
$has_ips = mysql_query($search_first);
$has_ip = mysql_num_rows($has_ips);
echo $has_ip. ' has IP
'; // should show count in table

Using this snippet does not provide the result that I need.  If the table is empty, (no match to this IP), I still get a '1' as the echo of $has_ip. I really need '0' if there is no match, and anything '&gt 1' if this IP has been recorded in qb_sessions table before. The purpose of this snippet is to identify a new, non-registered hit on this landing page and later to redirect them to another page, like join a newsletter, get a discount coupon, etc.

I have tried various combinations of the sql to no avail, including escaping the (') $ip_address quotes.

Thank you in advance for any help.

Body:
... If the table is empty, (no match to this IP), I still get a '1' as the echo of $has_ip.

That's because of MySQL's COUNT() function. Whether the table contains 1 row or n rows SELECT COUNT(...) ... will still return exactly one row containing a number which shows the number of rows returned from the SELECT query.

Since you're using PHP's mysql_num_rows() function anyway to count number of rows, drop COUNT() from your SELECT query.

$search_first="SELECT DISTINCT(ip_address) FROM `qb_sessions` ...

Sidenote: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.


答:
```<code>SELECT COUNT(DISTINCT(ip_address))
</code>```

This is always going to return a row.  Exactly one row.  Containing exactly one number.  That number might be a zero, but there will be a row in the result containing that number.

```<code>mysql_num_rows($has_ips)
</code>```

This will always be 1, because the above query will always return one row.

Instead of counting the returned rows, examine the already-counted returned value.  Something like this:

```<code>$has_ips = mysql_query($search_first);
$row = mysql_fetch_array($has_ips);
$has_ip = $row[0];
echo $has_ip. ' has IP<br/>';
</code>```

(I think that's how a result would be fetched, it's been a while since I've written PHP code.  But the idea is straightforward enough, you want the first (only) element of the first (only) returned row.)

Title: Pull an IP from the landing page and compare to known users

Body:
SELECT COUNT(DISTINCT(ip_address))

This is always going to return a row.  Exactly one row.  Containing exactly one number.  That number might be a zero, but there will be a row in the result containing that number.

mysql_num_rows($has_ips)

This will always be 1, because the above query will always return one row.

Instead of counting the returned rows, examine the already-counted returned value.  Something like this:

$has_ips = mysql_query($search_first);
$row = mysql_fetch_array($has_ips);
$has_ip = $row[0];
echo $has_ip. ' has IP<br/>';

(I think that's how a result would be fetched, it's been a while since I've written PHP code.  But the idea is straightforward enough, you want the first (only) element of the first (only) returned row.)


问:
Finding the data attribute value of a parent div several levels up with jQuery
I am trying to access the nearest div from the anchor tag that has a data-id attribute.

.parent().parent().parent() works but I am really trying to avoid doing that.

```<code><div class="panel panel-default" data-id="@customer.Id">
        <div class="panel-heading clearfix">
            @customer.Name
            <div class="pull-right">
                <a class="btn btn-sm btn-default js-deleteCustomer" href="#" title="Delete">
                    <i class="fa fa-trash" aria-hidden="true"></i>
                </a>
        </div>
</div>
</code>```

I tried the following:

```<code>var customerId = $(this).closest("div:has(*[data-id])").attr('data-id');
</code>```

答:
You want

```<code>var customerId = $(this).closest("div[data-id]").attr('data-id');
</code>```

:has(*[data-id]) doesn't match an element with that attribute. It matches an element that contains another element with that attribute. The element that's matched probably doesn't have this same attribute, which would explain why :has(*[data-id]) doesn't work. For instance, it would match the outer div, not the inner div, in the following:

```<code><div>
  <div data-id="@customer.Id"></div>
</div>
</code>```

To match an element that has an attribute, simply attach the attribute selector directly without using :has().

Body:
I am trying to access the nearest div from the anchor tag that has a data-id attribute.

.parent().parent().parent() works but I am really trying to avoid doing that.

            @customer.Name

I tried the following:

var customerId = $(this).closest("div:has(*[data-id])").attr('data-id');

Body:
You want

var customerId = $(this).closest("div[data-id]").attr('data-id');

:has(*[data-id]) doesn't match an element with that attribute. It matches an element that contains another element with that attribute. The element that's matched probably doesn't have this same attribute, which would explain why :has(*[data-id]) doesn't work. For instance, it would match the outer div, not the inner div, in the following:

<div>
  <div data-id="@customer.Id"></div>
</div>

To match an element that has an attribute, simply attach the attribute selector directly without using :has().


问:
Nginx + Passenger + Rails 3 Rack processes hang
I have a MySQL backed Rails 3 application.  I currently have scaling issues with reads on the database and I am working on fixing them independently.

In the meantime, since certain database queries take many minutes to run, Passenger spawns multiple Rack processes (upto the limit specified), but all of them wait / hang waiting for the database.

At a certain point, nginx refuses to accept more connections.

Is there a way I can tell Passenger to timeout its Rails delegated calls and free up resources so it can listen for incoming requests?

Thanks.

答:
If you're handling queries in requests that take many minutes, you're doing it wrong.

Requests should be as fast as possible. Several minutes is unacceptable. Consider off-loading the long-running queries to Delayed::Job, so they can run in the background instead of blocking other requests.

Also, I don't know what query you're running, but if it's taking many minutes you might want consider analyzing them.


问:
How to add stopwords to the default list in ElasticSearch
I want to add more words to the default "english" stopwards, e.g., "inc", "incorporated", "ltd" and "limited". How can I achieve this?

My current code to create an index is as follows. Thanks.

```<code>PUT /my_index
{
  "settings": {
    "analysis": {
      "filter": {
        "my_stop": {
          "type": "stop",
          "stopwords": "_english_"
        }
      },
      "analyzer": {
        "my_analyzer": {
          "tokenizer": "whitespace",
           "char_filter": [
            "html_strip"
          ],
          "filter": [
            "lowercase",
            "asciifolding",
            "my_stop"
          ]
        }
      }
    }
  }
}
</code>```

My test code

```<code>POST my_index/_analyze
{
  "analyzer": "my_analyzer",
  "text": "House of Dickson<br> corp"
}
</code>```

答:
The set of "english" stopwords is the same as the set in Standard Analyzer.

You can create a file with these words and your additional stopwords and use stopwords_path option to point to this file (instead of stopwords setting):

```<code>{
  "settings": {
    "analysis": {
      "filter": {
        "my_stop": {
          "type": "stop",
          "stopwords_path": "stopwords/custom_english.txt"
        }
      },
      ...
}
</code>```

You can find more information how the file should look like in ES-docs (UTF-8, single stopword per line, file present on all nodes).

Body:
I want to add more words to the default "english" stopwards, e.g., "inc", "incorporated", "ltd" and "limited". How can I achieve this?

My current code to create an index is as follows. Thanks.

PUT /my_index
{
  "settings": {
    "analysis": {
      "filter": {
        "my_stop": {
          "type": "stop",
          "stopwords": "_english_"
        }
      },
      "analyzer": {
        "my_analyzer": {
          "tokenizer": "whitespace",
           "char_filter": [
            "html_strip"
          ],
          "filter": [
            "lowercase",
            "asciifolding",
            "my_stop"
          ]
        }
      }
    }
  }
}

My test code

POST my_index/_analyze
{
  "analyzer": "my_analyzer",
  "text": "House of Dickson
 corp"
}

Body:
The set of "english" stopwords is the same as the set in Standard Analyzer.

You can create a file with these words and your additional stopwords and use stopwords_path option to point to this file (instead of stopwords setting):

{
  "settings": {
    "analysis": {
      "filter": {
        "my_stop": {
          "type": "stop",
          "stopwords_path": "stopwords/custom_english.txt"
        }
      },
      ...
}

You can find more information how the file should look like in ES-docs (UTF-8, single stopword per line, file present on all nodes).


问:
Javascript counter on key input instead of button?
So I have this counter that increments 'positive' and 'negative' values, it's working fine. Now I also want to assign keyboard key to increment the values, 'f' for negative and 'j' for positive. How do I do this?
I have been fiddling with onkeypress/onkeyup but it is still confusing.

```<code><html>
<head>
<script type="text/javascript">

function modify_qty(val) {
var qty = document.getElementById('qty').value;
var new_qty = parseInt(qty,10) + val;

if (new_qty < 0) {
    new_qty = 0;
}

document.getElementById('qty').value = new_qty;
return new_qty;
}

function modify_qtyn(val) {
var qtyn = document.getElementById('qtyn').value;
var new_qtyn = parseInt(qtyn,10) + val;

if (new_qtyn < 0) {
    new_qtyn = 0;
}

document.getElementById('qtyn').value = new_qtyn;
return new_qtyn;
}

</script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

<div class="box">
    <label for="Positive"><abbr title="Positive">Qty</abbr></label>
    <label for="Negative"><abbr title="Negative">Qtyn</abbr></label>
    <input id="qtyn" value="0" />
    <input id="qty" value="0" />
    <button id="down" onclick="modify_qtyn(1)">MINUS</button>
    <button id="up" onclick="modify_qty(1)">PLUS</button>

</div>

</body>
</html>
</code>```

I found the solution by adding this:

```<code>function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
window.onload = function(){
document.onkeypress = function(e){
    var key = code(e);
    if (key==102) {modify_qtyn(1);}
    if (key==70) {modify_qtyn(1);}
    if (key==106) {modify_qty(1);}
    if (key==74) {modify_qty(1);}
   };
};
</code>```

答:
You can use the event keypress in the tag  or even in the window. Check the documentation of this event.

```<code><body onkeypress="func(event)">
</code>```

or

```<code>window.addEventListener('keypress', func);
</code>```

sor in this func you read the event.key passed as the first parameter to verify if is letter "f" or "j".

Body:
So I have this counter that increments 'positive' and 'negative' values, it's working fine. Now I also want to assign keyboard key to increment the values, 'f' for negative and 'j' for positive. How do I do this?
I have been fiddling with onkeypress/onkeyup but it is still confusing.

<link rel="stylesheet" type="text/css" href="style.css">

    Qty
    Qtyn
    <input id="qtyn" value="0" />
    <input id="qty" value="0" />
    <button id="down" onclick="modify_qtyn(1)">MINUS</button>
    <button id="up" onclick="modify_qty(1)">PLUS</button>

I found the solution by adding this:

function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
window.onload = function(){
document.onkeypress = function(e){
    var key = code(e);
    if (key==102) {modify_qtyn(1);}
    if (key==70) {modify_qtyn(1);}
    if (key==106) {modify_qty(1);}
    if (key==74) {modify_qty(1);}
   };
};

Body:
You can use the event keypress in the tag <body> or even in the window. Check the documentation of this event.

<body onkeypress="func(event)">

or

window.addEventListener('keypress', func);

sor in this func you read the event.key passed as the first parameter to verify if is letter "f" or "j".


问:
creating javascript arrays in typescript when to use an interface, when not to, and when to use a constructor
here is my understanding regarding java script object arrays in typescript

In my current code I am grabbing an array of json from an observable. As I understand it I can declare the array then initalize it without a need for a interface or type.

```<code>let cityList[]; // the value of cityList here is null correct?
cityList[] = response;
</code>```

I could also use an interface too but it isn't necessary ever just a good idea so the compiler is your friend like in java no?

```<code>interface Blah{
city: string;
}

let cityList: Blah[];
cityList[] = response;
</code>```

I as well could create a constructor (if I needed to dynamically add javascript objects to the array and thats the only time I would need to correct?

答:
So I was wrong I now KNow that this is the proper way of doing things.

I only need to create a constructor if I am adding an object or creating an new object that will be used in my code or sent over the wire.

I don't use interfaces, I use models

so if I wanted to create a city javascript object which just contains the cities name I would have the following

this is written in typescript

```<code>export class City{
  public name: string;

  constructor(name:string){
    this.name = name;
  }
}
</code>```

then the array  i want to store these objects would have to have the proper type :

```<code>cityList:City[];
</code>```

the array above in uninitialized to initalize it, set a value to the array or if you have no values but need it initalized set it to an empty array like so.

```<code>cityList: City[] = [];
</code>```

Body:
here is my understanding regarding java script object arrays in typescript

In my current code I am grabbing an array of json from an observable. As I understand it I can declare the array then initalize it without a need for a interface or type.

let cityList[]; // the value of cityList here is null correct?
cityList[] = response;

I could also use an interface too but it isn't necessary ever just a good idea so the compiler is your friend like in java no?

interface Blah{
city: string;
}

let cityList: Blah[];
cityList[] = response;

I as well could create a constructor (if I needed to dynamically add javascript objects to the array and thats the only time I would need to correct?

Body:
So I was wrong I now KNow that this is the proper way of doing things.

I only need to create a constructor if I am adding an object or creating an new object that will be used in my code or sent over the wire.

I don't use interfaces, I use models

so if I wanted to create a city javascript object which just contains the cities name I would have the following

this is written in typescript

export class City{
  public name: string;

  constructor(name:string){
    this.name = name;
  }
}

then the array  i want to store these objects would have to have the proper type :

cityList:City[];

the array above in uninitialized to initalize it, set a value to the array or if you have no values but need it initalized set it to an empty array like so.

cityList: City[] = [];


问:
How to get a certain Croppie JavaScript to rotate using buttons
I am trying to get a Croppie Script to rotate using buttons. It does not work with this particular script due to what appears to be a different syntax or something. I am not an avid JavaScript coder. But the below code is what I have and trying to get rotation using button to work. So far no good! Oh! I have enabled the Orientation by default in croppie.js because due to the syntax I did not know how to add it within the script below, just in case you are wondering.

```<code>$( document ).ready(function() {

    var $uploadCrop = $('#upload-demo');

        $uploadCrop.croppie({
            viewport: {
                width: 450,
                height: 450,
                type: 'square'
            },
            boundary: {
                width: 500,
                height: 500
            }
        });
        $uploadCrop.croppie('bind', 'imgs/cat.jpg');

        $('.vanilla-rotate').on('click', function(ev) {
            vanilla.rotate(parseInt($(this).data('deg'))); //<-------
        });

    $('.upload-result').on('click', function (ev) {
        $uploadCrop.croppie('result', {
            type: 'canvas',
            size: 'original'
        }).then(function (resp) {
            $('#imagebase64').val(resp);
            $('#form').submit();
        });
    });

});
</code>```

It seems to me that the line where I have comment out arrow is the problem. But I could be wrong.

I have a button on html page as

```<code><button class="vanilla-rotate" data-deg="-90">Rotate</button>
</code>```

Their Vanilla demo has the rotating feature but I am trying to get it to work on the Upload demo where they do not have rotation feature.

答:
Create a function after initializing uploadCrop.</p>

```<code>$(function() {
  $('.vanilla-rotate').on('click', function(ev) {
        $uploadCrop.croppie('rotate', parseInt($(this).data('deg')));
    });
});
</code>```

Body:
I am trying to get a Croppie Script to rotate using buttons. It does not work with this particular script due to what appears to be a different syntax or something. I am not an avid JavaScript coder. But the below code is what I have and trying to get rotation using button to work. So far no good! Oh! I have enabled the Orientation by default in croppie.js because due to the syntax I did not know how to add it within the script below, just in case you are wondering.

$( document ).ready(function() {

    var $uploadCrop = $('#upload-demo');

        $uploadCrop.croppie({
            viewport: {
                width: 450,
                height: 450,
                type: 'square'
            },
            boundary: {
                width: 500,
                height: 500
            }
        });
        $uploadCrop.croppie('bind', 'imgs/cat.jpg');

        $('.vanilla-rotate').on('click', function(ev) {
            vanilla.rotate(parseInt($(this).data('deg'))); //<-------
        });

    $('.upload-result').on('click', function (ev) {
        $uploadCrop.croppie('result', {
            type: 'canvas',
            size: 'original'
        }).then(function (resp) {
            $('#imagebase64').val(resp);
            $('#form').submit();
        });
    });

});

It seems to me that the line where I have comment out arrow is the problem. But I could be wrong.

I have a button on html page as

<button class="vanilla-rotate" data-deg="-90">Rotate</button>

Their Vanilla demo has the rotating feature but I am trying to get it to work on the Upload demo where they do not have rotation feature.

Body:
Create a function after initializing uploadCrop.

$(function() {
  $('.vanilla-rotate').on('click', function(ev) {
        $uploadCrop.croppie('rotate', parseInt($(this).data('deg')));
    });
});


问:
rails parsing xml to show json format
I'm trying to convert some XML into JSON

This is what I have so far

```<code>def skiddle_api
  skiddlexml = 'http://xml.skiddlecdn.co.uk/affiliates/all.xml'
  doc = Nokogiri::XML(open(skiddlexml))
  doc.css('event#12987613').css('ticket').each do |node|
    children = node.children
      byebug
    @ticket_json = {
      'name' => children.css('name').inner_text
      'facevalue' => children.css('faceValue').inner_text
    }
  end
  respond_to do |format|
     format.json  { render :json => {:ticket => @ticket_json } }
  end
end
</code>```

The event I have on here at the moment has 5-8 different ticket types

I'm wanting each ticket type to show as JSON format like this:

```<code>{
    "ticket": {
        "name": "Return Coach Ticket - Glasgow - Coach A"
        "faceValue": "20.00"
    }
    "ticket": {
        "name": "Return Coach Ticket - Manchester - Coach B"
        "faceValue": "25.00"
    }
}
</code>```

What am I doing wrong here?

Thank you :)

答:
The problem is that you replace @ticket_json each time here:

```<code>@ticket_json = {
  'name' => children.css('name').inner_text,
  'facevalue' => children.css('faceValue').inner_text
}
</code>```

So you need to assign a new value each time, but @ticket_json can't be a hash, it must be an array of hashes in order for it to work (you can't have duplicate keys in a hash, and your example has duplicate keys).

The solution then will be to create an array instead of hash outside the each loop and add a ticket on each iteration, something like this:

```<code>def skiddle_api
  skiddlexml = 'http://xml.skiddlecdn.co.uk/affiliates/all.xml'
  doc = Nokogiri::XML(open(skiddlexml))

  @ticket_json = []

  doc.css('event#12987613').css('ticket').each do |node|
    children = node.children
    @ticket_json << {
      'name' => children.css('name').inner_text,
      'facevalue' => children.css('faceValue').inner_text
    }
  end

  respond_to do |format|
     format.json  { render :json => {:ticket => @ticket_json } }
  end
end
</code>```

The output will something like this:

```<code>[
  {
    "name":"Earlybird Ticket",
    "facevalue":"30.00"
  },
  {
    "name":"VIP Ticket",
    "facevalue":"50.00"
  },
  {
    "name":"Standard E-Ticket",
    "facevalue":"0.00"
  }
]
</code>```

If you want to keep a ticket key, you can do so, just make their values an array of hashes, for example:

```<code>def skiddle_api
  skiddlexml = 'http://xml.skiddlecdn.co.uk/affiliates/all.xml'
  doc = Nokogiri::XML(open(skiddlexml))

  @ticket_json = { tickets: [] }

  doc.css('event#12987613').css('ticket').each do |node|
    children = node.children
    @ticket_json[:tickets] << {
      'name' => children.css('name').inner_text,
      'facevalue' => children.css('faceValue').inner_text
    }
  end

  respond_to do |format|
     format.json  { render :json => {:ticket => @ticket_json } }
  end
end
</code>```

And the output will be similar to:

```<code>{
  "tickets": [
    {
      "name":"Earlybird Ticket",
      "facevalue":"30.00"
    },
    {
      "name":"VIP Ticket",
      "facevalue":"50.00"
    },
    {
      "name":"Standard E-Ticket",
      "facevalue":"0.00"
    }
  ]
}
</code>```

Title: rails parsing xml to show json format

Body:
I'm trying to convert some XML into JSON

This is what I have so far

def skiddle_api
  skiddlexml = 'http://xml.skiddlecdn.co.uk/affiliates/all.xml'
  doc = Nokogiri::XML(open(skiddlexml))
  doc.css('event#12987613').css('ticket').each do |node|
    children = node.children
      byebug
    @ticket_json = {
      'name' => children.css('name').inner_text
      'facevalue' => children.css('faceValue').inner_text
    }
  end
  respond_to do |format|
     format.json  { render :json => {:ticket => @ticket_json } }
  end
end

The event I have on here at the moment has 5-8 different ticket types

I'm wanting each ticket type to show as JSON format like this:

{
    "ticket": {
        "name": "Return Coach Ticket - Glasgow - Coach A"
        "faceValue": "20.00"
    }
    "ticket": {
        "name": "Return Coach Ticket - Manchester - Coach B"
        "faceValue": "25.00"
    }
}

What am I doing wrong here?

Thank you :)

Body:
The problem is that you replace @ticket_json each time here:

@ticket_json = {
  'name' => children.css('name').inner_text,
  'facevalue' => children.css('faceValue').inner_text
}

So you need to assign a new value each time, but @ticket_json can't be a hash, it must be an array of hashes in order for it to work (you can't have duplicate keys in a hash, and your example has duplicate keys).

The solution then will be to create an array instead of hash outside the each loop and add a ticket on each iteration, something like this:

def skiddle_api
  skiddlexml = 'http://xml.skiddlecdn.co.uk/affiliates/all.xml'
  doc = Nokogiri::XML(open(skiddlexml))

  @ticket_json = []

  doc.css('event#12987613').css('ticket').each do |node|
    children = node.children
    @ticket_json << {
      'name' => children.css('name').inner_text,
      'facevalue' => children.css('faceValue').inner_text
    }
  end

  respond_to do |format|
     format.json  { render :json => {:ticket => @ticket_json } }
  end
end

The output will something like this:

[
  {
    "name":"Earlybird Ticket",
    "facevalue":"30.00"
  },
  {
    "name":"VIP Ticket",
    "facevalue":"50.00"
  },
  {
    "name":"Standard E-Ticket",
    "facevalue":"0.00"
  }
]

If you want to keep a ticket key, you can do so, just make their values an array of hashes, for example:

def skiddle_api
  skiddlexml = 'http://xml.skiddlecdn.co.uk/affiliates/all.xml'
  doc = Nokogiri::XML(open(skiddlexml))

  @ticket_json = { tickets: [] }

  doc.css('event#12987613').css('ticket').each do |node|
    children = node.children
    @ticket_json[:tickets] << {
      'name' => children.css('name').inner_text,
      'facevalue' => children.css('faceValue').inner_text
    }
  end

  respond_to do |format|
     format.json  { render :json => {:ticket => @ticket_json } }
  end
end

And the output will be similar to:

{
  "tickets": [
    {
      "name":"Earlybird Ticket",
      "facevalue":"30.00"
    },
    {
      "name":"VIP Ticket",
      "facevalue":"50.00"
    },
    {
      "name":"Standard E-Ticket",
      "facevalue":"0.00"
    }
  ]
}


问:
How do I position the drop down of AngularJS Material Select?
Try running the code I made in plunker here http://plnkr.co/bvysoi

```<code><div ng-controller="dropdownController" class="md-padding" ng-cloak>
  <div layout="row">
    <md-input-container>
      <md-select md-container-class="my-container" ng-model="selected" md-selected-text="displaySelected()" multiple>
        <md-optgroup>
          <md-option ng-value="data.label" ng-repeat="data in datas" ng-click="clicked(datas, data)" ng-selected="data.selected">{{data.label}}</md-option>
        </md-optgroup>
      </md-select>
    </md-input-container>
  </div>
</div>
</code>```

As you can see, this is what you see when you click on the select menu

Now try clicking on "Contribution 2" and deselect "All Contribution Types" then click out of the drop down then click again on the select menu. As you noticed, this is what you get

The position of the drop down moved. I think this is the default behavior so I wanted to change this.

My question is how do I always position the drop down just below the select exactly just like the 1st screenshot no matter what I've selected first? I'm still new to AngularJS. Thanks!

EDIT: I'm not allowed to use jQuery or any other libraries. I'm only limited to AngularJS

答:
Yeah it's the default behaviour. If you want to change the dropdown's position then you've to handle it using jquery to change its CSS property. And also have to take care that your dom manipulation executes after Material design js does. So by finding offset top of md-select element & subtracting approx. height of select (here 20px) you'll get css top for your dropdown which you can give it be selecting its class which made available by attribute md-container-class="my-container" So your code shall look like:

```<code><div layout="row">
  <div class="select" ng-click="selclicked()">
    <md-input-container>
      <md-select md-container-class="my-container" ng-model="selected"
        md-selected-text="displaySelected()" multiple class="my-md-select">
        <md-optgroup>
          <md-option ng-value="data.label" ng-repeat="data in datas"
           ng-click="clicked(datas, data)" ng-selected="data.selected">{{data.label}}
          </md-option>
        </md-optgroup>
      </md-select>
    </md-input-container>
  </div>
</div>
</code>```

selclicked() function will carry out position change which is:

```<code>$scope.selclicked = function(){
    var containerTop = $(".my-md-select").offset().top - 20 + "px";
    setTimeout(function(){
        $(".my-container").css({'top':containerTop});
    }, 50);

};
</code>```

Here timeout should depend on how fast animations for material design implemented in your project & minimal time required to execute md js functions. Here's updated version of your plunker: http://plnkr.co/edit/4FSWeAC4Ae4iWfWSCzvG?p=preview

Update:

If you've restriction to use only javascript then you can achieve same thing of finding offset of those elements using Element.getBoundingClientRect() It has basic support for all the browsers. So your function might look:

```<code>$scope.selclicked = function(){
    var bodyRect = document.body.getBoundingClientRect();
    var myElement  = document.getElementsByClassName('sel');
    var containerTop = myElement[0].getBoundingClientRect().top - bodyRect.top + 'px';
    var myContainer = document.getElementsByClassName('my-container');
    setTimeout(function(){
        angular.element(myContainer).css({'top':containerTop});
    }, 50);

};
</code>```

Here's working plunker link: http://plnkr.co/edit/DjFiWJD1FPFzEK0v7siG?p=preview

Body:
Try running the code I made in plunker here http://plnkr.co/bvysoi

    <md-input-container>
      <md-select md-container-class="my-container" ng-model="selected" md-selected-text="displaySelected()" multiple>
        <md-optgroup>
          <md-option ng-value="data.label" ng-repeat="data in datas" ng-click="clicked(datas, data)" ng-selected="data.selected">{{data.label}}</md-option>
        </md-optgroup>
      </md-select>
    </md-input-container>

As you can see, this is what you see when you click on the select menu

Now try clicking on "Contribution 2" and deselect "All Contribution Types" then click out of the drop down then click again on the select menu. As you noticed, this is what you get

The position of the drop down moved. I think this is the default behavior so I wanted to change this.

My question is how do I always position the drop down just below the select exactly just like the 1st screenshot no matter what I've selected first? I'm still new to AngularJS. Thanks!

EDIT: I'm not allowed to use jQuery or any other libraries. I'm only limited to AngularJS

Body:
Yeah it's the default behaviour. If you want to change the dropdown's position then you've to handle it using jquery to change its CSS property. And also have to take care that your dom manipulation executes after Material design js does. So by finding offset top of md-select element & subtracting approx. height of select (here 20px) you'll get css top for your dropdown which you can give it be selecting its class which made available by attribute md-container-class="my-container" So your code shall look like:

<div layout="row">
  <div class="select" ng-click="selclicked()">
    <md-input-container>
      <md-select md-container-class="my-container" ng-model="selected"
        md-selected-text="displaySelected()" multiple class="my-md-select">
        <md-optgroup>
          <md-option ng-value="data.label" ng-repeat="data in datas"
           ng-click="clicked(datas, data)" ng-selected="data.selected">{{data.label}}
          </md-option>
        </md-optgroup>
      </md-select>
    </md-input-container>
  </div>
</div>

selclicked() function will carry out position change which is:

$scope.selclicked = function(){
    var containerTop = $(".my-md-select").offset().top - 20 + "px";
    setTimeout(function(){
        $(".my-container").css({'top':containerTop});
    }, 50);

};

Here timeout should depend on how fast animations for material design implemented in your project & minimal time required to execute md js functions. Here's updated version of your plunker: http://plnkr.co/edit/4FSWeAC4Ae4iWfWSCzvG?p=preview

Update:

If you've restriction to use only javascript then you can achieve same thing of finding offset of those elements using Element.getBoundingClientRect() It has basic support for all the browsers. So your function might look:

$scope.selclicked = function(){
    var bodyRect = document.body.getBoundingClientRect();
    var myElement  = document.getElementsByClassName('sel');
    var containerTop = myElement[0].getBoundingClientRect().top - bodyRect.top + 'px';
    var myContainer = document.getElementsByClassName('my-container');
    setTimeout(function(){
        angular.element(myContainer).css({'top':containerTop});
    }, 50);

};

Here's working plunker link: http://plnkr.co/edit/DjFiWJD1FPFzEK0v7siG?p=preview


问:
How to read "fetch(PDO::FETCH_ASSOC);"
I am trying to build a web application using PHP and I am using Memcached for storing user data from the database.

For example, let’s say that I have this code:

```<code> $sql    = "SELECT * FROM users WHERE user_id = :user_id";
$stmt   = $this->_db->prepare($sql);
$result = $stmt->execute(array(":user_id" => $user_id));
$user   = $stmt->fetch(PDO::FETCH_ASSOC);
</code>```

I am not really sure how to read the $user variable and get the data out of it. I will need to be able to read the email and password column.

How does this work?

答:
Method

```<code>$user = $stmt->fetch(PDO::FETCH_ASSOC);
</code>```

returns a dictionary. You can simply get email and password:

```<code>$email = $user['email'];
$password = $user['password'];
</code>```

Other method

```<code>$users = $stmt->fetchall(PDO::FETCH_ASSOC);
</code>```

returns a list of a dictionary

ContentLicense: CC BY-SA 4.0

Title: How to read "fetch(PDO::FETCH_ASSOC);"

Body:
I am trying to build a web application using PHP and I am using Memcached for storing user data from the database.

For example, let’s say that I have this code:

 $sql    = "SELECT * FROM users WHERE user_id = :user_id";
$stmt   = $this->_db->prepare($sql);
$result = $stmt->execute(array(":user_id" => $user_id));
$user   = $stmt->fetch(PDO::FETCH_ASSOC);

I am not really sure how to read the $user variable and get the data out of it. I will need to be able to read the email and password column.

How does this work?

Body:
Method

$user = $stmt->fetch(PDO::FETCH_ASSOC);

returns a dictionary. You can simply get email and password:

$email = $user['email'];
$password = $user['password'];

Other method

$users = $stmt->fetchall(PDO::FETCH_ASSOC);

returns a list of a dictionary


问:
Is there a way to handle WCF server faults in one spot on the client?
Right now I am wrapping all my WCF service calls in the following try/catch block and I am wondering if there is a way to set this in one place and have it apply to all service calls.</p>

```<code>try
{
    Product test = client.GetProductById(1);
}
catch (TimeoutException ex)
{
    WPFMessageBox.Show("The service operation timed out." + ex.Message);
}
catch (FaultException<CustomFault> ex)
{
    WPFMessageBox.Show("CustomFault:" + ex.ToString());
}
catch (FaultException ex)
{
    WPFMessageBox.Show("Unknown Fault:" + ex.ToString());
}
catch (CommunicationException ex)
{
    WPFMessageBox.Show("There was a communication problem" + ex.Message +
                        ex.StackTrace);
}
</code>```

答:
You could do that through AoP and IoC.

Here I have written how:
http://pablocastilla.wordpress.com/2010/11/09/aop-and-ioc-in-wcf-4-0-with-enterprise-library-5-and-appfabric-part-1/

There is a code example.

Body:
Right now I am wrapping all my WCF service calls in the following try/catch block and I am wondering if there is a way to set this in one place and have it apply to all service calls.

try
{
    Product test = client.GetProductById(1);
}
catch (TimeoutException ex)
{
    WPFMessageBox.Show("The service operation timed out." + ex.Message);
}
catch (FaultException<CustomFault> ex)
{
    WPFMessageBox.Show("CustomFault:" + ex.ToString());
}
catch (FaultException ex)
{
    WPFMessageBox.Show("Unknown Fault:" + ex.ToString());
}
catch (CommunicationException ex)
{
    WPFMessageBox.Show("There was a communication problem" + ex.Message +
                        ex.StackTrace);
}


问:
Uva's 3n+1 problem
I'm solving Uva's 3n+1 problem and I don't get why the judge is rejecting my answer. The time limit hasn't been exceeded and the all test cases I've tried have run correctly so far. </p>

```<code>   import java.io.*;

public class NewClass{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {

        int maxCounter= 0;
        int input;

        int lowerBound;
        int upperBound;
        int counter;
        int numberOfCycles;
        int maxCycles= 0;
        int lowerInt;
        BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
        String line = consoleInput.readLine();
        String [] splitted =  line.split(" ");

        lowerBound = Integer.parseInt(splitted[0]);
        upperBound = Integer.parseInt(splitted[1]);

        int [] recentlyused =  new int[1000001];

if (lowerBound > upperBound )
{
    int h = upperBound;
    upperBound = lowerBound;
    lowerBound = h;

}
lowerInt = lowerBound;
        while (lowerBound <= upperBound)
        {
            counter = lowerBound;
            numberOfCycles = 0;

            if (recentlyused[counter] == 0)
            {
                while ( counter != 1 )
                {

                        if (recentlyused[counter] != 0)
                        {

                        numberOfCycles = recentlyused[counter] + numberOfCycles;
                        counter = 1;
                        }
                        else
                        {
                            if (counter % 2 == 0)
                            {
                            counter = counter /2;
                            }
                            else
                            {
                            counter = 3*counter + 1;
                            }
                            numberOfCycles++;
                        }

                }
            }
            else
            {

            numberOfCycles = recentlyused[counter] + numberOfCycles;
            counter = 1;
            }

            recentlyused[lowerBound] = numberOfCycles;

            if (numberOfCycles > maxCycles)
            {
            maxCycles = numberOfCycles;
            }

            lowerBound++;
        }
        System.out.println(lowerInt +" "+ upperBound+ " "+ (maxCycles+1));

    }

}
</code>```

答:
This solution gets accepted within 0.5s. I had to remove the package modifier.</p>

```<code>   import java.util.*;

    public class Main {

    static Map<Integer, Integer> map = new HashMap<>();

    private static int f(int N) {
        if (N == 1) {
            return 1;
        }

        if (map.containsKey(N)) {
            return map.get(N);
        }

        if (N % 2 == 0) {
            N >>= 1;
            map.put(N, f(N));
            return 1 + map.get(N);
        } else {
            N = 3*N + 1;
            map.put(N, f(N) );
            return 1 + map.get(N);
        }
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        try {
            while(scanner.hasNextLine()) {
                int i = scanner.nextInt();
                int j = scanner.nextInt();

                int maxx = 0;
                if (i <= j) {
                    for(int m = i; m <= j; m++) {
                        maxx = Math.max(Main.f(m), maxx);
                    }
                } else {
                    for(int m = j; m <= i; m++) {
                        maxx = Math.max(Main.f(m), maxx);
                    }
                }
                System.out.println(i + " " + j + " " + maxx);
            }
            System.exit(0);
        } catch (Exception e) {

        }

    }
}
</code>```

Title: Uva's 3n+1 problem

Body:
I'm solving Uva's 3n+1 problem and I don't get why the judge is rejecting my answer. The time limit hasn't been exceeded and the all test cases I've tried have run correctly so far.

   import java.io.*;

public class NewClass{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {

        int maxCounter= 0;
        int input;

        int lowerBound;
        int upperBound;
        int counter;
        int numberOfCycles;
        int maxCycles= 0;
        int lowerInt;
        BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
        String line = consoleInput.readLine();
        String [] splitted =  line.split(" ");

        lowerBound = Integer.parseInt(splitted[0]);
        upperBound = Integer.parseInt(splitted[1]);

        int [] recentlyused =  new int[1000001];

if (lowerBound > upperBound )
{
    int h = upperBound;
    upperBound = lowerBound;
    lowerBound = h;

}
lowerInt = lowerBound;
        while (lowerBound <= upperBound)
        {
            counter = lowerBound;
            numberOfCycles = 0;

            if (recentlyused[counter] == 0)
            {
                while ( counter != 1 )
                {

                        if (recentlyused[counter] != 0)
                        {

                        numberOfCycles = recentlyused[counter] + numberOfCycles;
                        counter = 1;
                        }
                        else
                        {
                            if (counter % 2 == 0)
                            {
                            counter = counter /2;
                            }
                            else
                            {
                            counter = 3*counter + 1;
                            }
                            numberOfCycles++;
                        }

                }
            }
            else
            {

            numberOfCycles = recentlyused[counter] + numberOfCycles;
            counter = 1;
            }

            recentlyused[lowerBound] = numberOfCycles;

            if (numberOfCycles > maxCycles)
            {
            maxCycles = numberOfCycles;
            }

            lowerBound++;
        }
        System.out.println(lowerInt +" "+ upperBound+ " "+ (maxCycles+1));

    }

}

Body:
This solution gets accepted within 0.5s. I had to remove the package modifier.

   import java.util.*;

    public class Main {

    static Map<Integer, Integer> map = new HashMap<>();

    private static int f(int N) {
        if (N == 1) {
            return 1;
        }

        if (map.containsKey(N)) {
            return map.get(N);
        }

        if (N % 2 == 0) {
            N >>= 1;
            map.put(N, f(N));
            return 1 + map.get(N);
        } else {
            N = 3*N + 1;
            map.put(N, f(N) );
            return 1 + map.get(N);
        }
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        try {
            while(scanner.hasNextLine()) {
                int i = scanner.nextInt();
                int j = scanner.nextInt();

                int maxx = 0;
                if (i <= j) {
                    for(int m = i; m <= j; m++) {
                        maxx = Math.max(Main.f(m), maxx);
                    }
                } else {
                    for(int m = j; m <= i; m++) {
                        maxx = Math.max(Main.f(m), maxx);
                    }
                }
                System.out.println(i + " " + j + " " + maxx);
            }
            System.exit(0);
        } catch (Exception e) {

        }

    }
}


问:
Does Forth support multithreading?
I had a short look at the Forth programming language for a while. Is it possible to do multithreading with synchronization primitives in Forth?

For example, is it possible to do n-by-n matrix multiplication with multiple threads in Forth? If so, what is the basic mechanism, or programming patterns?

答:
For now, Forth standard doesn't specify any multithreading or multitask related words. Although, many historic Forth implementations have such primitives, or allow to define them using Forth-assembler or API to underlying system.

As example, synchronization primitives and multithreading in SP-Forth/4 are mostly just generic wrappers over Windows and Linux (pthreads) APIs.

Note that a threads pool should be used to have better performance for small operations — since creating/destroying thread could be time-consuming operation.

Also it is possible that implementation of n-by-n matrix multiplication can get better gain from using SSE operations, or even GPU (see gpu.js for example).

In any way, the solution depends on particular Forth system.

Example (conceptual model)

Using matrices and thread-pool libraries, matrix multiplication could look like the following:

```<code>\ matrices vocabulary is in the context.

slot-enum{ m1 m2 m3 tp }slot-enum

: calc-item { r c -- }
  0e  m1 columns 0 do
    r i m1 item
    i c m2 item
    F* F+
  loop  r c m3 item!
;
: mult-matrix ( a b c -- ) \ c = a * b
  m3! m2! m1!
  \ m3 dimenisions should be m1 rows x m2 columns
  threadpool::new-group tp!
  m1 rows 0 do m2 columns 0 do
    i j 2 'calc-item tp threadpool::run
  loop
  tp threadpool::join
  tp threadpool::free
;
</code>```

Title: Does Forth support multithreading?

Body:
For now, Forth standard doesn't specify any multithreading or multitask related words. Although, many historic Forth implementations have such primitives, or allow to define them using Forth-assembler or API to underlying system.

As example, synchronization primitives and multithreading in SP-Forth/4 are mostly just generic wrappers over Windows and Linux (pthreads) APIs.

Note that a threads pool should be used to have better performance for small operations — since creating/destroying thread could be time-consuming operation.

Also it is possible that implementation of n-by-n matrix multiplication can get better gain from using SSE operations, or even GPU (see gpu.js for example).

In any way, the solution depends on particular Forth system.

Example (conceptual model)

Using matrices and thread-pool libraries, matrix multiplication could look like the following:

\ matrices vocabulary is in the context.

slot-enum{ m1 m2 m3 tp }slot-enum

: calc-item { r c -- }
  0e  m1 columns 0 do
    r i m1 item
    i c m2 item
    F* F+
  loop  r c m3 item!
;
: mult-matrix ( a b c -- ) \ c = a * b
  m3! m2! m1!
  \ m3 dimenisions should be m1 rows x m2 columns
  threadpool::new-group tp!
  m1 rows 0 do m2 columns 0 do
    i j 2 'calc-item tp threadpool::run
  loop
  tp threadpool::join
  tp threadpool::free
;