问:
Trying to merge into a dataframe but it keeps creating new columns
I am trying to open files and derive 2 columns(1 row for each) from multiple spreadsheets and then merging them to a base spreadsheet.So, the base dataframe (derived from a spreadsheet, from which I only needed 3 columns)  is like this :

```<code>Model |  Roadmap | Family
a       08/12/17  ROW
b       08/14/17  MACRO
c       08/15/17  CONN
d       08/27/17  MACRO
</code>```

The dataframes from the multiple spreadsheets(the model names are the spreadsheet names and they have multiple dates for each gate which i am deriving in multiple dataframes) and have this format :

```<code>    df1 (part1 -  the dataframe derived from the spreadsheet with model a for gate 0 ):
    Model   |  Gate 0
    a         02/01/18

df1 (Dataframe derived from the spreadsheet with model a for gate1):
        Model   |  Gate 1
        a         03/01/18

   df2 (part1):
    Model  |  Gate 0
    b       04/23/18

df2 (part1):
        Model  |  Gate 1
        b       05/23/18
</code>```

The output it produces is :

```<code>Model |  Roadmap | Family | Gate 0_x  | Gate 1_x   | gate 0_y | Gate 1_y
a       08/12/17  ROW      02/01/18   03/01/18
b       08/14/17  MACRO                              04/23/18  05/23/18
c       08/15/17  CONN
d       08/27/17  MACRO
</code>```

the output i want :

```<code>  Model |  Roadmap | Family | Gate 0   | Gate 1
   a       08/12/17  ROW     02/01/18   03/01/18
   b       08/14/17  MACRO    04/23/18  05/23/18
   ..
</code>```

The following is the code i am using:

```<code>import glob
import pandas as pd
import re
import ntpath

extension = 'xlsx'
d='Final.xlsx'
c = 'Roadmap.xlsx'
dflist = []
z=[]
result = [i for i in glob.glob('*.{}'.format(extension))]

for b in result:
    if b==c:
        base_file = pd.read_excel(b, sheet_name='Antennas', header=7)
        ind1 = base_file.set_index('Model')
        ind1 = base_file[['Model', 'Roadmap', 'Family']]
        #print(ind1)
        ind1.to_excel('Final.xlsx')
        file3 = pd.read_excel('Final.xlsx')
        file3= file3.replace(r'[,\"\']','', regex=True).replace(r'\s*([^\s]+)\s*', r'\1', regex=True)

for a in result:

        if a == c:
            base_file = pd.read_excel(a, sheet_name='Antennas', header=7)
            ind1 = base_file.set_index('Model')
            ind1 = base_file[['Model', 'Roadmap', 'Family']]
            ind1.to_excel('Final.xlsx')
        elif a != d:
            gates = ['Gate 0 Complete','Gate 1 Complete']
            file1 = pd.read_excel('Final.xlsx')
            file1= file1.replace(r'[,\"\']','', regex=True).replace(r'\s*([^\s]+)\s*', r'\1', regex=True)
            #print(file1)
            file = pd.read_excel(a, sheet_name='Timeline')
            #print(file)
            models = pd.DataFrame([['','']], columns=['Model', gates])
            for g in gates:
                z = file.loc[file['Task'] == g, 'Complete'].iloc[0]
                v=ntpath.basename(a)
                v = v[5:-5]
                models = pd.DataFrame([[v,z]], columns =['Model',g])
                file1 = pd.merge(file1, models, how='left', on='Model')
            file3 = pd.merge(file3, file1, how='left' ,['Model','Roadmap','Family'])
            file3.to_excel('new.xlsx')
</code>```

file3 is the file i have opened as the dataframe for the base file before the for loop. Let me know if anything is not clear.

答:
Currently, you are merging twice but really need to merge base with individual dfs and then append all together with pd.concat.

Below recreates your posted examples above which assumes same structure as Excel files  and demonstrates the merge and append steps. You will notice drop_duplicates is used due to the left join merges that render same row values. Keep or remove this method on actual data.

Data

```<code>from io import StringIO
import pandas as pd

txt = '''
Model  Roadmap  Family
a      some_date  some
b      some_date  some
c      some_date  some
d      some_date  some
'''
base_df = pd.read_table(StringIO(txt), sep="\s+")

txt = '''
Model  "Gate 0" "Gate 1"
    a   some_date  some
'''
df1 = pd.read_table(StringIO(txt), sep="\s+")

txt = '''
Model  "Gate 0" "Gate 1"
    b   some_date  some
'''
df2 = pd.read_table(StringIO(txt), sep="\s+")
</code>```

Merge and Append (using list comprehension)

```<code>finaldf = pd.concat([pd.merge(base_df, df, how='left', on='Model')
                    for df in [df1, df2]], ignore_index=True).drop_duplicates()

print(finaldf)
#   Model    Roadmap Family     Gate 0 Gate 1
# 0     a  some_date   some  some_date   some
# 1     b  some_date   some        NaN    NaN
# 2     c  some_date   some        NaN    NaN
# 3     d  some_date   some        NaN    NaN
# 4     a  some_date   some        NaN    NaN
# 5     b  some_date   some  some_date   some
</code>```

To integrate in your current process, consider appending individual models into a list to be concatenated and merged at the end. Build base_df as your posted example above.

```<code>...
dfList = []

for g in gates:
     z = file.loc[file['Task'] == g, 'Complete'].iloc[0]
     v = ntpath.basename(a)
     v = v[5:-5]
     mod = pd.DataFrame([[v,z]], columns =['Model',g])
     models = pd.merge(models, mod, how='left', on='Model')
dfList.append(models)

finaldf = pd.merge(base_df, pd.concat(dfList), how='left', on='Model')
finaldf.to_excel('Final_Dataset.xlsx')
</code>```

Body:
I am trying to open files and derive 2 columns(1 row for each) from multiple spreadsheets and then merging them to a base spreadsheet.So, the base dataframe (derived from a spreadsheet, from which I only needed 3 columns)  is like this :

Model |  Roadmap | Family
a       08/12/17  ROW
b       08/14/17  MACRO
c       08/15/17  CONN
d       08/27/17  MACRO

The dataframes from the multiple spreadsheets(the model names are the spreadsheet names and they have multiple dates for each gate which i am deriving in multiple dataframes) and have this format :

    df1 (part1 -  the dataframe derived from the spreadsheet with model a for gate 0 ):
    Model   |  Gate 0
    a         02/01/18

df1 (Dataframe derived from the spreadsheet with model a for gate1):
        Model   |  Gate 1
        a         03/01/18

   df2 (part1):
    Model  |  Gate 0
    b       04/23/18

df2 (part1):
        Model  |  Gate 1
        b       05/23/18

The output it produces is :

Model |  Roadmap | Family | Gate 0_x  | Gate 1_x   | gate 0_y | Gate 1_y
a       08/12/17  ROW      02/01/18   03/01/18
b       08/14/17  MACRO                              04/23/18  05/23/18
c       08/15/17  CONN
d       08/27/17  MACRO

the output i want :

  Model |  Roadmap | Family | Gate 0   | Gate 1
   a       08/12/17  ROW     02/01/18   03/01/18
   b       08/14/17  MACRO    04/23/18  05/23/18
   ..

The following is the code i am using:

import glob
import pandas as pd
import re
import ntpath

extension = 'xlsx'
d='Final.xlsx'
c = 'Roadmap.xlsx'
dflist = []
z=[]
result = [i for i in glob.glob('*.{}'.format(extension))]

for b in result:
    if b==c:
        base_file = pd.read_excel(b, sheet_name='Antennas', header=7)
        ind1 = base_file.set_index('Model')
        ind1 = base_file[['Model', 'Roadmap', 'Family']]
        #print(ind1)
        ind1.to_excel('Final.xlsx')
        file3 = pd.read_excel('Final.xlsx')
        file3= file3.replace(r'[,\"\']','', regex=True).replace(r'\s*([^\s]+)\s*', r'\1', regex=True)

for a in result:

        if a == c:
            base_file = pd.read_excel(a, sheet_name='Antennas', header=7)
            ind1 = base_file.set_index('Model')
            ind1 = base_file[['Model', 'Roadmap', 'Family']]
            ind1.to_excel('Final.xlsx')
        elif a != d:
            gates = ['Gate 0 Complete','Gate 1 Complete']
            file1 = pd.read_excel('Final.xlsx')
            file1= file1.replace(r'[,\"\']','', regex=True).replace(r'\s*([^\s]+)\s*', r'\1', regex=True)
            #print(file1)
            file = pd.read_excel(a, sheet_name='Timeline')
            #print(file)
            models = pd.DataFrame([['','']], columns=['Model', gates])
            for g in gates:
                z = file.loc[file['Task'] == g, 'Complete'].iloc[0]
                v=ntpath.basename(a)
                v = v[5:-5]
                models = pd.DataFrame([[v,z]], columns =['Model',g])
                file1 = pd.merge(file1, models, how='left', on='Model')
            file3 = pd.merge(file3, file1, how='left' ,['Model','Roadmap','Family'])
            file3.to_excel('new.xlsx')

file3 is the file i have opened as the dataframe for the base file before the for loop. Let me know if anything is not clear.

Body:
Currently, you are merging twice but really need to merge base with individual dfs and then append all together with pd.concat.

Below recreates your posted examples above which assumes same structure as Excel files  and demonstrates the merge and append steps. You will notice drop_duplicates is used due to the left join merges that render same row values. Keep or remove this method on actual data.

Data

from io import StringIO
import pandas as pd

txt = '''
Model  Roadmap  Family
a      some_date  some
b      some_date  some
c      some_date  some
d      some_date  some
'''
base_df = pd.read_table(StringIO(txt), sep="\s+")

txt = '''
Model  "Gate 0" "Gate 1"
    a   some_date  some
'''
df1 = pd.read_table(StringIO(txt), sep="\s+")

txt = '''
Model  "Gate 0" "Gate 1"
    b   some_date  some
'''
df2 = pd.read_table(StringIO(txt), sep="\s+")

Merge and Append (using list comprehension)

finaldf = pd.concat([pd.merge(base_df, df, how='left', on='Model')
                    for df in [df1, df2]], ignore_index=True).drop_duplicates()

print(finaldf)
#   Model    Roadmap Family     Gate 0 Gate 1
# 0     a  some_date   some  some_date   some
# 1     b  some_date   some        NaN    NaN
# 2     c  some_date   some        NaN    NaN
# 3     d  some_date   some        NaN    NaN
# 4     a  some_date   some        NaN    NaN
# 5     b  some_date   some  some_date   some

To integrate in your current process, consider appending individual models into a list to be concatenated and merged at the end. Build base_df as your posted example above.

...
dfList = []

for g in gates:
     z = file.loc[file['Task'] == g, 'Complete'].iloc[0]
     v = ntpath.basename(a)
     v = v[5:-5]
     mod = pd.DataFrame([[v,z]], columns =['Model',g])
     models = pd.merge(models, mod, how='left', on='Model')
dfList.append(models)

finaldf = pd.merge(base_df, pd.concat(dfList), how='left', on='Model')
finaldf.to_excel('Final_Dataset.xlsx')


来源: stackexchange

问:
Error on folder delete in Azure Portal Console
I'm attempting to manually delete a folder in my app service in Azure Portal's console. The console I'm talking about is in the portal, go to App Services > (name) > Deployment slots > (slot) > Console.

(Deploy failed to delete folder, fix is to manually delete and re-run.)

When I attempt to delete the folder, I get this:

Basically, I enter the command to delete the folder, get an "are you sure, enter Y/N", I type Y and return, and then get an error about 'Y' is not recognized as an internal or external command. Just hitting return, not entering Y, I just get a new prompt line.

What am I missing here?

答:
OH MY GOSH this is the stupidest thing.

Still don't know what's up with the delete in the Portal Console, but if you go to the KUDU console, it works just fine.

https://{your application}-{slot}.scm.azurewebsites.net/DebugConsole

ContentLicense: CC BY-SA 3.0


问:
"Class constructor cannot be invoked without 'new'" when trying to NPM publish
I have a project I'm trying to publish as an npm module. It all runs correctly on my computer, and when I import it in a different folder, I can use it without any problems, but npm publish gives me this:

```<code>npm ERR! Class constructor  cannot be invoked without 'new'

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/forrest/.npm/_logs/2017-11-09T13_21_57_362Z-debug.log
</code>```

Honestly, I don't even know where to look for this kind of error - I'm pretty sure my code isn't missing any 'new' keywords, since it runs correctly before I try to publish. If it's an npm specific problem, I haven't been able to search up anything.

How can I fix this error and publish successfully? Failing that, what kind of a problem is it and where in my code should I look?

Here's that log file:

```<code>0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'publish' ]
2 info using npm@5.5.1
3 info using node@v8.6.0
4 verbose npm-session 5adaf2e8823e5058
5 verbose publish [ '.' ]
6 info lifecycle Meristem@1.0.0~prepublish: Meristem@1.0.0
7 info lifecycle Meristem@1.0.0~prepare: Meristem@1.0.0
8 info lifecycle Meristem@1.0.0~prepublishOnly: Meristem@1.0.0
9 info lifecycle Meristem@1.0.0~prepack: Meristem@1.0.0
10 verbose tar pack [ '/var/folders/29/p2_sljq17376p_ycszkbx9rr0000gn/T/npm-35498-ea084a31/tmp/packing-340ae87b/package.tgz',
10 verbose tar pack   '.' ]
11 verbose tarball /var/folders/29/p2_sljq17376p_ycszkbx9rr0000gn/T/npm-35498-ea084a31/tmp/packing-340ae87b/package.tgz
12 verbose folder .
13 verbose stack TypeError: Class constructor  cannot be invoked without 'new'
13 verbose stack     at pack_ (/usr/local/lib/node_modules/npm/lib/utils/tar.js:213:15)
13 verbose stack     at /usr/local/lib/node_modules/npm/lib/utils/tar.js:45:7
13 verbose stack     at /usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:115:5
13 verbose stack     at /usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:402:5
13 verbose stack     at checkBinReferences_ (/usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:357:45)
13 verbose stack     at final (/usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:400:3)
13 verbose stack     at then (/usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:160:5)
13 verbose stack     at /usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:348:12
13 verbose stack     at /usr/local/lib/node_modules/npm/node_modules/graceful-fs/graceful-fs.js:78:16
13 verbose stack     at tryToString (fs.js:514:3)
13 verbose stack     at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:502:12)
14 verbose cwd /Users/forrest/web-projects/meristem
15 verbose Darwin 14.5.0
16 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "publish"
17 verbose node v8.6.0
18 verbose npm  v5.5.1
19 error Class constructor  cannot be invoked without 'new'
20 verbose exit [ 1, true ]
</code>```

And here's the code I'm trying to publish.

答:
what kind of a problem is it and where in my code should I look?

By trying the npm pack command (which creates a tarball of a package but doesn't publish it) on a simple test folder without a valid package.json but none of my code in it, I was able to discover that this was a problem with NPM itself, not with my code.

How can I fix this error and publish successfully?

Although I had updated NPM shortly before attempting to publish, I did so again (with npm install npm@latest -g), and this seems to have fixed the problem.

Body:
I have a project I'm trying to publish as an npm module. It all runs correctly on my computer, and when I import it in a different folder, I can use it without any problems, but npm publish gives me this:

npm ERR! Class constructor  cannot be invoked without 'new'

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/forrest/.npm/_logs/2017-11-09T13_21_57_362Z-debug.log

Honestly, I don't even know where to look for this kind of error - I'm pretty sure my code isn't missing any 'new' keywords, since it runs correctly before I try to publish. If it's an npm specific problem, I haven't been able to search up anything.

How can I fix this error and publish successfully? Failing that, what kind of a problem is it and where in my code should I look?

Here's that log file:

0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'publish' ]
2 info using npm@5.5.1
3 info using node@v8.6.0
4 verbose npm-session 5adaf2e8823e5058
5 verbose publish [ '.' ]
6 info lifecycle Meristem@1.0.0~prepublish: Meristem@1.0.0
7 info lifecycle Meristem@1.0.0~prepare: Meristem@1.0.0
8 info lifecycle Meristem@1.0.0~prepublishOnly: Meristem@1.0.0
9 info lifecycle Meristem@1.0.0~prepack: Meristem@1.0.0
10 verbose tar pack [ '/var/folders/29/p2_sljq17376p_ycszkbx9rr0000gn/T/npm-35498-ea084a31/tmp/packing-340ae87b/package.tgz',
10 verbose tar pack   '.' ]
11 verbose tarball /var/folders/29/p2_sljq17376p_ycszkbx9rr0000gn/T/npm-35498-ea084a31/tmp/packing-340ae87b/package.tgz
12 verbose folder .
13 verbose stack TypeError: Class constructor  cannot be invoked without 'new'
13 verbose stack     at pack_ (/usr/local/lib/node_modules/npm/lib/utils/tar.js:213:15)
13 verbose stack     at /usr/local/lib/node_modules/npm/lib/utils/tar.js:45:7
13 verbose stack     at /usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:115:5
13 verbose stack     at /usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:402:5
13 verbose stack     at checkBinReferences_ (/usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:357:45)
13 verbose stack     at final (/usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:400:3)
13 verbose stack     at then (/usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:160:5)
13 verbose stack     at /usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:348:12
13 verbose stack     at /usr/local/lib/node_modules/npm/node_modules/graceful-fs/graceful-fs.js:78:16
13 verbose stack     at tryToString (fs.js:514:3)
13 verbose stack     at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:502:12)
14 verbose cwd /Users/forrest/web-projects/meristem
15 verbose Darwin 14.5.0
16 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "publish"
17 verbose node v8.6.0
18 verbose npm  v5.5.1
19 error Class constructor  cannot be invoked without 'new'
20 verbose exit [ 1, true ]

And here's the code I'm trying to publish.


问:
Sum values from a text file and printing them
I'm trying to add the cost of books from a text file and print them. However, I'm getting [Ljava.lang.Double;@55f96302 where my values should be.

Here is my current code:

```<code>System.out.println("Welcome to the libary book search system.");
System.out.println("------------------------------------------");

if(choice.equals("Text File")) {

    //String sc = null;
    System.out.println("Title\t\t\tAuthor\t\t\tPrice\t\t\tBookPublisher\t\t\tISBN");
    System.out.println("=====\t\t\t======\t\t\t=====\t\t\t=============\t\t\t====");

    int count = 0;

    try {
        File Fileobject = new File ("E:\\text files for java\\BooksToImport.txt");
        Scanner sc = new Scanner(Fileobject);

        // Read and display each line of the file
        while(sc.hasNextLine()) {
            String line2 = sc.nextLine();
            Scanner sc2 = new Scanner(line2);
            sc2.useDelimiter("-");
            System.out.println(line2);

            while(sc2.hasNext()) {
                BookTitle[count] = sc2.next();
                System.out.println(BookTitle[count]);
                BookAuthor[count] = (sc2.next());
                System.out.println(BookAuthor[count]);
                BookPrice[count] = sc2.next();
                System.out.println(BookPrice[count]);
                BookPublisher[count] = sc2.next();
                System.out.println(BookPublisher[count]);
                ISBN[count] = sc2.next();
                System.out.println(ISBN[count]);
            }

            sc2.close();
            count++;

        }

        //for(int index=0;index<count;++index) {
            //BookPrice2[index]=Double.parseDouble(BookPrice[index]);
            //System.out.println(BookPrice2[index]);
        //}

        sc.close();
        System.out.println("----------------------");
        System.out.println("Totals of the Text File:");
        System.out.println("----------------------");
        System.out.println("Total Numbers Of Books:" + NUMBEROFBOOKS);
        System.out.println("Total Cost Of Books:"+ BookPrice2 );
        System.out.println("Maximum Cost Of A Book:");
        System.out.println("Minimum Cost Of A Book:");
        System.out.println("Average Cost Of A Book:");
        System.out.println("Total number of valid books:");
        System.out.println("Total number of invalid books:");
    } catch (FileNotFoundException e) {
            System.out.println("File does not exist");
    }
}
</code>```

Here is my text file:

```<code>The Hunger Games - Suzanne Collins - 5 - Scholastic Press - 9781921988752
OOP programming - Graham Winter - 32 - Oriely - 9876543219
Harry potter - Jk Rowling - 10 - Bloomsbury - 9788700631625
</code>```

Here is what is being displayed by my java program:

```<code>Enter what you want to do: Type 'Input' for user input or 'Text File' to read from file.

Text File

Welcome to the libary book search system.
------------------------------------------
Title           Author          Price           BookPublisher               ISBN
=====           ======          =====           =============           ====
The Hunger Games - Suzanne Collins - 5 - Scholastic Press - 9781921988752
The Hunger Games
Suzanne Collins
5
Scholastic Press
9781921988752
OOP programming - Graham Winter - 32 - Oriely - 9876543219
OOP programming
Graham Winter
32
Oriely
9876543219
Harry potter - Jk Rowling - 10 - Bloomsbury - 9788700631625
Harry potter
Jk Rowling
10
Bloomsbury
9788700631625
----------------------
Totals of the Text File:
----------------------
Total Numbers Of Books:3
Total Cost Of Books:[Ljava.lang.Double;@55f96302
Maximum Cost Of A Book:
Minimum Cost Of A Book:
Average Cost Of A Book:
Total number of valid books:
Total number of invalid books:
</code>```

答:
Finally sorted it

```<code>for (int x = 0; x < BookPrice.length; x++) {
                            total2 = total2 + Double.parseDouble(BookPrice[x]);
                        }
                        System.out.println(total2);
</code>```

Thank you all for your help. Now onto the average, minimum and maximum prices :)

Body:
I'm trying to add the cost of books from a text file and print them. However, I'm getting [Ljava.lang.Double;@55f96302 where my values should be.

Here is my current code:

System.out.println("Welcome to the libary book search system.");
System.out.println("------------------------------------------");

if(choice.equals("Text File")) {

    //String sc = null;
    System.out.println("Title\t\t\tAuthor\t\t\tPrice\t\t\tBookPublisher\t\t\tISBN");
    System.out.println("=====\t\t\t======\t\t\t=====\t\t\t=============\t\t\t====");

    int count = 0;

    try {
        File Fileobject = new File ("E:\\text files for java\\BooksToImport.txt");
        Scanner sc = new Scanner(Fileobject);

        // Read and display each line of the file
        while(sc.hasNextLine()) {
            String line2 = sc.nextLine();
            Scanner sc2 = new Scanner(line2);
            sc2.useDelimiter("-");
            System.out.println(line2);

            while(sc2.hasNext()) {
                BookTitle[count] = sc2.next();
                System.out.println(BookTitle[count]);
                BookAuthor[count] = (sc2.next());
                System.out.println(BookAuthor[count]);
                BookPrice[count] = sc2.next();
                System.out.println(BookPrice[count]);
                BookPublisher[count] = sc2.next();
                System.out.println(BookPublisher[count]);
                ISBN[count] = sc2.next();
                System.out.println(ISBN[count]);
            }

            sc2.close();
            count++;

        }

        //for(int index=0;index<count;++index) {
            //BookPrice2[index]=Double.parseDouble(BookPrice[index]);
            //System.out.println(BookPrice2[index]);
        //}

        sc.close();
        System.out.println("----------------------");
        System.out.println("Totals of the Text File:");
        System.out.println("----------------------");
        System.out.println("Total Numbers Of Books:" + NUMBEROFBOOKS);
        System.out.println("Total Cost Of Books:"+ BookPrice2 );
        System.out.println("Maximum Cost Of A Book:");
        System.out.println("Minimum Cost Of A Book:");
        System.out.println("Average Cost Of A Book:");
        System.out.println("Total number of valid books:");
        System.out.println("Total number of invalid books:");
    } catch (FileNotFoundException e) {
            System.out.println("File does not exist");
    }
}

Here is my text file:

The Hunger Games - Suzanne Collins - 5 - Scholastic Press - 9781921988752
OOP programming - Graham Winter - 32 - Oriely - 9876543219
Harry potter - Jk Rowling - 10 - Bloomsbury - 9788700631625

Here is what is being displayed by my java program:

Enter what you want to do: Type 'Input' for user input or 'Text File' to read from file.

Text File

Welcome to the libary book search system.
------------------------------------------
Title           Author          Price           BookPublisher               ISBN
=====           ======          =====           =============           ====
The Hunger Games - Suzanne Collins - 5 - Scholastic Press - 9781921988752
The Hunger Games
Suzanne Collins
5
Scholastic Press
9781921988752
OOP programming - Graham Winter - 32 - Oriely - 9876543219
OOP programming
Graham Winter
32
Oriely
9876543219
Harry potter - Jk Rowling - 10 - Bloomsbury - 9788700631625
Harry potter
Jk Rowling
10
Bloomsbury
9788700631625
----------------------
Totals of the Text File:
----------------------
Total Numbers Of Books:3
Total Cost Of Books:[Ljava.lang.Double;@55f96302
Maximum Cost Of A Book:
Minimum Cost Of A Book:
Average Cost Of A Book:
Total number of valid books:
Total number of invalid books:

Body:
Finally sorted it

for (int x = 0; x < BookPrice.length; x++) {
                            total2 = total2 + Double.parseDouble(BookPrice[x]);
                        }
                        System.out.println(total2);

Thank you all for your help. Now onto the average, minimum and maximum prices :)


问:
ng2-file-upload access-control origin issue
I have used this library for angular2 file upload https://github.com/valor-software/ng2-file-upload

Now I'm getting this error when I upload a file

XMLHttpRequest cannot load http://localhost:8080/files. Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

答:
Make withCredentials = false before uploading the item. You can put this code in ngOnInit/ constructor or ngOnChanges.

```<code>this.uploader.onBeforeUploadItem = (item) => {
  item.withCredentials = false;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Make withCredentials = false before uploading the item. You can put this code in ngOnInit/ constructor or ngOnChanges.

this.uploader.onBeforeUploadItem = (item) => {
  item.withCredentials = false;
}


问:
Marklogic Roxy: Calling a javascript module from app_specific.rb
I have a Marklogic 9 project that I'm configuring with Roxy.
I've been following these examples: https://github.com/marklogic-community/roxy/wiki/Adding-Custom-Build-Steps

Basically, I have a server-side JS function that I want to call after deploy content. I have something like this:

# then you would define your new method

```<code>  def deploy_content
    # you can optionally call the original
    original_deploy_content

    # do your stuff here
    execute_query(%Q{
      xquery version "1.0-ml";
      xdmp:javascript-eval('var process = require("/ingestion/process.sjs"); process.postDeployContent();')
    },
    :db_name => @properties["ml.app-name"] + "-content")

  end
</code>```

The xquery being called here evaluates fine when executed via query console. But when I call ml local deploy content, I get the following error:

```<code>ERROR: 500 "Internal Server Error"
ERROR: <html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>500 Internal Server Error</title>
    <meta name="robots" content="noindex,nofollow"/>
    <link rel="stylesheet" href="/error.css"/>
  </head>
  <body>
    <span class="error">
      <h1>500 Internal Server Error</h1>
      <dl>
        <dt>XDMP-MODNOTFOUND: var process = require("/ingestion/process.sjs"); process.postDeployContent(); -- Module /ingestion/process.sjs not found</dt>
        <dd></dd>
        <dt>in [anonymous], at 1:14 [javascript]</dt>
        <dd></dd>
        <dt>at 3:6,
in xdmp:eval("var process = require("/ingestion/process.sjs"); proce...") [javascript]</dt>
        <dd></dd>
        <dt>in /eval, at 3:6 [1.0-ml]</dt>
        <dd></dd>
      </dl>
    </span>
  </body>
</html>
</code>```

Why is the module not found when running via xquery from app_specific.rb?

Or... is there a better way to call a JS module function from here. Sorry, I'm not too familiar with the xquery side, so I just called a JS function instead.

答:
You need to use :app_name rather than :db_name, and pass in the name of an app-server that has the correct combination of documents database, and modules database. Otherwise the code is evaluated against the App-Services server, which runs against the out of the box, and typically empty Documents and Modules databases.

It would be nice if you could provide SJS code directly, and it would require only limited changes to Roxy. Add weight to this ticket to push its priority:

https://github.com/marklogic-community/roxy/issues/821

HTH!

Body:
I have a Marklogic 9 project that I'm configuring with Roxy.
I've been following these examples: https://github.com/marklogic-community/roxy/wiki/Adding-Custom-Build-Steps

Basically, I have a server-side JS function that I want to call after deploy content. I have something like this:

# then you would define your new method

  def deploy_content
    # you can optionally call the original
    original_deploy_content

    # do your stuff here
    execute_query(%Q{
      xquery version "1.0-ml";
      xdmp:javascript-eval('var process = require("/ingestion/process.sjs"); process.postDeployContent();')
    },
    :db_name => @properties["ml.app-name"] + "-content")

  end

The xquery being called here evaluates fine when executed via query console. But when I call ml local deploy content, I get the following error:

ERROR: 500 "Internal Server Error"
ERROR:

    <title>500 Internal Server Error</title>
    <meta name="robots" content="noindex,nofollow"/>
    <link rel="stylesheet" href="/error.css"/>

500 Internal Server Error

XDMP-MODNOTFOUND: var process = require("/ingestion/process.sjs"); process.postDeployContent(); -- Module /ingestion/process.sjs not found

in [anonymous], at 1:14 [javascript]

at 3:6,
in xdmp:eval("var process = require(&quot;/ingestion/process.sjs&quot;); proce...") [javascript]

in /eval, at 3:6 [1.0-ml]

Why is the module not found when running via xquery from app_specific.rb?

Or... is there a better way to call a JS module function from here. Sorry, I'm not too familiar with the xquery side, so I just called a JS function instead.


问:
generic data frame update function with tidyverse dplyr like sql-update
I search for a generic data frame update function like the sql-update that updates values in the first data frame in case the keys match with the keys in the second data frame. Is there a more generic way as in my example, maybe also by considering the value names? Something like a generic dplyr::update(df1, df2, by = "key") function?</p>

```<code>library(tidyverse)
# example data frame
df1 <- as_data_frame(list(key = c(1,2,3,4,5,6,7,8,9),
                          v1 = c(11,12,13,14,15,16,17,18,19),
                          v2 = c(21,22,23,24,25,26,27,28,29),
                          v3 = c(31,32,33,34,35,36,37,38,39),
                          v4 = c(41,42,43,44,45,46,47,48,49)))
df2 <- as_data_frame(list(key = c(3,5,9),
                          v2 = c(231,252,293),
                          v4 = c(424,455,496)))

# update df1 with values from df2 where key match
org_names <- df1 %>% names()
df1 <- df1 %>%
  left_join(df2, by = "key") %>%
  mutate(v2 = ifelse(is.na(v2.y), v2.x, v2.y),
         v4 = ifelse(is.na(v4.y), v4.x, v4.y)) %>%
  select(org_names)

> df1
# A tibble: 9 x 5
key    v1    v2    v3    v4
<dbl> <dbl> <dbl> <dbl> <dbl>
1     1    11    21    31    41
2     2    12    22    32    42
3     3    13   231    33   424
4     4    14    24    34    44
5     5    15   252    35   455
6     6    16    26    36    46
7     7    17    27    37    47
8     8    18    28    38    48
9     9    19   293    39   496
>
</code>```

答:
1) %<>% Magrittr has the compound assignment pipe:

```<code>library(magrittr)

df1 %>%
    { keys <- intersect(.$key, df2$key)
    .[match(keys, .$key), names(df2)] %<>% { df2[match(keys, df2$key), ] }
    .
}
</code>```

which, for the problem under consideration, simplifies to this because all keys in df2 are in df1:

```<code>df1 %>% { .[match(df2$key, .$key), names(df2)]  %<>% { df2 }; . }
</code>```

2) <- The basic R assignment operator could also be used in much the same way and, in fact, the code is shorter than (1):

```<code>df1 %>%
    { keys <- intersect(.$key, df2$key)
    .[match(keys, .$key), names(df2)] <- df2[match(keys, df2$key), ]
    .
}
</code>```

however, for the problem under consideration all keys in df2 are in df1 so it simplifies to:

```<code>df1 %>% { .[match(df2$key, .$key), names(df2)] <- df2; . }
</code>```

3) mutate_cond Using mutate_cond defined in this SO post we can write the following.

```<code>df1 %>% mutate_cond(.$key %in% df2$key, v2 = df2$v2, v4 = df2$v4)
</code>```

Note:  The first two approaches work if the keys in df1 and df2 are each unique. The third additionally requires the keys be in the same order and every key in df2 be in df1.  The problem in the question satisfies these.

Update: Have somewhat generalized the code in (1) and (2).

Body:
I search for a generic data frame update function like the sql-update that updates values in the first data frame in case the keys match with the keys in the second data frame. Is there a more generic way as in my example, maybe also by considering the value names? Something like a generic dplyr::update(df1, df2, by = "key") function?

library(tidyverse)
# example data frame
df1 <- as_data_frame(list(key = c(1,2,3,4,5,6,7,8,9),
                          v1 = c(11,12,13,14,15,16,17,18,19),
                          v2 = c(21,22,23,24,25,26,27,28,29),
                          v3 = c(31,32,33,34,35,36,37,38,39),
                          v4 = c(41,42,43,44,45,46,47,48,49)))
df2 <- as_data_frame(list(key = c(3,5,9),
                          v2 = c(231,252,293),
                          v4 = c(424,455,496)))

# update df1 with values from df2 where key match
org_names <- df1 %>% names()
df1 <- df1 %>%
  left_join(df2, by = "key") %>%
  mutate(v2 = ifelse(is.na(v2.y), v2.x, v2.y),
         v4 = ifelse(is.na(v4.y), v4.x, v4.y)) %>%
  select(org_names)

> df1
# A tibble: 9 x 5
key    v1    v2    v3    v4
<dbl> <dbl> <dbl> <dbl> <dbl>
1     1    11    21    31    41
2     2    12    22    32    42
3     3    13   231    33   424
4     4    14    24    34    44
5     5    15   252    35   455
6     6    16    26    36    46
7     7    17    27    37    47
8     8    18    28    38    48
9     9    19   293    39   496
>

Body:
1) %<>% Magrittr has the compound assignment pipe:

library(magrittr)

df1 %>%
    { keys <- intersect(.$key, df2$key)
    .[match(keys, .$key), names(df2)] %<>% { df2[match(keys, df2$key), ] }
    .
}

which, for the problem under consideration, simplifies to this because all keys in df2 are in df1:

df1 %>% { .[match(df2$key, .$key), names(df2)]  %<>% { df2 }; . }

2) <- The basic R assignment operator could also be used in much the same way and, in fact, the code is shorter than (1):

df1 %>%
    { keys <- intersect(.$key, df2$key)
    .[match(keys, .$key), names(df2)] <- df2[match(keys, df2$key), ]
    .
}

however, for the problem under consideration all keys in df2 are in df1 so it simplifies to:

df1 %>% { .[match(df2$key, .$key), names(df2)] <- df2; . }

3) mutate_cond Using mutate_cond defined in this SO post we can write the following.

df1 %>% mutate_cond(.$key %in% df2$key, v2 = df2$v2, v4 = df2$v4)

Note:  The first two approaches work if the keys in df1 and df2 are each unique. The third additionally requires the keys be in the same order and every key in df2 be in df1.  The problem in the question satisfies these.

Update: Have somewhat generalized the code in (1) and (2).


问:
Allow locally built snapshots to override more recent remote snapshots
We have a large multi-module maven project. With the objective of increasing development productivity, we recently started to deploy snapshots to a remote repository (via central build) and introduced maven profiles that mean users only need to check out and build a sub-set of modules and take snapshots for the rest. We have also set our update policy on remote repositories to 'never', to ensure that it is explicit when we want to update local snapshots. A typical command is thus; mvn -Pref -U clean install.

Now, in the maven reactor, the build for the modules defined in the profile works perfectly, maven using snapshots for their dependencies, including downloading any updated ones from the remote repository (important note; to ensure we have a consistent set of snapshots, our central deploy is of all module snapshots from our project, even if only a couple of them have changed).

The hitch seems to be when maven is then resolving dependencies back to those locally built modules from modules that exist outside the profile - if a snapshot has been deployed remotely since the build of such a module, then maven sees this as a more up to date version and proceeds to download and overwrite the locally built snapshot. This can cause breaks where other modules are expecting the locally changed module.

Basically I would like to have an option like 'use locally built snapshot' within any modules in my profile over any remote snapshot, even though the timestamp indicates that the remote snapshot is more recent.

What have other people done in this scenario?

thanks,

Paul

答:
I know this is very old, but came across the same problem and solved it by splitting the build into two steps:

mvn -U dependency:tree

mvn test

The first step does the snapshot update without building anything and runs very fast.

Then the second step is a regular build/test, but WITHOUT updatig snapshots.


问:
Dataframes: Replace Value in Column If 2 Separate Conditions are Met
Logic I'm trying to implement:

If 'phasename' column contains C1, C2, C4, or C18 AND 'reqmnt' column contains C

Replace C in requirement column with value in 'phasename' column

Otherwise leave 'reqmnt' column as is

Below is a sample screen shot of what I'm trying to do

Currently, I'm not able to figure out how to incorporate the "and" condition into my python code.  So I'm getting the results from current_column in the screen shot.

```<code># create mapping dictionary
phasename_dictionary = {'C1':'C1', 'C2':'C2', 'C4':'C4', 'C18':'C18'}
# replace column value
df.loc[df['phasename'].isin(phasename_dictionary.keys()), 'reqmnt'] = \
       df['phasename'].map(phasename_dictionary)
</code>```

答:
I think you're looking for np.where:

```<code>v = ['C1', 'C2', 'C4', 'C18']
df.reqmnt = np.where(df.phasename.isin(v) & df.reqmnt.eq('C'), df.phasename, df.reqmnt)
</code>```

Body:
Logic I'm trying to implement:

If 'phasename' column contains C1, C2, C4, or C18 AND 'reqmnt' column contains C

Replace C in requirement column with value in 'phasename' column

Otherwise leave 'reqmnt' column as is

Below is a sample screen shot of what I'm trying to do

Currently, I'm not able to figure out how to incorporate the "and" condition into my python code.  So I'm getting the results from current_column in the screen shot.

# create mapping dictionary
phasename_dictionary = {'C1':'C1', 'C2':'C2', 'C4':'C4', 'C18':'C18'}
# replace column value
df.loc[df['phasename'].isin(phasename_dictionary.keys()), 'reqmnt'] = \
       df['phasename'].map(phasename_dictionary)

Body:
I think you're looking for np.where:

v = ['C1', 'C2', 'C4', 'C18']
df.reqmnt = np.where(df.phasename.isin(v) & df.reqmnt.eq('C'), df.phasename, df.reqmnt)


问:
java.lang.Class java.lang.Object.getClass()' on a null object reference
I try to use viewPager with the tablayout but when i set adapter with the view pager i'm getting error "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass() on a null object reference" i don't understand why this error is show.

view pager set Adapter:

```<code>viewPager= (ViewPager) findViewById(R.id.viewPager_id);
  viewPager.setAdapter(newViewPagerAdapterUseThisClass(getSupportFragmentManager(),14));
</code>```

Adapter clss:

```<code>class ViewPagerAdapterUseThisClass extends FragmentPagerAdapter {
    int countTabItem;
     ViewPagerAdapterUseThisClass(FragmentManager fm,int contTabItem) {
        super(fm);

        this.countTabItem=contTabItem;
    }

    @Override
    public Fragment getItem(int position) {

        if(position==0){
            EnthusamTab enthusamTab=new EnthusamTab();
            return enthusamTab;
        }

        return null;
    }

    @Override
    public int getCount() {
        return countTabItem;
    }
}
</code>```

view pager xml file:

```<code> <android.support.v4.view.ViewPager
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/tab_layout_id"
            android:id="@+id/viewPager_id"/>
</code>```

Error log:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
                                                                                at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:380)
                                                                                at android.support.v4.app.BackStackRecord.add(BackStackRecord.java:375)
                                                                                at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:103)
                                                                                at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1034)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1248)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1116)
                                                                                at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1642)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                                                at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1081)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at com.android.internal.policy.DecorView.onMeasure(DecorView.java:689)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2275)
                                                                                at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1366)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1619)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6343)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                                                at android.view.Choreographer.doFrame(Choreographer.java:621)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6126)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

答:
This error usually comes when you have few fragments to return than the count specified. Like for example, returning count=3, and you return null on the second position.
Please note that count is a zero based index.</p>

Body:
I try to use viewPager with the tablayout but when i set adapter with the view pager i'm getting error "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass() on a null object reference" i don't understand why this error is show.

view pager set Adapter:

viewPager= (ViewPager) findViewById(R.id.viewPager_id);
  viewPager.setAdapter(newViewPagerAdapterUseThisClass(getSupportFragmentManager(),14));

Adapter clss:

class ViewPagerAdapterUseThisClass extends FragmentPagerAdapter {
    int countTabItem;
     ViewPagerAdapterUseThisClass(FragmentManager fm,int contTabItem) {
        super(fm);

        this.countTabItem=contTabItem;
    }

    @Override
    public Fragment getItem(int position) {

        if(position==0){
            EnthusamTab enthusamTab=new EnthusamTab();
            return enthusamTab;
        }

        return null;
    }

    @Override
    public int getCount() {
        return countTabItem;
    }
}

view pager xml file:

 <android.support.v4.view.ViewPager
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/tab_layout_id"
            android:id="@+id/viewPager_id"/>

Error log:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
                                                                                at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:380)
                                                                                at android.support.v4.app.BackStackRecord.add(BackStackRecord.java:375)
                                                                                at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:103)
                                                                                at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1034)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1248)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1116)
                                                                                at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1642)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                                                at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1081)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at com.android.internal.policy.DecorView.onMeasure(DecorView.java:689)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2275)
                                                                                at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1366)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1619)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6343)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                                                at android.view.Choreographer.doFrame(Choreographer.java:621)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6126)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)


问:
Checking to see if a name is in a notepad text document for an A.I system.
I have looked over the answers given on other questions. But they are not making any sense to me sorry. I have a notepad document that I want to check to see if the name that you give the program is in the document and if it is. it says hello and let you access the program and lets you do stuff. If your name is not it the program I want it to say that you do not have an account and ask you if you want to make an account and if you say yes then you give it your name and it adds it to the text document. The problem that I am having is that it does not see if your name is in the text document but when you print the names it gives you them and they look like this. <code>'Coryn\n'</code> and I have no clue what this means. My code is down below. </p>

```<code>def AI():
    name = raw_input("Hello my name is Cora I am an artificial helper. What is your name? ")
    yes1 = ""
    name_list = list(open('r','\\\\ph-fss1\\Students\\S39055\\Desktop\\names.txt'))
    for names in name_list:
        if name in name_list:
            print "Welcome back sir"
        else:
            yes1 = raw_input("You do not have an account do you wish to make one? yes/no ").lower()
        if yes1 == "no":
            break
        if yes1 == "yes":
            name('w',open('\\\\ph-fss1\\Students\\S39055\\Desktop\\names.txt'))
</code>```

答: You need to split the lines to make them 'readable' for the AI. str.splitlines Docs</p>

Body:
I have looked over the answers given on other questions. But they are not making any sense to me sorry. I have a notepad document that I want to check to see if the name that you give the program is in the document and if it is. it says hello and let you access the program and lets you do stuff. If your name is not it the program I want it to say that you do not have an account and ask you if you want to make an account and if you say yes then you give it your name and it adds it to the text document. The problem that I am having is that it does not see if your name is in the text document but when you print the names it gives you them and they look like this. 'Coryn\n' and I have no clue what this means. My code is down below.

def AI():
    name = raw_input("Hello my name is Cora I am an artificial helper. What is your name? ")
    yes1 = ""
    name_list = list(open('r','\\\\ph-fss1\\Students\\S39055\\Desktop\\names.txt'))
    for names in name_list:
        if name in name_list:
            print "Welcome back sir"
        else:
            yes1 = raw_input("You do not have an account do you wish to make one? yes/no ").lower()
        if yes1 == "no":
            break
        if yes1 == "yes":
            name('w',open('\\\\ph-fss1\\Students\\S39055\\Desktop\\names.txt'))


问:
How to sync repo in bitbucket to S3 with jenkins
Background: I have a repository say example.com along with master and develop branch. My master branch repo push the change to /efs/prod through jenkins build and develop branch repo push the change to /efs/qa through jenkins build. Now I have setup a folder say /s3 in my develop branch of repo to push the changes to amazon S3, for this I have used "Publish Artifacts to S3 Bucket" plugin in jenkins.

Requirement: I am able to move the bitbucket uploads to aws s3 but when someone delete the file in bitbucket repo then I am unable to sync it with AWS s3.
I have followed below source to move the repo changes to s3

```<code>http://www.devops-share.com/upload-builds-from-jenkins-to-s3/
</code>```

Could someone let me know how could I make jenkins to sync the bitbucket repo with S3.

答:
I have resolved it by using below command at Build>Execute shell in jenkins</p>

```<code>aws s3 sync --delete cdn/ s3://bucket-path
</code>```

Body:
Background: I have a repository say example.com along with master and develop branch. My master branch repo push the change to /efs/prod through jenkins build and develop branch repo push the change to /efs/qa through jenkins build. Now I have setup a folder say /s3 in my develop branch of repo to push the changes to amazon S3, for this I have used "Publish Artifacts to S3 Bucket" plugin in jenkins.

Requirement: I am able to move the bitbucket uploads to aws s3 but when someone delete the file in bitbucket repo then I am unable to sync it with AWS s3.
I have followed below source to move the repo changes to s3

http://www.devops-share.com/upload-builds-from-jenkins-to-s3/

Could someone let me know how could I make jenkins to sync the bitbucket repo with S3.

Body:
I have resolved it by using below command at Build>Execute shell in jenkins

aws s3 sync --delete cdn/ s3://bucket-path


问:
how do i create a custom navigation bar in xamarin forms for Android
how do i create a custom navigation bar like this in xamarin forms for Android?

I have tried using CustomNavigationRenderer and have got a reference to SupportActionBar(it is not null in the activity, nor the NavigationRenderer), But when i try to apply any changes to the actionbar, it doesn't do anything. I am using FormsAppCompatActivity.

答:
try below to customise the navigation bar on Android

```<code>[assembly: ExportRenderer(typeof(NavigationPage), typeof(CustomeNavigationPageRenderer))]
namespace Trainer.Droid.AndroidControls
{
public class CustomeNavigationPageRenderer : NavigationPageRenderer
{
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>
(Resource.Id.toolbar);
for (var i = 0; i < toolbar.ChildCount; i++)
{
var imageButton = toolbar.GetChildAt(i) as ImageButton;

        var drawerArrow = imageButton?.Drawable as DrawerArrowDrawable;
        if (drawerArrow == null)
            continue;

        imageButton.SetImageDrawable(Forms.Context.GetDrawable(Resource.Drawable.menu_icon));
    }
}
}
}
</code>```

where "menu_icon" is any icon or image of your choice

& Set the Tile by this

```<code>Title = "Search Test";
</code>```

and on the left of your toolbar like this

```<code>ToolbarItem new_tb = new ToolbarItem
        {
            Icon = "cart.png",

            Order = ToolbarItemOrder.Primary,
            Command = new Command(() => root())
        };

        ToolbarItems.Add(new_tb);
</code>```

Body:
try below to customise the navigation bar on Android

[assembly: ExportRenderer(typeof(NavigationPage), typeof(CustomeNavigationPageRenderer))]
namespace Trainer.Droid.AndroidControls
{
public class CustomeNavigationPageRenderer : NavigationPageRenderer
{
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>
(Resource.Id.toolbar);
for (var i = 0; i < toolbar.ChildCount; i++)
{
var imageButton = toolbar.GetChildAt(i) as ImageButton;

        var drawerArrow = imageButton?.Drawable as DrawerArrowDrawable;
        if (drawerArrow == null)
            continue;

        imageButton.SetImageDrawable(Forms.Context.GetDrawable(Resource.Drawable.menu_icon));
    }
}
}
}

where "menu_icon" is any icon or image of your choice

& Set the Tile by this

Title = "Search Test";

and on the left of your toolbar like this

ToolbarItem new_tb = new ToolbarItem
        {
            Icon = "cart.png",

            Order = ToolbarItemOrder.Primary,
            Command = new Command(() => root())
        };

        ToolbarItems.Add(new_tb);


问:
Linq to SQL query not returning expected results
Can anyone explain to me why these two are different functionally?

The first returns null on my sample data, and the second returns the expected result. I put the + @"" part in to avoid calling replace on a null string.

Code always returns null on my sample data:

```<code>to_follows_contact = db.CONTACTs.Where(n =>
    n.ACCOUNTID == account.ACCOUNTID
    && (
        (n.FIRSTNAME + n.MIDDLENAME + n.LASTNAME + @"").Replace(@" ", @"")
                                                            == @"TOFOLLOW"
        ||
        (n.FIRSTNAME + n.MIDDLENAME + n.LASTNAME + @"").Replace(@" ", @"")
                                                            == @"FOLLOWTO"
    )
).FirstOrDefault();
</code>```

Code returns correct contact on my sample data:

```<code>foreach (CONTACT n in db.CONTACTs.Where(n => n.ACCOUNTID == account.ACCOUNTID))
{
    string ContactName = (n.FIRSTNAME + n.MIDDLENAME + n.LASTNAME + @"")
                         .Replace(@" ", @"");
    if (ContactName == @"TOFOLLOW" || ContactName == @"FOLLOWTO")
        to_follows_contact = n;
}
</code>```

答:
At a guess, the generated SQL will concatenate the various strings, however, if one of them is null, then you'll always get NULL returned from the concatenation, which will fail to pass your equality test.

In the code, the strings will always be empty, which will then work.

ContentLicense: CC BY-SA 2.5

Body:
Can anyone explain to me why these two are different functionally?

The first returns null on my sample data, and the second returns the expected result. I put the + @"" part in to avoid calling replace on a null string.

Code always returns null on my sample data:

to_follows_contact = db.CONTACTs.Where(n =>
    n.ACCOUNTID == account.ACCOUNTID
    && (
        (n.FIRSTNAME + n.MIDDLENAME + n.LASTNAME + @"").Replace(@" ", @"")
                                                            == @"TOFOLLOW"
        ||
        (n.FIRSTNAME + n.MIDDLENAME + n.LASTNAME + @"").Replace(@" ", @"")
                                                            == @"FOLLOWTO"
    )
).FirstOrDefault();

Code returns correct contact on my sample data:

foreach (CONTACT n in db.CONTACTs.Where(n => n.ACCOUNTID == account.ACCOUNTID))
{
    string ContactName = (n.FIRSTNAME + n.MIDDLENAME + n.LASTNAME + @"")
                         .Replace(@" ", @"");
    if (ContactName == @"TOFOLLOW" || ContactName == @"FOLLOWTO")
        to_follows_contact = n;
}


问:
PhantomJS, generated PDF file size is different on local in compare with aws-lambda
I am using PhantomJS to convert web page to PDF.
When I run the code in my development environment the output file size is around few KB but when I run the same code on AWS-Lambda the output file size is around few MB.

I want to generate a pdf file with the same size of dev environment.

Here is the code I am using for conversion

```<code>var system = require('system');
var page = require('webpage').create();

page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36';

var url = system.args[1];
var file_name = system.args[2]
var margin = system.args[3];

page.paperSize = {
    format: 'A2',
    orientation: 'portrait',
    margin:  JSON.parse(margin)
};

page.evaluate(function () {
    var style = document.createElement('style');
    style.innerHTML = '.card-padding{padding-top: 0;padding-bottom: 0;}';
    document.body.appendChild(style);
})

page.open(url, function start(status) {
    window.setTimeout(function () {
        page.render(file_name, {format: 'pdf'});
        system.stdout.write(file_name)
        phantom.exit();
    }, 5000);
});
</code>```

I also tried to set the page dpi

```<code>page.open(url, function start(status) {
    window.setTimeout(function () {
        page.dpi=72
        page.render(file_name, {format: 'pdf'});
        system.stdout.write(file_name)
        phantom.exit();
    }, 5000);
})
</code>```

but it didn't help.
You can find the project here

答:
Solution is;

create a .fonts folder

put the fonts you are using in PDF in .fonts folder

Add enviroment variable to lambda HOME = /var/task

it significantly reduces the file size.

What was the issue;

PhantomJs v2.1.x on debian and ubuntu at least handles local fonts correctly, i.e, they are embedded in the pdf and therefore rendered on screen in high quality, the text is searchable and selectable and the file size is kept low. For remote webfonts, the text is converted to outlines, fonts are not embedded and text doesn't search and selectable, and makes the file size huge for longer docs.

Body:
I am using PhantomJS to convert web page to PDF.
When I run the code in my development environment the output file size is around few KB but when I run the same code on AWS-Lambda the output file size is around few MB.

I want to generate a pdf file with the same size of dev environment.

Here is the code I am using for conversion

var system = require('system');
var page = require('webpage').create();

page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36';

var url = system.args[1];
var file_name = system.args[2]
var margin = system.args[3];

page.paperSize = {
    format: 'A2',
    orientation: 'portrait',
    margin:  JSON.parse(margin)
};

page.evaluate(function () {
    var style = document.createElement('style');
    style.innerHTML = '.card-padding{padding-top: 0;padding-bottom: 0;}';
    document.body.appendChild(style);
})

page.open(url, function start(status) {
    window.setTimeout(function () {
        page.render(file_name, {format: 'pdf'});
        system.stdout.write(file_name)
        phantom.exit();
    }, 5000);
});

I also tried to set the page dpi

page.open(url, function start(status) {
    window.setTimeout(function () {
        page.dpi=72
        page.render(file_name, {format: 'pdf'});
        system.stdout.write(file_name)
        phantom.exit();
    }, 5000);
})

but it didn't help.
You can find the project here


问:
SQL WHERE Like Clause not returning all results
I have a strange one that I have been scratching my head over for the past few hours.

I have a relatively simple TSQL

```<code>SELECT
  LTRIM(RTRIM(bom_comp_code)) [bom_comp_code]
  , bom_product
  , bom.actual_partnumber
FROM
  dbo.MRP_ALL bom
WHERE
  bom.bom_product = 'F00434'
</code>```

This returns 500 rows of a result like - perfect

```<code>[bom_comp_code]  [bom_product]  [actual_partnumber]
M03275           F00434         99292922
M03275           F00434         99292922
B01869           F00434         99292922
B01869           F00434         99292922
M03275           F00434         99292922
M03275           F00434         99292922
B01869           F00434         99292922
...
...
B01869           F00434         99292922
B01869           F00434         99292922
M03275           F00434         1110-011
M03275           F00434         1110-011
</code>```

Now I am only interested in bom_comp_code that start with an M, so naturally I use the following TSQL

```<code>SELECT
  LTRIM(RTRIM(bom_comp_code)) [bom_comp_code]
  , bom_product
  , bom.actual_partnumber
FROM
  dbo.MRP_ALL bom
WHERE
  bom.bom_product = 'F00434'
AND LTRIM(RTRIM(bom.bom_comp_code)) like 'M%'
</code>```

But this only returns one row!

```<code>[bom_comp_code]  [bom_product]  [actual_partnumber]
M03275           F00434         1110-011
</code>```

I cannot for the life of me understand why only one row is returned when there are 224 in the table that match my criteria

The LTRIM / RTRIM was me thinking there was whitespace around the bom_comp_code field, but this did not work.

I have also tried this around bom_product too just in case.

What could possible be stopping all my rows from returning?

答:
USE LEFT()

```<code>AND LEFT(bom_comp_code, 1) = 'M'
</code>```

And if you really have spaces

```<code>AND LEFT(LTRIM(bom_comp_code), 1) = 'M'
</code>```

To check if you have special character at begining of your string then debug like this

```<code>SELECT LEFT(LTRIM(bom_comp_code), 1) as first_char,
       ASCII (LEFT(LTRIM(bom_comp_code), 1)) as ascii_number
       LTRIM(bom_comp_code)
FROM dbo.MRP_ALL bom
</code>```

Body:
I have a strange one that I have been scratching my head over for the past few hours.

I have a relatively simple TSQL

SELECT
  LTRIM(RTRIM(bom_comp_code)) [bom_comp_code]
  , bom_product
  , bom.actual_partnumber
FROM
  dbo.MRP_ALL bom
WHERE
  bom.bom_product = 'F00434'

This returns 500 rows of a result like - perfect

[bom_comp_code]  [bom_product]  [actual_partnumber]
M03275           F00434         99292922
M03275           F00434         99292922
B01869           F00434         99292922
B01869           F00434         99292922
M03275           F00434         99292922
M03275           F00434         99292922
B01869           F00434         99292922
...
...
B01869           F00434         99292922
B01869           F00434         99292922
M03275           F00434         1110-011
M03275           F00434         1110-011

Now I am only interested in bom_comp_code that start with an M, so naturally I use the following TSQL

SELECT
  LTRIM(RTRIM(bom_comp_code)) [bom_comp_code]
  , bom_product
  , bom.actual_partnumber
FROM
  dbo.MRP_ALL bom
WHERE
  bom.bom_product = 'F00434'
AND LTRIM(RTRIM(bom.bom_comp_code)) like 'M%'

But this only returns one row!

[bom_comp_code]  [bom_product]  [actual_partnumber]
M03275           F00434         1110-011

I cannot for the life of me understand why only one row is returned when there are 224 in the table that match my criteria

The LTRIM / RTRIM was me thinking there was whitespace around the bom_comp_code field, but this did not work.

I have also tried this around bom_product too just in case.

What could possible be stopping all my rows from returning?

Body:
USE LEFT()

AND LEFT(bom_comp_code, 1) = 'M'

And if you really have spaces

AND LEFT(LTRIM(bom_comp_code), 1) = 'M'

To check if you have special character at begining of your string then debug like this

SELECT LEFT(LTRIM(bom_comp_code), 1) as first_char,
       ASCII (LEFT(LTRIM(bom_comp_code), 1)) as ascii_number
       LTRIM(bom_comp_code)
FROM dbo.MRP_ALL bom


问:
How to extract the month, day of month and IP address from the line using sed or awk?
I have extracted the day/month and IP that are continuously bruteforcing my IMAP server:

```<code>Nov1 unknown[186.216.99.239]:
Nov1 unknown[62.249.196.214]:
Nov1 unknown[110.145.123.120]:
Nov1 fixed-187-190-251-149.totalplay.net[187.190.251.149]:
Nov1 pd9568164.dip0.t-ipconnect.de[217.86.129.100]:
Nov1 unknown[103.227.88.130]:
</code>```

I want the output to be like below:

```<code>Nov1 186.216.99.239
Nov1 62.249.196.214
Nov1 110.145.123.120
Nov1 187.190.251.149
Nov1 217.86.129.100
Nov1 103.227.88.130
</code>```

I achieved this result using combination of sed, awk and cut with below code, but I would like to learn if there are better ways?

```<code>while read -r line
    do
        monthday=$(echo $line | awk '{ print $1 }')
        # ip=$(echo $line | awk -F'[\\\[\\\]]' { print $2 } )
        ip=$(echo $line| cut -d[ -f2| cut -d] -f1 )
        echo "${monthday} ${ip}"
    done < badIpList.txt
</code>```

Body:
I have extracted the day/month and IP that are continuously bruteforcing my IMAP server:

Nov1 unknown[186.216.99.239]:
Nov1 unknown[62.249.196.214]:
Nov1 unknown[110.145.123.120]:
Nov1 fixed-187-190-251-149.totalplay.net[187.190.251.149]:
Nov1 pd9568164.dip0.t-ipconnect.de[217.86.129.100]:
Nov1 unknown[103.227.88.130]:

I want the output to be like below:

Nov1 186.216.99.239
Nov1 62.249.196.214
Nov1 110.145.123.120
Nov1 187.190.251.149
Nov1 217.86.129.100
Nov1 103.227.88.130

I achieved this result using combination of sed, awk and cut with below code, but I would like to learn if there are better ways?

while read -r line
    do
        monthday=$(echo $line | awk '{ print $1 }')
        # ip=$(echo $line | awk -F'[\\\[\\\]]' { print $2 } )
        ip=$(echo $line| cut -d[ -f2| cut -d] -f1 )
        echo "${monthday} ${ip}"
    done < badIpList.txt

Body:
Simple with this sed:

$ sed -r 's|^([^ ]*)[^[]*\[([^]]*)\].*|\1 \2|' badIpList.txt
Nov1 186.216.99.239
Nov1 62.249.196.214
Nov1 110.145.123.120
Nov1 187.190.251.149
Nov1 217.86.129.100
Nov1 103.227.88.130

Logic: Print the first word and the contents of the square bracket.


问:
Swift's Decimal precision issue
According to the docs here, Swift 3/4 Decimal type is a representation in base 10 bridged to NSDecimalNumber. However I'm having precision issues that do not reproduce when using NSDecimalNumber.

```<code>let dec24 = Decimal(integerLiteral: 24)
let dec1 = Decimal(integerLiteral: 1)
let decResult = dec1/dec24*dec24
// prints 0.99999999999999999999999999999999999984

let dn24 = NSDecimalNumber(value: 24)
let dn1 = NSDecimalNumber(value: 1)
let dnResult = dn1.dividing(by: dn24).multiplying(by: dn24)
// prints 1
</code>```

Shouldn't the Decimal struct be accurate, or am I misunderstanding something?

答:
The problem is simply an artefact of the way Playground formats numbers.

I typed this into Playground

```<code>import Foundation

let dn1 = Decimal(integerLiteral: 1)
let dn24 = Decimal(integerLiteral: 24)
let decResult = dn1 / dn24 * dn24
print(decResult)

let nsdn1 = NSDecimalNumber(value: 1)
let nsdn24 = NSDecimalNumber(value: 24)

let nsdecResult = nsdn1.dividing(by: nsdn24).multiplying(by: nsdn24)
print(nsdecResult)
</code>```

Playground displays the number on the right hand side as 0.99999999999999999999999999999999999984 for the first calculation  and 1 for the second calculation. However, both print statements printed 0.99999999999999999999999999999999999984.

Here's a picture to prove it:

Oh, and the reason why the calculation produces 0.99999999999999999999999999999999999984instead of 1 is because (as Martin R says) 1/24 cannot be represented exactly as a Decimal.

Title: Swift's Decimal precision issue

Body:
According to the docs here, Swift 3/4 Decimal type is a representation in base 10 bridged to NSDecimalNumber. However I'm having precision issues that do not reproduce when using NSDecimalNumber.

let dec24 = Decimal(integerLiteral: 24)
let dec1 = Decimal(integerLiteral: 1)
let decResult = dec1/dec24*dec24
// prints 0.99999999999999999999999999999999999984

let dn24 = NSDecimalNumber(value: 24)
let dn1 = NSDecimalNumber(value: 1)
let dnResult = dn1.dividing(by: dn24).multiplying(by: dn24)
// prints 1

Shouldn't the Decimal struct be accurate, or am I misunderstanding something?

Body:
The problem is simply an artefact of the way Playground formats numbers.

I typed this into Playground

import Foundation

let dn1 = Decimal(integerLiteral: 1)
let dn24 = Decimal(integerLiteral: 24)
let decResult = dn1 / dn24 * dn24
print(decResult)

let nsdn1 = NSDecimalNumber(value: 1)
let nsdn24 = NSDecimalNumber(value: 24)

let nsdecResult = nsdn1.dividing(by: nsdn24).multiplying(by: nsdn24)
print(nsdecResult)

Playground displays the number on the right hand side as 0.99999999999999999999999999999999999984 for the first calculation  and 1 for the second calculation. However, both print statements printed 0.99999999999999999999999999999999999984.

Here's a picture to prove it:

Oh, and the reason why the calculation produces 0.99999999999999999999999999999999999984instead of 1 is because (as Martin R says) 1/24 cannot be represented exactly as a Decimal.


问:
Convert Soap XML response to Object
i'm new to working with SOAP API's

I have a soap response from an API

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<LoginResponse xmlns="http://test.org/ADMail_Service">
<LoginResult>
<ErrorMessage>Successful login</ErrorMessage>
<Status>true</Status>
</LoginResult>
</LoginResponse>
</soapenv:Body>
</soapenv:Envelope>
</code>```

I'm trying to transform this into an object.

From reading articles online I'm trying to use JAXB to do this, but my object is empty.

Here's the code for reading the response. I wrote the response to an xml file for test purposes:

```<code>try {
    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));
    xsr.nextTag(); // Advance to Envelope tag

    xsr.nextTag(); // Advance to Body tag
    xsr.nextTag();
    xsr.nextTag();

    JAXBContext jc = JAXBContext.newInstance(LoginResult.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    JAXBElement<LoginResult> je = unmarshaller.unmarshal(xsr, LoginResult.class);

    System.out.println(je.getName());
    System.out.println(je.getValue());
} catch (XMLStreamException e) {
    e.printStackTrace();
} catch (JAXBException e) {
    e.printStackTrace();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
</code>```

The LoginResult class:

```<code>public class LoginResult {
    private String errorMessage;
    private String status;

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}
</code>```

Thanks in advance!

答:
you can use this code to retrieve a POJO, and also add an @XmlRootElement as header to your POJO.

(I did'nt test the code below)

```<code>XMLInputFactory xif = XMLInputFactory.newFactory();
        XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));
        xsr.nextTag(); // Advance to Envelope tag

        xsr.nextTag(); // Advance to Body tag
        xsr.nextTag();
        xsr.nextTag();

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        StringWriter stringWriter = new StringWriter();
        transformer.transform(new StAXSource(xsr), new StreamResult(stringWriter));
        StringReader sr = new StringReader(stringWriter.toString());
        JAXBContext jaxbContext = JAXBContext.newInstance(LoginResult.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        LoginResult loginResult = (LoginResult) unmarshaller.unmarshal(sr);
</code>```

EDIT :

I found a solution for you:

```<code>    @XmlRootElement(name = "LoginResult", namespace = "http://test.org/ADMail_Service")
@XmlAccessorType(XmlAccessType.FIELD)
public class LoginResult {
    @XmlElement(name = "ErrorMessage", namespace = "http://test.org/ADMail_Service")
    private String errorMessage;
    @XmlElement(name = "Status", namespace = "http://test.org/ADMail_Service")
    private String status;

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}

public static void main(String[] args) {
        try {
            XMLInputFactory xif = XMLInputFactory.newFactory();
            XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));
            xsr.nextTag(); // Advance to Envelope tag

            xsr.nextTag(); // Advance to Body tag
            xsr.nextTag();
            xsr.nextTag();

            JAXBContext jc = JAXBContext.newInstance(LoginResult.class);
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            JAXBElement<LoginResult> je = unmarshaller.unmarshal(xsr, LoginResult.class);

            System.out.println(je.getName());
            System.out.println(je.getValue());
            System.out.println(je.getValue().getErrorMessage());
        } catch (XMLStreamException e) {
            e.printStackTrace();
        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
</code>```

Title: Convert Soap XML response to Object

Body:
i'm new to working with SOAP API's

I have a soap response from an API

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<LoginResponse xmlns="http://test.org/ADMail_Service">
<LoginResult>
<ErrorMessage>Successful login</ErrorMessage>
<Status>true</Status>
</LoginResult>
</LoginResponse>
</soapenv:Body>
</soapenv:Envelope>

I'm trying to transform this into an object.

From reading articles online I'm trying to use JAXB to do this, but my object is empty.

Here's the code for reading the response. I wrote the response to an xml file for test purposes:

try {
    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));
    xsr.nextTag(); // Advance to Envelope tag

    xsr.nextTag(); // Advance to Body tag
    xsr.nextTag();
    xsr.nextTag();

    JAXBContext jc = JAXBContext.newInstance(LoginResult.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    JAXBElement<LoginResult> je = unmarshaller.unmarshal(xsr, LoginResult.class);

    System.out.println(je.getName());
    System.out.println(je.getValue());
} catch (XMLStreamException e) {
    e.printStackTrace();
} catch (JAXBException e) {
    e.printStackTrace();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

The LoginResult class:

public class LoginResult {
    private String errorMessage;
    private String status;

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}

Thanks in advance!

Body:
you can use this code to retrieve a POJO, and also add an @XmlRootElement as header to your POJO.

(I did'nt test the code below)

XMLInputFactory xif = XMLInputFactory.newFactory();
        XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));
        xsr.nextTag(); // Advance to Envelope tag

        xsr.nextTag(); // Advance to Body tag
        xsr.nextTag();
        xsr.nextTag();

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        StringWriter stringWriter = new StringWriter();
        transformer.transform(new StAXSource(xsr), new StreamResult(stringWriter));
        StringReader sr = new StringReader(stringWriter.toString());
        JAXBContext jaxbContext = JAXBContext.newInstance(LoginResult.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        LoginResult loginResult = (LoginResult) unmarshaller.unmarshal(sr);

EDIT :

I found a solution for you:

    @XmlRootElement(name = "LoginResult", namespace = "http://test.org/ADMail_Service")
@XmlAccessorType(XmlAccessType.FIELD)
public class LoginResult {
    @XmlElement(name = "ErrorMessage", namespace = "http://test.org/ADMail_Service")
    private String errorMessage;
    @XmlElement(name = "Status", namespace = "http://test.org/ADMail_Service")
    private String status;

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}

public static void main(String[] args) {
        try {
            XMLInputFactory xif = XMLInputFactory.newFactory();
            XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));
            xsr.nextTag(); // Advance to Envelope tag

            xsr.nextTag(); // Advance to Body tag
            xsr.nextTag();
            xsr.nextTag();

            JAXBContext jc = JAXBContext.newInstance(LoginResult.class);
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            JAXBElement<LoginResult> je = unmarshaller.unmarshal(xsr, LoginResult.class);

            System.out.println(je.getName());
            System.out.println(je.getValue());
            System.out.println(je.getValue().getErrorMessage());
        } catch (XMLStreamException e) {
            e.printStackTrace();
        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }


问:
How do I set up git so that I get a message through gchat or aim that someone pushed onto the server?
What do I need to set up the server so that I get an update message through gchat/aim? Do I just set up a client on the server and use a hook combined with a script? </p>

答: You can use the .git/hooks/post-receive hook to inspect the new changesets and use a command line tool like sendxmpp to send the messages.</p>