问:
Scraped CSV pandas dataframe I get: ValueError('Length of values does not match length of ' 'index')
I run below code and get:

```<code>raise ValueError('Length of values does not match length of ' 'index')
</code>```

ValueError: Length of values does not match length of index

for:

```<code>print(df3)
zz = df1.WE=np.where(df1.EW.isin(df3.AL),df1.WE,np.nan)
df3['O2'] = zz  #Error Line
</code>```

I have got this to work for data in a csv that has identical column structure save for this is scraped data where as the other csv was created manually.

df1

```<code>                                                 EW      WE  \
0                                            can v can   1.900
1                       Lanus U20 v Argentinos Jrs U20   2.100

                                                    DA
0    https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
1    https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
</code>```

df2

```<code>                AA                      AB                       AC      AD  \
0      Today 19:00           Indonesia U23           Kyrgyzstan U23  650.00
1      Today 23:00   Brunei Darussalam U23             Mongolia U23    3.30
2      Today 19:30                     can                      can  110.00

                                                   AE
0   https://www.betfair.com.au/exchange/plus/footb...
1   https://www.betfair.com.au/exchange/plus/footb...
2   https://www.betfair.com.au/exchange/plus/footb...
</code>```

df3

```<code>df3 = pd.DataFrame(columns=['DAT', 'G', 'TN', 'O1', 'L1', 'TN2', 'O2', 'L2', 'D', 'AJ', 'AK', 'AL'])
</code>```

Desired:

df3:

```<code>               DAT                      G  \
0      Today 19:00                 can v can

         TN                           O1  \
0   can v can                        1.900

                         L1  \
0   https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...

        TN2                         O2  \
0   can v can                       110.00

                                                   L2    D
0   https://www.betfair.com.au/exchange/plus/footb...  108.1
</code>```

Code:

```<code>   import pandas as pd
    import time
    import numpy as np
    import pandas as pd
    print('####CURRIES###')
    df1 = pd.read_csv('C:\\O\\df1.csv',
                       index_col=False,
                       usecols=[0,1,2],
                       names=["EW", "WE", "DA"],
                       header=None)
    print(df1)

    print('####Mangoes###')
    df2 = pd.read_csv('C:\\O\\df2.csv',
                       index_col=False,
                       usecols=[0,1,2, 3, 4],
                       names=["AA", "AB", "AC", "AD", "AE"],
                       header=None)
    print(df2)

    df3 = pd.DataFrame(columns=['DAT', 'G', 'TN', 'O1', 'L1', 'TN2', 'O2', 'L2', 'D', 'AJ', 'AK', 'AL'])

    df3['DAT'] = df2['AA']

    df3['G'] = df2['AB'] + ' v ' + df2['AC']

    df3['AK'] = df2['AB'] + ' v ' + df2['AC']
    df3['AL'] = df2['AB'] + ' v ' + df2['AC']

    print(df3)

    #TN

    print('Vlookup')
    aa = df3.AK=np.where(df3.AK.isin(df1.EW),df3.AK,np.nan)
    print(aa)
    df3['TN'] = aa

    print('Vlookup output')
    print(df3)
    ## Not working

    #TN

    print('Vlookup')
    aa = df3.AK=np.where(df3.AK.isin(df1.EW),df3.AK,np.nan)
    print(aa)
    df3['TN2'] = aa
    ## Not working

    #L
    df3['L1'] = df2['AE']
    df3['L2'] = df1['DA']

    print('dataframe complete')
    print(df3)
    ##O  <-- Get value beside T

    print('done')

    #O1 Mangoes
    aa = df2.AD=np.where(df3.AL.isin(df1.EW),df2.AD,np.nan)

    df3['O1'] = aa

    #O2 Curries
    #zz = df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)

    #zz = df1.WE=np.where(df1.EW.isin(df3.AL),df1.WE,np.nan)

    ###############ERROR B#  ###############ERROR B#

    print(df3)
    zz = df1.WE=np.where(df1.EW.isin(df3.AL),df1.WE,np.nan)
    df3['O2'] = zz

###############ERROR ABOVE#
    print('output')
    df = df3[pd.notnull(df3['TN'])]

    #df3['D'] = df3['O2'] - df3['O1']

    print('tt')
    #df3.dropna(how='all')
    #df3.columns = df3.columns.droplevel(3)
    print(df3)
    #df3['AA'] = df1[zz]

    print('zza')
    df3.pop('AK')
    df3.pop('AL')

    df3['D'] = df3['O2'].sub(df3['O1'], fill_value=0)
    df3.pop('AJ')

    print(df3.dtypes)
    NaNs = df3 = df3.dropna(subset=['O1','O2'])
    print(NaNs)
    import pandas as pd

    print('test')
    print(df3)

    writer = pd.ExcelWriter('C:\\O\\dx.xlsx')
    df3.to_excel(writer, startcol=0, index = False)
    writer.save()
    print(df3)

    #df3.pop('AK')

    #df3['T1'] = df1[zz]

    #Delete Columns
    #put O in a column value
    #
</code>```

Scraping code to create dataframes here .

I then write can v can in df1 column A row 1.

I then write can in df2 Column B row 3

I then write can in df2 column C row 3

Or simply here are exact files (scraped) I am using.

df1

df2

These files below the code above works perfectly.  I don't understand why it is not working for scraped data.

Working code

df2

df1

答:
The correct syntax is:

```<code>df3['O2'] = pd.Series(za)
</code>```

Not a scraping problem at all upon investigation with isolated python script and simplified.

Body:
I run below code and get:

raise ValueError('Length of values does not match length of ' 'index')

ValueError: Length of values does not match length of index

for:

print(df3)
zz = df1.WE=np.where(df1.EW.isin(df3.AL),df1.WE,np.nan)
df3['O2'] = zz  #Error Line

I have got this to work for data in a csv that has identical column structure save for this is scraped data where as the other csv was created manually.

df1

                                                 EW      WE  \
0                                            can v can   1.900
1                       Lanus U20 v Argentinos Jrs U20   2.100

                                                    DA
0    https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
1    https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...

df2

                AA                      AB                       AC      AD  \
0      Today 19:00           Indonesia U23           Kyrgyzstan U23  650.00
1      Today 23:00   Brunei Darussalam U23             Mongolia U23    3.30
2      Today 19:30                     can                      can  110.00

                                                   AE
0   https://www.betfair.com.au/exchange/plus/footb...
1   https://www.betfair.com.au/exchange/plus/footb...
2   https://www.betfair.com.au/exchange/plus/footb...

df3

df3 = pd.DataFrame(columns=['DAT', 'G', 'TN', 'O1', 'L1', 'TN2', 'O2', 'L2', 'D', 'AJ', 'AK', 'AL'])

Desired:

df3:

               DAT                      G  \
0      Today 19:00                 can v can

         TN                           O1  \
0   can v can                        1.900

                         L1  \
0   https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...

        TN2                         O2  \
0   can v can                       110.00

                                                   L2    D
0   https://www.betfair.com.au/exchange/plus/footb...  108.1

Code:

   import pandas as pd
    import time
    import numpy as np
    import pandas as pd
    print('####CURRIES###')
    df1 = pd.read_csv('C:\\O\\df1.csv',
                       index_col=False,
                       usecols=[0,1,2],
                       names=["EW", "WE", "DA"],
                       header=None)
    print(df1)

    print('####Mangoes###')
    df2 = pd.read_csv('C:\\O\\df2.csv',
                       index_col=False,
                       usecols=[0,1,2, 3, 4],
                       names=["AA", "AB", "AC", "AD", "AE"],
                       header=None)
    print(df2)

    df3 = pd.DataFrame(columns=['DAT', 'G', 'TN', 'O1', 'L1', 'TN2', 'O2', 'L2', 'D', 'AJ', 'AK', 'AL'])

    df3['DAT'] = df2['AA']

    df3['G'] = df2['AB'] + ' v ' + df2['AC']

    df3['AK'] = df2['AB'] + ' v ' + df2['AC']
    df3['AL'] = df2['AB'] + ' v ' + df2['AC']

    print(df3)

    #TN

    print('Vlookup')
    aa = df3.AK=np.where(df3.AK.isin(df1.EW),df3.AK,np.nan)
    print(aa)
    df3['TN'] = aa

    print('Vlookup output')
    print(df3)
    ## Not working

    #TN

    print('Vlookup')
    aa = df3.AK=np.where(df3.AK.isin(df1.EW),df3.AK,np.nan)
    print(aa)
    df3['TN2'] = aa
    ## Not working

    #L
    df3['L1'] = df2['AE']
    df3['L2'] = df1['DA']

    print('dataframe complete')
    print(df3)
    ##O  <-- Get value beside T

    print('done')

    #O1 Mangoes
    aa = df2.AD=np.where(df3.AL.isin(df1.EW),df2.AD,np.nan)

    df3['O1'] = aa

    #O2 Curries
    #zz = df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)

    #zz = df1.WE=np.where(df1.EW.isin(df3.AL),df1.WE,np.nan)

    ###############ERROR B#  ###############ERROR B#

    print(df3)
    zz = df1.WE=np.where(df1.EW.isin(df3.AL),df1.WE,np.nan)
    df3['O2'] = zz

###############ERROR ABOVE#
    print('output')
    df = df3[pd.notnull(df3['TN'])]

    #df3['D'] = df3['O2'] - df3['O1']

    print('tt')
    #df3.dropna(how='all')
    #df3.columns = df3.columns.droplevel(3)
    print(df3)
    #df3['AA'] = df1[zz]

    print('zza')
    df3.pop('AK')
    df3.pop('AL')

    df3['D'] = df3['O2'].sub(df3['O1'], fill_value=0)
    df3.pop('AJ')

    print(df3.dtypes)
    NaNs = df3 = df3.dropna(subset=['O1','O2'])
    print(NaNs)
    import pandas as pd

    print('test')
    print(df3)

    writer = pd.ExcelWriter('C:\\O\\dx.xlsx')
    df3.to_excel(writer, startcol=0, index = False)
    writer.save()
    print(df3)

    #df3.pop('AK')

    #df3['T1'] = df1[zz]

    #Delete Columns
    #put O in a column value
    #

Scraping code to create dataframes here .

I then write can v can in df1 column A row 1.

I then write can in df2 Column B row 3

I then write can in df2 column C row 3

Or simply here are exact files (scraped) I am using.

df1

df2

These files below the code above works perfectly.  I don't understand why it is not working for scraped data.

Working code

df2

df1

Body:
The correct syntax is:

df3['O2'] = pd.Series(za)

Not a scraping problem at all upon investigation with isolated python script and simplified.


来源: stackexchange

问:
Matlab One Hot Encoding - convert column with categoricals into several columns of logicals
CONTEXT

I have a large number of columns with categoricals, all with different, unrankable choices. To make my life easier for analysis, I'd like to take each of them and convert it to several columns with logicals. For example:

```<code>1   GENRE
2   Pop
3   Classical
4   Jazz
</code>```

...would turn into...

```<code>1   Pop Classical Jazz
2   1       0      0
3   0       1      0
4   0       0      1
</code>```

PROBLEM

I've tried using ind2vec but this only works with numericals or logicals. I've also come across this but am not sure it works with categoricals.  What is the right function to use in this case?

答:
If you want to convert from a categorical vector to a logical array, you can use the unique function to generate column indices, then perform your encoding using any of the options from this related question:

```<code>% Sample data:
data = categorical({'Pop'; 'Classical'; 'Jazz'; 'Pop'; 'Pop'; 'Jazz'});

% Get unique categories and create indices:
[genre, ~, index] = unique(data)

genre =

     Classical
     Jazz
     Pop

index =

     3
     1
     2
     3
     3
     2

% Create logical matrix:
mat = logical(accumarray([(1:numel(index)).' index], 1))

mat =

  6×3 logical array

   0   0   1
   1   0   0
   0   1   0
   0   0   1
   0   0   1
   0   1   0
</code>```

ContentLicense: CC BY-SA 3.0

Body:
CONTEXT

I have a large number of columns with categoricals, all with different, unrankable choices. To make my life easier for analysis, I'd like to take each of them and convert it to several columns with logicals. For example:

1   GENRE
2   Pop
3   Classical
4   Jazz

...would turn into...

1   Pop Classical Jazz
2   1       0      0
3   0       1      0
4   0       0      1

PROBLEM

I've tried using ind2vec but this only works with numericals or logicals. I've also come across this but am not sure it works with categoricals.  What is the right function to use in this case?

Body:
If you want to convert from a categorical vector to a logical array, you can use the unique function to generate column indices, then perform your encoding using any of the options from this related question:

% Sample data:
data = categorical({'Pop'; 'Classical'; 'Jazz'; 'Pop'; 'Pop'; 'Jazz'});

% Get unique categories and create indices:
[genre, ~, index] = unique(data)

genre =

     Classical
     Jazz
     Pop

index =

     3
     1
     2
     3
     3
     2

% Create logical matrix:
mat = logical(accumarray([(1:numel(index)).' index], 1))

mat =

  6×3 logical array

   0   0   1
   1   0   0
   0   1   0
   0   0   1
   0   0   1
   0   1   0


问:
addPullToRefresh function is not invoked when only one item exists
In my code I have a scrollable container, I want to call a refresh function when the user pulls down on the container.

```<code>    venueList = new Container(BoxLayout.y());
    venueList.setScrollableY(true);

    venueList.addPullToRefresh(() -> {
        refresh();
    });
</code>```

This works well when there is more then one item in the container, however, when there is only one item or less, this does not work.

The issue occurs both on the NetBeans simulator and on my ios device.

My current workaround is to add a button to the list if it is empty (after calling a web-service) named "REFRESH", with the refresh() function invoked on clicking it.

答:
Update I just tried this with tabs too with the same result:

```<code>Form hi = new Form("Hi World", new BorderLayout());
Tabs t = new Tabs();
Container mainContainer = new Container(BoxLayout.y());
mainContainer.setScrollableY(true);
mainContainer.addPullToRefresh(() -> log("Pull..."));
t.addTab("Test Tabs", mainContainer);
hi.add(CENTER, t);
hi.show();
</code>```

Original answer below:

This worked fine for me with no elements so I'm guessing there is a different issue such as placing the container within a nested scrollable hierarchy:

```<code>Form hi = new Form("Hi World", new BorderLayout());
Container mainContainer = new Container(BoxLayout.y());
mainContainer.setScrollableY(true);
mainContainer.addPullToRefresh(() -> log("Pull..."));
hi.add(CENTER, mainContainer);
hi.show();
</code>```

Body:
In my code I have a scrollable container, I want to call a refresh function when the user pulls down on the container.

    venueList = new Container(BoxLayout.y());
    venueList.setScrollableY(true);

    venueList.addPullToRefresh(() -> {
        refresh();
    });

This works well when there is more then one item in the container, however, when there is only one item or less, this does not work.

The issue occurs both on the NetBeans simulator and on my ios device.

My current workaround is to add a button to the list if it is empty (after calling a web-service) named "REFRESH", with the refresh() function invoked on clicking it.

Body:
Update I just tried this with tabs too with the same result:

Form hi = new Form("Hi World", new BorderLayout());
Tabs t = new Tabs();
Container mainContainer = new Container(BoxLayout.y());
mainContainer.setScrollableY(true);
mainContainer.addPullToRefresh(() -> log("Pull..."));
t.addTab("Test Tabs", mainContainer);
hi.add(CENTER, t);
hi.show();

Original answer below:

This worked fine for me with no elements so I'm guessing there is a different issue such as placing the container within a nested scrollable hierarchy:

Form hi = new Form("Hi World", new BorderLayout());
Container mainContainer = new Container(BoxLayout.y());
mainContainer.setScrollableY(true);
mainContainer.addPullToRefresh(() -> log("Pull..."));
hi.add(CENTER, mainContainer);
hi.show();


问:
How do I resize an open window in WebdriverIO?
I am using WebdriverIO for automation and am required to resize an open window to check the display of various UI elements compared to a maximized display.

I've tried each of the following separately with no success:

```<code>browser.setViewportSize({width:1200,height:662})
browser.windowHandleSize(1200, 662);
</code>```

I also have checks to make sure the window has been properly resized:

```<code>expect(browser.getViewportSize('width')).to.be.lessThan(1300);
expect(browser.getViewportSize('width')).to.be.greaterThan(1000);
</code>```

Unfortunately, nothing happens visually and the expects fail, as expected. I'm not sure if I'm not understanding how to use setViewportSize or windowHandleSize properly (maybe they're only intended to be used to resize new windows rather than existing ones?), or if this functionality exists in WebdriverIO at all.

答:
I've used the following command in my WebdriverIO Config in setup hooks, but also just tested it in the middle of a test that's already running to both resize it smaller and then back to larger. Hope it helps!

```<code>browser.windowHandleSize({width:700, height:500});
browser.windowHandleSize({width:1280, height:870});
</code>```

http://webdriver.io/api/protocol/windowHandleSize.html

Just to note as there have been several updates, please make sure your browser drivers, WebdriverIO, and Selenium Server are the latest versions!

Body:
I am using WebdriverIO for automation and am required to resize an open window to check the display of various UI elements compared to a maximized display.

I've tried each of the following separately with no success:

browser.setViewportSize({width:1200,height:662})
browser.windowHandleSize(1200, 662);

I also have checks to make sure the window has been properly resized:

expect(browser.getViewportSize('width')).to.be.lessThan(1300);
expect(browser.getViewportSize('width')).to.be.greaterThan(1000);

Unfortunately, nothing happens visually and the expects fail, as expected. I'm not sure if I'm not understanding how to use setViewportSize or windowHandleSize properly (maybe they're only intended to be used to resize new windows rather than existing ones?), or if this functionality exists in WebdriverIO at all.

Body:
I've used the following command in my WebdriverIO Config in setup hooks, but also just tested it in the middle of a test that's already running to both resize it smaller and then back to larger. Hope it helps!

browser.windowHandleSize({width:700, height:500});
browser.windowHandleSize({width:1280, height:870});

http://webdriver.io/api/protocol/windowHandleSize.html

Just to note as there have been several updates, please make sure your browser drivers, WebdriverIO, and Selenium Server are the latest versions!


问:
Differences between up and back button in Android
I'm trying to create a basic "Find my nearest..." application as a learning exercise.

I have 3 activities:

A main activity, where the user enters his address, this passes an
array of objects to the list activity via the intent.

A list activity, which shows the nearest 10 places. When an item is selected this passes an object to the detail activity via the intent.

A detail activity, showing the detail for the selected place.

I have most things working, however I have noticed a slight problem, arising the difference from the back button (at the bottom of my phone screen), and the up button (the on action bar). After researching the difference between the two, it would appear they should behave the same in this scenario. When hitting the back button, everything works as intended, and we still see the same list. However, when hitting the up button, it appears to startup / resume the list activity in a different way, and the data from the list has disappeared.

Would anyone be able to explain to me why this is happening and how to prevent it?

My code is below: (any criticisms about my Android / Java techniques are very welcome!)

MainActivity.java

```<code>public class MainActivity extends Activity {

    public final static String TRACKS = "com.example.firstapp.TRACKS";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /** Called when the user clicks the 'Search' button */
    public void search(View view) {

        // Get Address Text
        // EditText editText = (EditText) findViewById(R.id.edit_address);
        // String address = editText.getText().toString();

        // Get tracks near to address
        Track[] trackArray = new Track[20];

        for(int i=0; i < trackArray.length; i++) {
            trackArray[i] = new Track("Track " + i, "Address" + i, (float) Math.random()*10);
        }

        // Fire intent to show results
        Intent intent = new Intent(this, TrackListActivity.class);
        intent.putExtra(TRACKS, trackArray);
        startActivity(intent);
    }

}
</code>```

TrackListActivity.java

```<code>public class TrackListActivity extends ListActivity {

    public final static String TRACK = "com.mycroft.runtrackdir.TRACK";

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();

        if (intent.hasExtra(MainActivity.TRACKS)) {
            Parcelable[] tempTrackArray = intent.getParcelableArrayExtra(MainActivity.TRACKS);

            // Cast Parcelable to Track
            Track[] trackArray = new Track[tempTrackArray.length];
            for(int i=0; i < trackArray.length; i++) {
                trackArray[i] = (Track) tempTrackArray[i];
            }

            ArrayAdapter<Track> arrayAdapter = new ArrayAdapter<Track>(this, android.R.layout.simple_list_item_1, trackArray);
            setListAdapter(arrayAdapter);
        }
    }

    @Override
    protected void onListItemClick (ListView l, View v, int position, long id) {
        Track clickedTrack = (Track) l.getItemAtPosition(position);

        // Fire intent to show detail
        Intent intent = new Intent(this, TrackDetailActivity.class);
        intent.putExtra(TRACK, clickedTrack);
        startActivity(intent);
    }
}
</code>```

TrackDetailActivity.java

```<code>public class TrackDetailActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        Track track = intent.getParcelableExtra(TrackListActivity.TRACK);

        setContentView(R.layout.activity_track_detail);

        TextView track_name = (TextView) findViewById(R.id.track_name);
        TextView track_address = (TextView) findViewById(R.id.track_address);
        TextView track_distance = (TextView) findViewById(R.id.track_distance);

        track_name.setText(track.name);
        track_address.setText(track.address);
        track_distance.setText(track.distance.toString());

    }
}
</code>```

Manifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.firstapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.firstapp.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.firstapp.TrackListActivity"
            android:label="@string/title_activity_track_list"
            android:parentActivityName="com.example.firstapp.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.firstapp.MainActivity" />
        </activity>
        <activity
            android:name="com.example.firstapp.TrackDetailActivity"
            android:label="@string/title_activity_track_detail"
            android:parentActivityName="com.example.firstapp.TrackListActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.firstapp.TrackListActivity" />
        </activity>
    </application>

</manifest>
</code>```

答:
Difference between Up Button and Back Button.

Back Button- Back Button takes you to the last activity where you are previously active.

Up button- Up Button takes you one level up in hierarchical or ancestral way.No matter what is your last active activity,you will always be redirected towards the parent activity that you have set in the manifest.

Although Back and Up Button almost does the same thing in many
  conditions but they were doing whole different steps behind the scene.

Body:
I'm trying to create a basic "Find my nearest..." application as a learning exercise.

I have 3 activities:

A main activity, where the user enters his address, this passes an
array of objects to the list activity via the intent.

A list activity, which shows the nearest 10 places. When an item is selected this passes an object to the detail activity via the intent.

A detail activity, showing the detail for the selected place.

I have most things working, however I have noticed a slight problem, arising the difference from the back button (at the bottom of my phone screen), and the up button (the on action bar). After researching the difference between the two, it would appear they should behave the same in this scenario. When hitting the back button, everything works as intended, and we still see the same list. However, when hitting the up button, it appears to startup / resume the list activity in a different way, and the data from the list has disappeared.

Would anyone be able to explain to me why this is happening and how to prevent it?

My code is below: (any criticisms about my Android / Java techniques are very welcome!)

MainActivity.java

public class MainActivity extends Activity {

    public final static String TRACKS = "com.example.firstapp.TRACKS";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /** Called when the user clicks the 'Search' button */
    public void search(View view) {

        // Get Address Text
        // EditText editText = (EditText) findViewById(R.id.edit_address);
        // String address = editText.getText().toString();

        // Get tracks near to address
        Track[] trackArray = new Track[20];

        for(int i=0; i < trackArray.length; i++) {
            trackArray[i] = new Track("Track " + i, "Address" + i, (float) Math.random()*10);
        }

        // Fire intent to show results
        Intent intent = new Intent(this, TrackListActivity.class);
        intent.putExtra(TRACKS, trackArray);
        startActivity(intent);
    }

}

TrackListActivity.java

public class TrackListActivity extends ListActivity {

    public final static String TRACK = "com.mycroft.runtrackdir.TRACK";

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();

        if (intent.hasExtra(MainActivity.TRACKS)) {
            Parcelable[] tempTrackArray = intent.getParcelableArrayExtra(MainActivity.TRACKS);

            // Cast Parcelable to Track
            Track[] trackArray = new Track[tempTrackArray.length];
            for(int i=0; i < trackArray.length; i++) {
                trackArray[i] = (Track) tempTrackArray[i];
            }

            ArrayAdapter<Track> arrayAdapter = new ArrayAdapter<Track>(this, android.R.layout.simple_list_item_1, trackArray);
            setListAdapter(arrayAdapter);
        }
    }

    @Override
    protected void onListItemClick (ListView l, View v, int position, long id) {
        Track clickedTrack = (Track) l.getItemAtPosition(position);

        // Fire intent to show detail
        Intent intent = new Intent(this, TrackDetailActivity.class);
        intent.putExtra(TRACK, clickedTrack);
        startActivity(intent);
    }
}

TrackDetailActivity.java

public class TrackDetailActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        Track track = intent.getParcelableExtra(TrackListActivity.TRACK);

        setContentView(R.layout.activity_track_detail);

        TextView track_name = (TextView) findViewById(R.id.track_name);
        TextView track_address = (TextView) findViewById(R.id.track_address);
        TextView track_distance = (TextView) findViewById(R.id.track_distance);

        track_name.setText(track.name);
        track_address.setText(track.address);
        track_distance.setText(track.distance.toString());

    }
}

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.firstapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.firstapp.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.firstapp.TrackListActivity"
            android:label="@string/title_activity_track_list"
            android:parentActivityName="com.example.firstapp.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.firstapp.MainActivity" />
        </activity>
        <activity
            android:name="com.example.firstapp.TrackDetailActivity"
            android:label="@string/title_activity_track_detail"
            android:parentActivityName="com.example.firstapp.TrackListActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.firstapp.TrackListActivity" />
        </activity>
    </application>

</manifest>


问:
Getting the URL of Google Place Photo from a GoogleMapsClient response
I'm building an API endpoint which will return details and a single photo of a Google place using express.js and Node.js client library for Google Maps API Web Services. The endpoint below returns details of a place and I'm having trouble retrieving the URL of a photo. Below is the code in question.

There are two requests to the google maps client:

Get place details based on req.params.id and the details contain a photos array

Get photo using the photo_reference from above

```<code>var googleMapsClient = require('@google/maps').createClient({
  key: 'mykeyhere',
  Promise: Promise
});

exports.getGglPlace = function(req, res) {

googleMapsClient.place({
     placeid: req.params.id
}).asPromise()
.then((response) => {
  var venue = response.json.result

  if (venue.photos[0]) {
    googleMapsClient.placesPhoto({
      photoreference: venue.photos[0].photo_reference,
      maxwidth: 200
    }).asPromise()
    .then((photo) => {

      console.log("Photo:", photo); // this returns a massive chunk of data which I think contains the actual image object also
      venue.photoURL = photo.url; // this doesn't work

      res.send(venue);
    })
    .catch((err)=>{
      console.log("Error Getting Photo!", err);
      res.send(venue);
    })
  } else {
    res.send(venue);
  }
})
.catch((err) => {
  res.send(404);
})
}
</code>```

Any idea how to obtain the URL from the response which is called photo in the code above?

If I try going to the API directly through the browser or Postman, the URL gets redirected to the actual source URL of the image, which is what I want to add to my venue object.

API request example: https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=CmRaAAAA8NPP1nJJ7RCzcQDGUrpBHJXlzlQkN74dcyQJ2ytVpeYIu47sR-8dfCjke1J5exP-HpkayaXOc26ShsVKkXOaJZBOdpmExUfCzUTIBN3x0uPfR5Nt3PnN-a3GoRVZ7YxKEhBvqXF356Tn9mBJ7lA_JQ_7GhQMKvZkOk-Rs9knsansx5yuhfIvsQ&sensor=false&key=mykeyhere

Redirects to (this is what I want photo.url to return): https://lh3.googleusercontent.com/p/AF1QipPVD12HA5FBnjmiqVLphYgjfPtIPydn4Ie-xGKr=s1600-w200

Any help is appreciated.

P.S. My first post here - sorry if I'm not clear enough with my question.

答:
Here is how I solved it. It doesn't seem perfect, but it does the job.

The response contains a req section which has keys in there that I was able to use to build the URL. Specifically, the response.req.socket._host key and the response.req.path key.

Here is what it looks like in my code (where photo is the response from google API)

venue.photoURL = "https://" + photo.req.socket._host + photo.req.path;

photo.req.socket._host gives me lh3.googleusercontent.com

photo.req.path gives me /p/AF1QipPVD12HA5FBnjmiqVLphYgjfPtIPydn4Ie-xGKr=s1600-w200

Results of the constructed URL to the photo is: https://lh3.googleusercontent.com/p/AF1QipPVD12HA5FBnjmiqVLphYgjfPtIPydn4Ie-xGKr=s1600-w200

Body:
I'm building an API endpoint which will return details and a single photo of a Google place using express.js and Node.js client library for Google Maps API Web Services. The endpoint below returns details of a place and I'm having trouble retrieving the URL of a photo. Below is the code in question.

There are two requests to the google maps client:

Get place details based on req.params.id and the details contain a photos array

Get photo using the photo_reference from above

var googleMapsClient = require('@google/maps').createClient({
  key: 'mykeyhere',
  Promise: Promise
});

exports.getGglPlace = function(req, res) {

googleMapsClient.place({
     placeid: req.params.id
}).asPromise()
.then((response) => {
  var venue = response.json.result

  if (venue.photos[0]) {
    googleMapsClient.placesPhoto({
      photoreference: venue.photos[0].photo_reference,
      maxwidth: 200
    }).asPromise()
    .then((photo) => {

      console.log("Photo:", photo); // this returns a massive chunk of data which I think contains the actual image object also
      venue.photoURL = photo.url; // this doesn't work

      res.send(venue);
    })
    .catch((err)=>{
      console.log("Error Getting Photo!", err);
      res.send(venue);
    })
  } else {
    res.send(venue);
  }
})
.catch((err) => {
  res.send(404);
})
}

Any idea how to obtain the URL from the response which is called photo in the code above?

If I try going to the API directly through the browser or Postman, the URL gets redirected to the actual source URL of the image, which is what I want to add to my venue object.

API request example: https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=CmRaAAAA8NPP1nJJ7RCzcQDGUrpBHJXlzlQkN74dcyQJ2ytVpeYIu47sR-8dfCjke1J5exP-HpkayaXOc26ShsVKkXOaJZBOdpmExUfCzUTIBN3x0uPfR5Nt3PnN-a3GoRVZ7YxKEhBvqXF356Tn9mBJ7lA_JQ_7GhQMKvZkOk-Rs9knsansx5yuhfIvsQ&sensor=false&key=mykeyhere

Redirects to (this is what I want photo.url to return): https://lh3.googleusercontent.com/p/AF1QipPVD12HA5FBnjmiqVLphYgjfPtIPydn4Ie-xGKr=s1600-w200

Any help is appreciated.

P.S. My first post here - sorry if I'm not clear enough with my question.


问:
Possibility of having variable parameter names in Django model updates
I'd like to shorten the following code from

```<code>if field == 'favorite_food':
    model_instance.update(favorite_food=value)
elif field == 'favorite_drink':
    model_instance.update(favorite_drink=value)
elif field == 'favorite_color':
    model_instance.update(favorite_color=value)
</code>```

to something like:

```<code>if field in list:
    model_instance.update(field=value)
</code>```

So I'm just wondering if it's possible.

答:
You can do this</p>

```<code>fields = ["favorite_food", "favorite_drink", "favorite_color"]
field = "favorite_food"
if field in fields:
    model_instance.update(field=value)
</code>```

Body:
I'd like to shorten the following code from

if field == 'favorite_food':
    model_instance.update(favorite_food=value)
elif field == 'favorite_drink':
    model_instance.update(favorite_drink=value)
elif field == 'favorite_color':
    model_instance.update(favorite_color=value)

to something like:

if field in list:
    model_instance.update(field=value)

So I'm just wondering if it's possible.

Body:
You can do this

fields = ["favorite_food", "favorite_drink", "favorite_color"]
field = "favorite_food"
if field in fields:
    model_instance.update(field=value)


问:
CodeIgniter Redirect issue
I am testing a server on http://example.com:8080, my CI app is here http://example.com:8080/app/

I have a port forward from 8080 (external) to 80 (internal)

My config.php looks like this:

```<code>...
$config['base_url'] = 'http://' . $_SERVER['HTTP_HOST'] . '/app';
...
$config['index_page'] = '';
</code>```

How should look the .htaccess file in order to get the site working. Also I have used this https://www.codeigniter.com/userguide3/general/urls.html with success on port 80, but cant get it work on 8080. If I leave the index.php in the url then everything works well also on port 8080.

Thanks for any suggestion.

答: Finally I have found the issue... The rewrite module was not enabled, so I have enabled and everything works well.</p>

Title: CodeIgniter Redirect issue

Body:
I am testing a server on http://example.com:8080, my CI app is here http://example.com:8080/app/

I have a port forward from 8080 (external) to 80 (internal)

My config.php looks like this:

...
$config['base_url'] = 'http://' . $_SERVER['HTTP_HOST'] . '/app';
...
$config['index_page'] = '';

How should look the .htaccess file in order to get the site working. Also I have used this https://www.codeigniter.com/userguide3/general/urls.html with success on port 80, but cant get it work on 8080. If I leave the index.php in the url then everything works well also on port 8080.

Thanks for any suggestion.


答:
You can just unpack into keyword arguments:

```<code>model_instance.update(**{field: value})
</code>```

There is also an option to set the model field value and then save (there are though differences):

```<code>setattr(model_instance, field, value)
model_instance.save()
</code>```

Title: Possibility of having variable parameter names in Django model updates

Body:
You can just unpack into keyword arguments:

model_instance.update(**{field: value})

There is also an option to set the model field value and then save (there are though differences):

setattr(model_instance, field, value)
model_instance.save()


问:
Angular 2 upload Image button is refreshing page
I have a html form with two buttons on it:-

[1] One button is used to upload an image file (.jpg)
[2] and the second one is to submit the form.

The problem is that the upload image button seems to be refreshing the page after the method for uploading the image has completed. Below is my html:-

```<code><div class="m-b-18px">
  <div class="col-m-12">
    <a (click)="readRecipes()" class="btn btn-primary pull-right">
      <span class="glyphicon glyphicon-plus"></span>Read Recipes
    </a>
  </div>
</div>

<div class="row">
  <div class="col-md-12">
    <form [formGroup]="create_recipe_form" (ngSubmit)="createRecipe()">
      <table class="table table-hover table-responsive table-bordered">
        <tr>
          <td>
            Name
          </td>
          <td>
            <input name="name" formControlName="name" type="text" class="form-control" required />
            <div *ngIf="create_recipe_form.get('name').touched && create_recipe_form.get('name').hasError('required')"
              class="alert alert-danger">Name is required
            </div>
          </td>
        </tr>

        <tr>
          <td>
            Description
          </td>
          <td>
            <textarea name="description" formControlName="description" class="form-control" required>

            </textarea>
            <div *ngIf="create_recipe_form.get('description').touched && create_recipe_form.get('description').hasError('required')"
              class="alert alert-danger">
              Description is required
            </div>
          </td>
        </tr>

        <tr>
          <td>
            Image
          </td>
          <td>
            <input name="selectFile" id="selectFile" type="file" class="form-control btn btn-success" />
            <button type="button" class="btn btn-primary" (click)="uploadImage($event)" value="Upload Image">Upload Image</button>
            <input type='hidden' id='image_id' name='img_id' value="6" formControlName="image_id" />
          </td>
        </tr>

        <tr>
          <td></td>
          <td>
            <button class="btn btn-primary" type="submit" [disabled]="!create_recipe_form.valid">
                <span class="glyphicon glyphicon-plus"></span> Create
            </button>
          </td>
        </tr>
      </table>
    </form>
  </div>
</div>
</code>```

My code for the uploadImage method is below:-

```<code> uploadImage(e) {
    let files = this.elem.nativeElement.querySelector('#selectFile').files;
    let formData = new FormData();
    let file = files[0];

    formData.append('selectFile', file, file.name);

    this._imageService.uploadImage(formData)
      .subscribe(
        image => {
          console.log(image);
          this.addImageIdToHtml(image)
          e.preventDefault();
          e.stopPropagation();
        },
        error => console.log(error)
      );
  }
</code>```

As soon as the above method has finished running the page appears to refreshing causing my app to go back to the land page. This is not the behaviour I want. What I actually want is the form page to be retained until the Submit form button is pressed. Can anyone help me please?

答:
If you are using button tag inside the form tag, add type="button" inside the button tag.

```<code><button type="button"></button>
</code>```

This will work perfectly

Body:
I have a html form with two buttons on it:-

[1] One button is used to upload an image file (.jpg)
[2] and the second one is to submit the form.

The problem is that the upload image button seems to be refreshing the page after the method for uploading the image has completed. Below is my html:-

      Read Recipes

    <form [formGroup]="create_recipe_form" (ngSubmit)="createRecipe()">

            Name

            <input name="name" formControlName="name" type="text" class="form-control" required />

Name is required

            Description

            <textarea name="description" formControlName="description" class="form-control" required>

            </textarea>

              Description is required

            Image

            <input name="selectFile" id="selectFile" type="file" class="form-control btn btn-success" />
            <button type="button" class="btn btn-primary" (click)="uploadImage($event)" value="Upload Image">Upload Image</button>
            <input type='hidden' id='image_id' name='img_id' value="6" formControlName="image_id" />

            <button class="btn btn-primary" type="submit" [disabled]="!create_recipe_form.valid">
                 Create
            </button>

    </form>

My code for the uploadImage method is below:-

 uploadImage(e) {
    let files = this.elem.nativeElement.querySelector('#selectFile').files;
    let formData = new FormData();
    let file = files[0];

    formData.append('selectFile', file, file.name);

    this._imageService.uploadImage(formData)
      .subscribe(
        image => {
          console.log(image);
          this.addImageIdToHtml(image)
          e.preventDefault();
          e.stopPropagation();
        },
        error => console.log(error)
      );
  }

As soon as the above method has finished running the page appears to refreshing causing my app to go back to the land page. This is not the behaviour I want. What I actually want is the form page to be retained until the Submit form button is pressed. Can anyone help me please?

Body:
If you are using button tag inside the form tag, add type="button" inside the button tag.

<button type="button"></button>

This will work perfectly


问:
How to display continuous date in mysql, If date is not present in table
This is a retention query i need to fetch continuous data from db i have written this query with two tables

deviceinfodatas - has the id , created_at time

sessions - deviceid, start_time

SELECT

u.DayOffset as Date,

SUM(s.DayOffset = 0) AS d0,

SUM(s.DayOffset = 1) AS d1,

SUM(s.DayOffset = 2) AS d2,

SUM(s.DayOffset = 3) AS d3

FROM

( SELECT id, DATE(created_at) AS DayOffset FROM deviceinfodatas WHERE
created_at BETWEEN '2017-10-01' AND '2017-12-30') as u
LEFT JOIN

( SELECT DISTINCT sessions.deviceid,
DATEDIFF(DATE(sessions.start_time), DATE(deviceinfodatas.created_at))
AS DayOffset FROM sessions

LEFT JOIN deviceinfodatas ON (deviceinfodatas.id = sessions.deviceid) WHERE
sessions.start_time BETWEEN '2017-10-01' AND '2017-12-30' )
as s ON s.deviceid = u.id GROUP BY u.DayOffset

My result is

```<code>Date          d0  d1  d2  d3

2017-10-25    1   0   0   0

2017-10-27    1   0   0   0

2017-10-31    0   0   1   1

2017-11-02    1   0   0   0

2017-11-03    1   0   0   0

2017-11-06    1   0   0   0

2017-11-08    1   0   0   0

2017-11-09    0   0   1   0

2017-11-13    0   0   1   0

2017-11-16    5   1   0   0
</code>```

But i need a continuous date

as

```<code> Date          d0  d1  d2  d3

2017-10-25    1   0   0   0

2017-10-26    0   0   0   0

2017-10-27    1   0   0   0

2017-10-28    0   0   0   0

2017-10-29    0   0   0   0

2017-10-30    0   0   0   0

2017-10-31    0   0   1   1

.....

2017-11-16    5   1   0   0
</code>```

And also based on date range the count of day d0,d1,d2,d3,d4,d5.... dn has to increased dynamically

I am a beginner in Mysql please do help with this query to achieve my result

i has referenced Continuous date and Daily retention query

Thank you in advance

答:
If you want the date values returned, your query will need a row source for the date values.  That could be a calendar table cal populated with all of the date values you need to return, or it could be an inline view that dynamically returns the set of dates.

Example of a simple calendar table containing unique values. This table will need to be maintained, we need to make sure it contains all possible date values that we would want to return, with no gaps.

```<code>CREATE TABLE cal (dt DATE NOT NULL PRIMARY KEY) ENGINE=InnoDB;

INSERT INTO cal (dt) VALUES ('2017-10-01'),('2017-10-02'),('2017-10-03') ;
INSERT INTO cal (dt) SELECT dt + INTERVAL 3 DAY FROM cal ORDER BY dt ;
INSERT INTO cal (dt) SELECT dt + INTERVAL 6 DAY FROM cal ORDER BY dt ;
INSERT INTO cal (dt) SELECT dt + INTERVAL 12 DAY FROM cal ORDER BY dt ;
INSERT INTO cal (dt) SELECT dt + INTERVAL 24 DAY FROM cal ORDER BY dt ;
INSERT INTO cal (dt) SELECT dt + INTERVAL 48 DAY FROM cal ORDER BY dt ;
INSERT INTO cal (dt) SELECT dt + INTERVAL 96 DAY FROM cal ORDER BY dt ;
</code>```

Then we can do something like this:

```<code>SELECT c.dt
     , ...
  FROM cal c

  LEFT
  JOIN mytable t
    ON t.date_col = c.dt

WHERE c.dt >= '2017-10-25'
  AND c.dt <  '2017-10-25' + INTERVAL 30 DAY
</code>```

Body:
This is a retention query i need to fetch continuous data from db i have written this query with two tables

deviceinfodatas - has the id , created_at time

sessions - deviceid, start_time

SELECT

u.DayOffset as Date,

SUM(s.DayOffset = 0) AS d0,

SUM(s.DayOffset = 1) AS d1,

SUM(s.DayOffset = 2) AS d2,

SUM(s.DayOffset = 3) AS d3

FROM

( SELECT id, DATE(created_at) AS DayOffset FROM deviceinfodatas WHERE
created_at BETWEEN '2017-10-01' AND '2017-12-30') as u
LEFT JOIN

( SELECT DISTINCT sessions.deviceid,
DATEDIFF(DATE(sessions.start_time), DATE(deviceinfodatas.created_at))
AS DayOffset FROM sessions

LEFT JOIN deviceinfodatas ON (deviceinfodatas.id = sessions.deviceid) WHERE
sessions.start_time BETWEEN '2017-10-01' AND '2017-12-30' )
as s ON s.deviceid = u.id GROUP BY u.DayOffset

My result is

Date          d0  d1  d2  d3

2017-10-25    1   0   0   0

2017-10-27    1   0   0   0

2017-10-31    0   0   1   1

2017-11-02    1   0   0   0

2017-11-03    1   0   0   0

2017-11-06    1   0   0   0

2017-11-08    1   0   0   0

2017-11-09    0   0   1   0

2017-11-13    0   0   1   0

2017-11-16    5   1   0   0

But i need a continuous date

as

 Date          d0  d1  d2  d3

2017-10-25    1   0   0   0

2017-10-26    0   0   0   0

2017-10-27    1   0   0   0

2017-10-28    0   0   0   0

2017-10-29    0   0   0   0

2017-10-30    0   0   0   0

2017-10-31    0   0   1   1

.....

2017-11-16    5   1   0   0

And also based on date range the count of day d0,d1,d2,d3,d4,d5.... dn has to increased dynamically

I am a beginner in Mysql please do help with this query to achieve my result

i has referenced Continuous date and Daily retention query

Thank you in advance

Body:
If you want the date values returned, your query will need a row source for the date values.  That could be a calendar table cal populated with all of the date values you need to return, or it could be an inline view that dynamically returns the set of dates.

Example of a simple calendar table containing unique values. This table will need to be maintained, we need to make sure it contains all possible date values that we would want to return, with no gaps.

CREATE TABLE cal (dt DATE NOT NULL PRIMARY KEY) ENGINE=InnoDB;

INSERT INTO cal (dt) VALUES ('2017-10-01'),('2017-10-02'),('2017-10-03') ;
INSERT INTO cal (dt) SELECT dt + INTERVAL 3 DAY FROM cal ORDER BY dt ;
INSERT INTO cal (dt) SELECT dt + INTERVAL 6 DAY FROM cal ORDER BY dt ;
INSERT INTO cal (dt) SELECT dt + INTERVAL 12 DAY FROM cal ORDER BY dt ;
INSERT INTO cal (dt) SELECT dt + INTERVAL 24 DAY FROM cal ORDER BY dt ;
INSERT INTO cal (dt) SELECT dt + INTERVAL 48 DAY FROM cal ORDER BY dt ;
INSERT INTO cal (dt) SELECT dt + INTERVAL 96 DAY FROM cal ORDER BY dt ;

Then we can do something like this:

SELECT c.dt
     , ...
  FROM cal c

  LEFT
  JOIN mytable t
    ON t.date_col = c.dt

WHERE c.dt >= '2017-10-25'
  AND c.dt <  '2017-10-25' + INTERVAL 30 DAY


问:
how to set Linearlayout Center inside relative layout in android
```<code> <RelativeLayout
            android:id="@+id/scroll_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/header"
            android:fillViewport="true"

            android:paddingLeft="80dp"
            android:paddingRight="80dp"
            android:paddingTop="40dp">

            <LinearLayout
                android:id="@+id/appLogogImageView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/circular_textview_drawable"
                android:gravity="center">

                <ImageView
                    android:layout_width="72dp"
                    android:layout_height="72dp"
                    android:layout_gravity="center"
                    android:background="@drawable/ic_share_illustration" />
            </LinearLayout>

            <TextView
                android:id="@+id/appTextview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/appLogogImageView"
                android:fontFamily="sans-serif-medium"
                android:gravity="center_horizontal"
                android:letterSpacing="-0.03"
                android:paddingTop="@dimen/baseline_grid_4x"
                android:text="Sharing is Caring"
                android:textColor="@color/colorDusk"
                android:textSize="20.1sp"
                android:textStyle="normal"

                />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/appTextview"
                android:fontFamily="sans-serif"
                android:gravity="center_horizontal"
                android:letterSpacing="-0.03"
                android:lineSpacingExtra="6sp"
                android:text="Share ContSync with your friends to get them onboard"
                android:textColor="@color/colorBlueyGrey"
                android:textSize="14sp"
                android:textStyle="normal" />

        </RelativeLayout>
    </RelativeLayout>

// toolbar .xml

      <android.support.design.widget.AppBarLayout
                android:layout_width="match_parent"

                android:layout_height="?android:attr/actionBarSize">

                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?android:attr/actionBarSize"
                    app:elevation="@dimen/app_bar_default_elevation"
                    style="@style/TextAppearance.Widget.Event.Toolbar.Title"
                    tools:title="@string/label_select_your_country" />
            </android.support.design.widget.AppBarLayout>

https://pasteboard.co/
</code>```

This is my Xml and current Screen you can see the imageview which is inside Linearlayout is not set center . i  have puted gravity center in Linarlayout but its not   set center  i dont know what mistake i am doing even  on tool bar also i tried to set shadow below but its not coming can any one please suggest me what i am doing wrong.
[![enter image description here][1]][1]

this is my expected screen   in my current Screen and using current xml i am not able to set Imageview which is coming inside linear layout is not center and also toolbar below shadow is not coming please suggest me how to keep its center and how to put shadow below on tool bar as expected screen.

答: In LinearLayout add this lineandroid:layout_centerInParent="true" to make it center in parent of RelativeLayout

Body:
 <RelativeLayout
            android:id="@+id/scroll_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/header"
            android:fillViewport="true"

            android:paddingLeft="80dp"
            android:paddingRight="80dp"
            android:paddingTop="40dp">

            <LinearLayout
                android:id="@+id/appLogogImageView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/circular_textview_drawable"
                android:gravity="center">

                <ImageView
                    android:layout_width="72dp"
                    android:layout_height="72dp"
                    android:layout_gravity="center"
                    android:background="@drawable/ic_share_illustration" />
            </LinearLayout>

            <TextView
                android:id="@+id/appTextview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/appLogogImageView"
                android:fontFamily="sans-serif-medium"
                android:gravity="center_horizontal"
                android:letterSpacing="-0.03"
                android:paddingTop="@dimen/baseline_grid_4x"
                android:text="Sharing is Caring"
                android:textColor="@color/colorDusk"
                android:textSize="20.1sp"
                android:textStyle="normal"

                />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/appTextview"
                android:fontFamily="sans-serif"
                android:gravity="center_horizontal"
                android:letterSpacing="-0.03"
                android:lineSpacingExtra="6sp"
                android:text="Share ContSync with your friends to get them onboard"
                android:textColor="@color/colorBlueyGrey"
                android:textSize="14sp"
                android:textStyle="normal" />

        </RelativeLayout>
    </RelativeLayout>

// toolbar .xml

      <android.support.design.widget.AppBarLayout
                android:layout_width="match_parent"

                android:layout_height="?android:attr/actionBarSize">

                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?android:attr/actionBarSize"
                    app:elevation="@dimen/app_bar_default_elevation"
                    style="@style/TextAppearance.Widget.Event.Toolbar.Title"
                    tools:title="@string/label_select_your_country" />
            </android.support.design.widget.AppBarLayout>

https://pasteboard.co/

This is my Xml and current Screen you can see the imageview which is inside Linearlayout is not set center . i  have puted gravity center in Linarlayout but its not   set center  i dont know what mistake i am doing even  on tool bar also i tried to set shadow below but its not coming can any one please suggest me what i am doing wrong.
[![enter image description here][1]][1]

this is my expected screen   in my current Screen and using current xml i am not able to set Imageview which is coming inside linear layout is not center and also toolbar below shadow is not coming please suggest me how to keep its center and how to put shadow below on tool bar as expected screen.


问:
How to use $templateCache for partials that are used in ui-router?
.state ('pages', {
      url: '/pages',
      templateUrl: 'views/common.html'
    })

```<code><script type="text/ng-template" id="common.html">
</code>```

how to use this using Ui-router?

答:
It will be helpful to you</p>

```<code>var myApp = angular.module('testApp', []);

myApp.run(['$templateCache',function($templateCache) {
  $templateCache.put('common.html', ' <p>how to use this using Ui-router?</p>');
   $templateCache.put('views/common.html', ' <p>how to use this using Ui-router?</p>');
}]);

myApp.config(['$stateProvide','$templateCache',function($stateProvider,$templateCache){
$stateProvider.state ('pages',
     { url: '/pages',
       template: $templateCache.get('common.html')
     })
.state ('pages',
     { url: '/pages',
       templateUrl: 'views/common.html'
     })
}]);

myApp.controller('testCtrl',function($scope){
})

    <body ng-app="testApp" ng-controller="testCtrl">

    </body>
</code>```

Body:
It will be helpful to you

var myApp = angular.module('testApp', []);

myApp.run(['$templateCache',function($templateCache) {
  $templateCache.put('common.html', ' <p>how to use this using Ui-router?</p>');
   $templateCache.put('views/common.html', ' <p>how to use this using Ui-router?</p>');
}]);

myApp.config(['$stateProvide','$templateCache',function($stateProvider,$templateCache){
$stateProvider.state ('pages',
     { url: '/pages',
       template: $templateCache.get('common.html')
     })
.state ('pages',
     { url: '/pages',
       templateUrl: 'views/common.html'
     })
}]);

myApp.controller('testCtrl',function($scope){
})

    <body ng-app="testApp" ng-controller="testCtrl">

    </body>


问:
GroupByKey with datasets in Spark 2.0 using Java
I have a dataset containing data like the following:

```<code>|c1| c2|
---------
| 1 | a |
| 1 | b |
| 1 | c |
| 2 | a |
| 2 | b |
</code>```

...

Now, I want to get the data grouped like the following (col1: String Key, col2: List):

```<code>| c1| c2 |
-----------
| 1 |a,b,c|
| 2 | a, b|
...
</code>```

I thought that using goupByKey would be an sufficient solution, but I can't find any example, how to use it.

Can anyone help me to find a solution using groupByKey or using any other combination of transformations and actions to get this output by using datasets, not RDD?

答:
This will read the table in to dataset variable</p>

```<code>Dataset<Row> datasetNew = dataset.groupBy("c1").agg(functions.collect_list("c2"));
datasetNew.show()
</code>```

Body:
I have a dataset containing data like the following:

|c1| c2|
---------
| 1 | a |
| 1 | b |
| 1 | c |
| 2 | a |
| 2 | b |

...

Now, I want to get the data grouped like the following (col1: String Key, col2: List):

| c1| c2 |
-----------
| 1 |a,b,c|
| 2 | a, b|
...

I thought that using goupByKey would be an sufficient solution, but I can't find any example, how to use it.

Can anyone help me to find a solution using groupByKey or using any other combination of transformations and actions to get this output by using datasets, not RDD?

Body:
This will read the table in to dataset variable

Dataset<Row> datasetNew = dataset.groupBy("c1").agg(functions.collect_list("c2"));
datasetNew.show()