问:
What changes should i make in my build.gradle before releasing my android app to production
This is more of asking suggestion for changes to be made to my build.gradle as i am about to release my first android app.Searched a lot but no satisfactory solution.Here is my gradle file

```<code>buildscript {
repositories {
    maven { url 'https://maven.fabric.io/public' }
}

dependencies {
    classpath 'io.fabric.tools:gradle:1.+'
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
maven { url 'https://maven.fabric.io/public' }
}

android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
    applicationId "com.example.app"
    minSdkVersion 19
    targetSdkVersion 25
    multiDexEnabled true
    versionCode 1
    versionName "1.0"
    resConfigs "en_US", "hi_IN"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
packagingOptions {
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/LICENSE-FIREBASE.txt'
    exclude 'META-INF/NOTICE'
}

}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile('com.digits.sdk.android:digits:2.0.6@aar') {
    transitive = true;

}
compile('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') {
    transitive = true;
}
compile('io.fabric.sdk.android:fabric:1.3.10@aar') {
    transitive = true;
}
compile 'com.android.support:multidex:1.0.1'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:customtabs:25.3.1'
compile 'com.android.support:support-v13:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:gridlayout-v7:25.3.1'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.android.support:support-annotations:25.3.1'
compile 'de.hdodenhof:circleimageview:1.3.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.google.code.gson:gson:2.7'
compile 'com.google.android.gms:play-services-location:10.2.1'
compile 'com.google.android.gms:play-services-places:10.2.1'
compile 'com.google.firebase:firebase-database:10.2.1'
compile 'com.google.firebase:firebase-core:10.2.1'
compile 'com.google.firebase:firebase-auth:10.2.1'
compile 'com.google.firebase:firebase-messaging:10.2.1'
compile 'com.google.firebase:firebase-crash:10.2.1'
compile 'com.firebaseui:firebase-ui-database:1.2.0'
compile 'com.google.firebase:firebase-storage:10.2.1'
compile 'com.google.firebase:firebase-appindexing:10.2.1'
compile ('io.branch.sdk.android:library:2.5.9') {
    transitive = true;
    exclude module: 'answers-shim';
}

}
apply plugin: 'com.google.gms.google-services'
</code>```

Every suggestion matters as it could also be helpful for other beginners like me who are planning to release their first build in play store.

答:
I can see that you have enabled pro guard in your release mode. I suggest you to consider following statement from android doc

For even more code shrinking, try the proguard-android-optimize.txt file that's in the same location. It includes the same ProGuard rules, but with other optimizations that perform analysis at the bytecode level—inside and across methods—to reduce your APK size further and help it run faster.

change this

proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

to this

```<code>proguardFiles getDefaultProguardFile('**proguard-android-optimize.txt**'), 'proguard-rules.pro'
</code>```

Also add this to release mode

```<code>shrinkResources true
</code>```

And don't forget to add pro guard rules if you haven't already.

Doing above two things will make your app small in size and more optimized.

Body:
This is more of asking suggestion for changes to be made to my build.gradle as i am about to release my first android app.Searched a lot but no satisfactory solution.Here is my gradle file

buildscript {
repositories {
    maven { url 'https://maven.fabric.io/public' }
}

dependencies {
    classpath 'io.fabric.tools:gradle:1.+'
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
maven { url 'https://maven.fabric.io/public' }
}

android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
    applicationId "com.example.app"
    minSdkVersion 19
    targetSdkVersion 25
    multiDexEnabled true
    versionCode 1
    versionName "1.0"
    resConfigs "en_US", "hi_IN"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
packagingOptions {
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/LICENSE-FIREBASE.txt'
    exclude 'META-INF/NOTICE'
}

}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile('com.digits.sdk.android:digits:2.0.6@aar') {
    transitive = true;

}
compile('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') {
    transitive = true;
}
compile('io.fabric.sdk.android:fabric:1.3.10@aar') {
    transitive = true;
}
compile 'com.android.support:multidex:1.0.1'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:customtabs:25.3.1'
compile 'com.android.support:support-v13:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:gridlayout-v7:25.3.1'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.android.support:support-annotations:25.3.1'
compile 'de.hdodenhof:circleimageview:1.3.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.google.code.gson:gson:2.7'
compile 'com.google.android.gms:play-services-location:10.2.1'
compile 'com.google.android.gms:play-services-places:10.2.1'
compile 'com.google.firebase:firebase-database:10.2.1'
compile 'com.google.firebase:firebase-core:10.2.1'
compile 'com.google.firebase:firebase-auth:10.2.1'
compile 'com.google.firebase:firebase-messaging:10.2.1'
compile 'com.google.firebase:firebase-crash:10.2.1'
compile 'com.firebaseui:firebase-ui-database:1.2.0'
compile 'com.google.firebase:firebase-storage:10.2.1'
compile 'com.google.firebase:firebase-appindexing:10.2.1'
compile ('io.branch.sdk.android:library:2.5.9') {
    transitive = true;
    exclude module: 'answers-shim';
}

}
apply plugin: 'com.google.gms.google-services'

Every suggestion matters as it could also be helpful for other beginners like me who are planning to release their first build in play store.

Body:
I can see that you have enabled pro guard in your release mode. I suggest you to consider following statement from android doc

For even more code shrinking, try the proguard-android-optimize.txt file that's in the same location. It includes the same ProGuard rules, but with other optimizations that perform analysis at the bytecode level—inside and across methods—to reduce your APK size further and help it run faster.

change this

proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

to this

proguardFiles getDefaultProguardFile('**proguard-android-optimize.txt**'), 'proguard-rules.pro'

Also add this to release mode

shrinkResources true

And don't forget to add pro guard rules if you haven't already.

Doing above two things will make your app small in size and more optimized.


来源: stackexchange

问:
Spark time series - how to parallelize code?
I have a dataset with the following schema.

```<code>inputData.printSchema()
 |-- seriesKeys: string (nullable = true)
 |-- timestamp: long (nullable = true)
 |-- targetSeries: double (nullable = true)
</code>```

Using sparkts library, I would like to generate ARIMA forecasts in a distributed fashion for a large number of time series. Usually, I could approach this problem by using a TimeSeriesRDD as described in this blog by Sandy Ryza. According to my understanding, TimeSeriesRDD requires all series to have the same start and end date which is not the case for my dataset. So I need to write a code which can handle this situation.

Currently, my code is written in a way that everything is executed on the driver and not distributed across executors:

```<code>val seriesKeys: Array[Row] = inputData.select("seriesKeys").distinct().collect()

  val forecastArray : Array[Array[Double]] = seriesKeys.map(key => {
  val inputDataTemp : Dataset[mySchema] = inputData.where(s"seriesKeys ='$key'")
  val dfTS : DataFrame = inputDataTemp.select("targetSeries")
  val rddTS : RDD[Double] = dfTS.rdd.map(row => row.getAs[Double]("targetSeries"))
  val dvTS: Vector = Vectors.dense(rddTS.collect())
  val dvForecast: Vector = ARIMA.autoFit(dvTS, 5, 2, 5).forecast(dvTS, 12)
  dvForecast.toArray
})
</code>```

How could I re-design the code to allow for parallel execution in oder to improve performance?

答: This isn't a phone call pun, but don't call collect. You need to operate with the distributed abstractions like RDD and Dataset/DataFrame. The way you have it now seriesKeys isn't distributed because it is an Array.

ContentLicense: CC BY-SA 3.0

Body:
I have a dataset with the following schema.

inputData.printSchema()
 |-- seriesKeys: string (nullable = true)
 |-- timestamp: long (nullable = true)
 |-- targetSeries: double (nullable = true)

Using sparkts library, I would like to generate ARIMA forecasts in a distributed fashion for a large number of time series. Usually, I could approach this problem by using a TimeSeriesRDD as described in this blog by Sandy Ryza. According to my understanding, TimeSeriesRDD requires all series to have the same start and end date which is not the case for my dataset. So I need to write a code which can handle this situation.

Currently, my code is written in a way that everything is executed on the driver and not distributed across executors:

val seriesKeys: Array[Row] = inputData.select("seriesKeys").distinct().collect()

  val forecastArray : Array[Array[Double]] = seriesKeys.map(key => {
  val inputDataTemp : Dataset[mySchema] = inputData.where(s"seriesKeys ='$key'")
  val dfTS : DataFrame = inputDataTemp.select("targetSeries")
  val rddTS : RDD[Double] = dfTS.rdd.map(row => row.getAs[Double]("targetSeries"))
  val dvTS: Vector = Vectors.dense(rddTS.collect())
  val dvForecast: Vector = ARIMA.autoFit(dvTS, 5, 2, 5).forecast(dvTS, 12)
  dvForecast.toArray
})

How could I re-design the code to allow for parallel execution in oder to improve performance?


问:
Android Studio - Why all controls are all in upper left
Why all my controls(buttons, textfields) are all in upper left of my emulator when I test run it?  </p>

答:
Your views are not setup up correctly in your layout. First of all, if you could give the code for your layout (activity_main.xml or something similar) it will be easier to solve your problem.

The likely culprit is either that you are using a RelativeLayout and haven't set the view to be in relative position to another or, more likely, that you are using a ConstraintLayout and haven't linked your views correctly.

If you are using constraint layout the easiest way to link your views is from the Design tab, looking at the UI of your app. Click your TextView/EditText/etc and drag from the little squares that appear on the sides to literally link to either the side of the screen or to another view.


问:
trying to change background color of rows in a datagrid based on multicell values
I need help binding this WPF to multiple datatriggers. I need to change row color based on two values not just the one. I wasn't able to figure out how to do that</p>

```<code><DataGrid.RowStyle>
   <Style TargetType="DataGridRow">
        <Style.Triggers>
            <DataTrigger Binding="{Binding AgentState}" Value="AUX-IN">
                <Setter Property="Background" Value="Green" />
                <Setter Property="Foreground" Value="White"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
 </DataGrid.RowStyle>
</code>```

答:
```<code> <DataGrid.RowStyle>
                    <Style TargetType="DataGridRow">
                       <Style.Triggers>
                            <MultiDataTrigger>
                                <MultiDataTrigger.Conditions>
                                    <Condition Binding="{Binding AgentState}" Value="ACD-IN"/>
                                    <Condition Binding="{Binding AuxReasons}" Value="General"/>
                                </MultiDataTrigger.Conditions>
                                <Setter Property="Background" Value="Green" />
                                <Setter Property="Foreground" Value="White"/>
                            </MultiDataTrigger>
                        </Style.Triggers>

                    </Style>
                </DataGrid.RowStyle>
</code>```

Body:
I need help binding this WPF to multiple datatriggers. I need to change row color based on two values not just the one. I wasn't able to figure out how to do that

<DataGrid.RowStyle>

    </Style>
 </DataGrid.RowStyle>


问:
How to instantiate an instance of our dependency graph in Dagger2
I am learning dagger2 dependency injection framework. I loved it how it injects dependency. I read this article https://github.com/codepath/android_guides/wiki/Dependency-Injection-with-Dagger-2 I see there they explained this with the help of two Modules.

AppModule & NetModule are the two Modules. Both has constructors, so they instantiate an instance of our dependency graph like this

```<code> mNetComponent = DaggerNetComponent.builder()
                // list of modules that are part of this component need to be created here too
                .appModule(new AppModule(this)) // This also corresponds to the name of your module: %component_name%Module
                .netModule(new NetModule("https://api.github.com"))
                .build();
</code>```

Suppose I have one more Modules which do not have a constructor then how would I initialize it, as other 2 modules need values in the constructor ?

Thanks

答:
If your third module doesn't need a constructor Dagger2 will automatically add it to component if you list it in @Component's modules like this:

```<code> @Component(modules = {
     AppModule.class,
     NetModule.class,
     ThirdModule.class // module without constructor
 })
 public interface NetComponent{
     // ...
 }
</code>```

Body:
I am learning dagger2 dependency injection framework. I loved it how it injects dependency. I read this article https://github.com/codepath/android_guides/wiki/Dependency-Injection-with-Dagger-2 I see there they explained this with the help of two Modules.

AppModule & NetModule are the two Modules. Both has constructors, so they instantiate an instance of our dependency graph like this

 mNetComponent = DaggerNetComponent.builder()
                // list of modules that are part of this component need to be created here too
                .appModule(new AppModule(this)) // This also corresponds to the name of your module: %component_name%Module
                .netModule(new NetModule("https://api.github.com"))
                .build();

Suppose I have one more Modules which do not have a constructor then how would I initialize it, as other 2 modules need values in the constructor ?

Thanks

Body:
If your third module doesn't need a constructor Dagger2 will automatically add it to component if you list it in @Component's modules like this:

 @Component(modules = {
     AppModule.class,
     NetModule.class,
     ThirdModule.class // module without constructor
 })
 public interface NetComponent{
     // ...
 }


问:
Python - MatPlotLib.PyPlot - Removing tick marks from Right Axis
I have the following pyplot subroutine. All data passes correctly to the subroutine. However, I am not able to control two things:
1 - I can't make the right ticks disappear
2 - I can't place a 2nd y-label on the right axis

I've added an example image which has right-ticks that I'm trying to remove, and also trying to add a right-hand y-axis label.

Much thanks!

```<code>def makeChart(dataToGraph,  titleForGraph, titleYlabel, titleYlabel2, legendLabels, yMax, yMin, dataSource):

    fig, ax = plt.subplots()

    colorZ2 = ('#002060', 'red')
    colorZ1 = ( '#92D050', 'purple')
    p1 = plt.Rectangle((0, 0), 1, 1, fc='red')
    p2 = plt.Rectangle((0, 0), 1, 1, fc='#002060')
    p3 = plt.Rectangle((0, 0), 1, 0, fc='black')
    p4 = plt.Rectangle((0, 0), 1, 1, fc='#92D050')
    p5 = plt.Rectangle((0, 0), 1, 1, fc='purple')

#   plt.ylim(yMin, yMax)

    ax2 = ax.twinx()
    ax2 = ax.twiny()

    ax3 = ax.twinx()
    ax3 = ax.twiny()

    dates, series1, series2, series3, series4, series5 = zip(*dataToGraph)

    ax.stackplot(dates, series1, series2, colors=colorZ1)
    ax2.stackplot(dates, series3, series4, colors=colorZ2)
    ax3.plot(dates, series5, c='black', lw=3)

    ax2.tick_params(labeltop='off', labelright='off')  # labelright is not working
    ax3.tick_params(labeltop='off', labelright='off')  # labelright is not working

# How do you turn off ticks on the right ticks?

    ax3.legend([p5, p4, p3, p2, p1 ], [legendLabels[4],legendLabels[3],legendLabels[2],legendLabels[1],legendLabels[0]], loc='best', shadow=True)

    plt.title('\n'.join(wrap(titleForGraph,50)), fontsize=14)

    ax.set_ylabel(titleYlabel, fontsize=14)

# How do you get the label for the right to appear

    ax2.set_ylabel(titleYlabel2, fontsize=14) # not working
    ax3.set_ylabel(titleYlabel2, fontsize=14) # not working

    y_format = tkr.FuncFormatter(numFunc)
    ax.yaxis.set_major_formatter(y_format)

    props = dict(boxstyle='square', facecolor='none' )
    fig.text(.999, 0.01, 'EPRINC', style='oblique', ha='right', fontsize=10, bbox=props)
    fig.text(.001, 0.01, dataSource, style='oblique', ha='left', fontsize=10, bbox=props)
    ax.grid(True)
    fig.autofmt_xdate()

    plt.show()

def numFunc(x, pos):  # formatter function takes tick label and tick position
    s = '{:0,d}'.format(int(x))
    return s
</code>```

答:
Well, a little more tinkering, and now I'm getting the results that I want. I removed the ax2 = twiny(), and am now using ax2 = twinx().

I can post the code to illustrate, if there is an interest.

Thank you again for your help.

Body:
I have the following pyplot subroutine. All data passes correctly to the subroutine. However, I am not able to control two things:
1 - I can't make the right ticks disappear
2 - I can't place a 2nd y-label on the right axis

I've added an example image which has right-ticks that I'm trying to remove, and also trying to add a right-hand y-axis label.

Much thanks!

def makeChart(dataToGraph,  titleForGraph, titleYlabel, titleYlabel2, legendLabels, yMax, yMin, dataSource):

    fig, ax = plt.subplots()

    colorZ2 = ('#002060', 'red')
    colorZ1 = ( '#92D050', 'purple')
    p1 = plt.Rectangle((0, 0), 1, 1, fc='red')
    p2 = plt.Rectangle((0, 0), 1, 1, fc='#002060')
    p3 = plt.Rectangle((0, 0), 1, 0, fc='black')
    p4 = plt.Rectangle((0, 0), 1, 1, fc='#92D050')
    p5 = plt.Rectangle((0, 0), 1, 1, fc='purple')

#   plt.ylim(yMin, yMax)

    ax2 = ax.twinx()
    ax2 = ax.twiny()

    ax3 = ax.twinx()
    ax3 = ax.twiny()

    dates, series1, series2, series3, series4, series5 = zip(*dataToGraph)

    ax.stackplot(dates, series1, series2, colors=colorZ1)
    ax2.stackplot(dates, series3, series4, colors=colorZ2)
    ax3.plot(dates, series5, c='black', lw=3)

    ax2.tick_params(labeltop='off', labelright='off')  # labelright is not working
    ax3.tick_params(labeltop='off', labelright='off')  # labelright is not working

# How do you turn off ticks on the right ticks?

    ax3.legend([p5, p4, p3, p2, p1 ], [legendLabels[4],legendLabels[3],legendLabels[2],legendLabels[1],legendLabels[0]], loc='best', shadow=True)

    plt.title('\n'.join(wrap(titleForGraph,50)), fontsize=14)

    ax.set_ylabel(titleYlabel, fontsize=14)

# How do you get the label for the right to appear

    ax2.set_ylabel(titleYlabel2, fontsize=14) # not working
    ax3.set_ylabel(titleYlabel2, fontsize=14) # not working

    y_format = tkr.FuncFormatter(numFunc)
    ax.yaxis.set_major_formatter(y_format)

    props = dict(boxstyle='square', facecolor='none' )
    fig.text(.999, 0.01, 'EPRINC', style='oblique', ha='right', fontsize=10, bbox=props)
    fig.text(.001, 0.01, dataSource, style='oblique', ha='left', fontsize=10, bbox=props)
    ax.grid(True)
    fig.autofmt_xdate()

    plt.show()

def numFunc(x, pos):  # formatter function takes tick label and tick position
    s = '{:0,d}'.format(int(x))
    return s


问:
PHP array search
I'm trying to add some quick and simple search functionality to a site. The site has an XML file with all their stores, and I want to create a search box to search for the closest store to the user by town or postcode.

I have put all the data into an array, but as far as I can tell, there is no way to 'search' an array (NOT array_search) to retrieve results like using a MySQL LIKE query.

Surely there must be a way? Using MySQL isn't an option in this case.

答: I think your best bet here is to actually load the XML into a DOM object (DOMDocument or SimpleXML) and then use its XPath impelemntation. Its not SQL but its a lot less work than writing your own algorithm that consumes the array. Especially if you are talking about performing real distance calculations like you might with an SQL platform.</p>

ContentLicense: CC BY-SA 2.5

Title: PHP array search


问:
mysql timediff to hours
I'm Trying to get the timediff from my table and convert it to hours (it's for an hourly billed service)

SELECT TIME_TO_SEC(TIMEDIFF(endDate,startDate))/3600 FROM tasks >

where endDate and startDate are in datetime format

is there another way (more efficient) to do this task?
Thanks !

答:
```<code>select hour(timediff('2017-01-01 00:00:00', '2017-01-01 00:01:00'));
 return 1

select hour(timediff('2017-01-01 00:01:00', '2017-01-01 00:00:00'));
 return 1

select time_to_sec(timediff('2017-01-01 00:00:00', '2017-01-01 00:00:05'));
return -5

select time_to_sec(timediff('2017-01-01 00:00:00', '2017-01-01 00:00:05'))/60 as 'minutes' ;
return -0.0833
</code>```

<p>if you have the seconds you can convert it as you want or what
and hours(..) will not use it when i compare because it's always postive value </p>

Title: mysql timediff to hours

Body:
select hour(timediff('2017-01-01 00:00:00', '2017-01-01 00:01:00'));
 return 1

select hour(timediff('2017-01-01 00:01:00', '2017-01-01 00:00:00'));
 return 1

select time_to_sec(timediff('2017-01-01 00:00:00', '2017-01-01 00:00:05'));
return -5

select time_to_sec(timediff('2017-01-01 00:00:00', '2017-01-01 00:00:05'))/60 as 'minutes' ;
return -0.0833

if you have the seconds you can convert it as you want or what
and hours(..) will not use it when i compare because it's always postive value


问:
Java looping array pattern
I was wondering if I could get some help with the following problem. I need to create an array that displays its output in a certain format, but I cannot seem to figure out how to actually get it to do so. The pattern is a little difficult to explain in words  so I've attached an image that would showcase it.

The code provided below displays the output in the following fashion: Depending on the number the user enters, lets assume they entered 4, the output would be the following 4x4 array:

1 2 3 4

8 7 6 5

9 10 11 12

16 15 14 13

this clearly is not the pattern I am trying to achieve.. so any help would be appreciated!

public class Question2 {

```<code>public static void main(String[] args) {

//declare scanner
    Scanner keyboard = new Scanner (System.in);

//Prompt user to enter a digit greater than or equal to 3
    System.out.println("How many rows/columns do you want your array to have? (Must be at least 3):");

//read user input
    int num = keyboard.nextInt();

//place constraints on int num so that if it is less than 3, the program does not execute
    while(num<3 )
    {
        System.out.println("Lets's try this again....");
        System.out.println("How many rows/colums do you want your array to have? (Must be at least 3):");
        num = keyboard.nextInt();
    }

    //2D array with number of rows and columns entered by user
    int[][] array = new int [num][num];
    int inc=1;

    for(int i=0;i<array.length;i++)
    {
        if(i%2 == 0){
            for(int j=0;j<array.length;j++)
            {
                array[i][j]=inc;
                inc++;
            }
        }
        else{
            for(int j=num-1;j>=0;j--)
            {
                array[i][j]=inc;
                inc++;
            }
        }
    }

            //display formatted output
    String [][]stringConvertedTable= new String[num][num];

    for(int i=0; i<num; i++) {
        for(int j=0; j<num; j++) {
            stringConvertedTable[i][j]= Integer.toString(array[i][j]);
            System.out.print(stringConvertedTable[i][j] + "\t");
        }
        System.out.println("");
</code>```

答:
you can achieve the wrapping of the counter by applying the modulo operator with the size of the array

```<code>result[i][(k+i)%size] = counter++;
</code>```

how about this?

```<code>    final int size = 5;
    int[][] result = new int[size][size];

    //the logic
    int counter = 1;
    for(int i = 0; i < size; i++) {
        for(int k = 0; k < size; k++) {
            result[i][(k+i)%size] = counter++;
        }
    }

    //just the output
    for(int i = 0; i < size; i++) {
        boolean isFirst = true;
        for(int k = 0; k < size; k++) {
            if(isFirst)
                isFirst = false;
            else
                System.out.print(", ");
            System.out.print(result[i][k]);
        }
        System.out.println();
    }
</code>```

output

```<code>1, 2, 3, 4, 5
10, 6, 7, 8, 9
14, 15, 11, 12, 13
18, 19, 20, 16, 17
22, 23, 24, 25, 21
</code>```

Title: Java looping array pattern

Body:
I was wondering if I could get some help with the following problem. I need to create an array that displays its output in a certain format, but I cannot seem to figure out how to actually get it to do so. The pattern is a little difficult to explain in words  so I've attached an image that would showcase it.

The code provided below displays the output in the following fashion: Depending on the number the user enters, lets assume they entered 4, the output would be the following 4x4 array:

1 2 3 4

8 7 6 5

9 10 11 12

16 15 14 13

this clearly is not the pattern I am trying to achieve.. so any help would be appreciated!

public class Question2 {

public static void main(String[] args) {

//declare scanner
    Scanner keyboard = new Scanner (System.in);

//Prompt user to enter a digit greater than or equal to 3
    System.out.println("How many rows/columns do you want your array to have? (Must be at least 3):");

//read user input
    int num = keyboard.nextInt();

//place constraints on int num so that if it is less than 3, the program does not execute
    while(num<3 )
    {
        System.out.println("Lets's try this again....");
        System.out.println("How many rows/colums do you want your array to have? (Must be at least 3):");
        num = keyboard.nextInt();
    }

    //2D array with number of rows and columns entered by user
    int[][] array = new int [num][num];
    int inc=1;

    for(int i=0;i<array.length;i++)
    {
        if(i%2 == 0){
            for(int j=0;j<array.length;j++)
            {
                array[i][j]=inc;
                inc++;
            }
        }
        else{
            for(int j=num-1;j>=0;j--)
            {
                array[i][j]=inc;
                inc++;
            }
        }
    }

            //display formatted output
    String [][]stringConvertedTable= new String[num][num];

    for(int i=0; i<num; i++) {
        for(int j=0; j<num; j++) {
            stringConvertedTable[i][j]= Integer.toString(array[i][j]);
            System.out.print(stringConvertedTable[i][j] + "\t");
        }
        System.out.println("");

Body:
you can achieve the wrapping of the counter by applying the modulo operator with the size of the array

result[i][(k+i)%size] = counter++;

how about this?

    final int size = 5;
    int[][] result = new int[size][size];

    //the logic
    int counter = 1;
    for(int i = 0; i < size; i++) {
        for(int k = 0; k < size; k++) {
            result[i][(k+i)%size] = counter++;
        }
    }

    //just the output
    for(int i = 0; i < size; i++) {
        boolean isFirst = true;
        for(int k = 0; k < size; k++) {
            if(isFirst)
                isFirst = false;
            else
                System.out.print(", ");
            System.out.print(result[i][k]);
        }
        System.out.println();
    }

output

1, 2, 3, 4, 5
10, 6, 7, 8, 9
14, 15, 11, 12, 13
18, 19, 20, 16, 17
22, 23, 24, 25, 21


问:
Vue component $(...).owlCarousel is not a function
I have the next issue.

I'm using Laravel 5.4 with vue components. I want to use owl carousel 2 in my app.

I have the next code in a script tag and it works:

```<code>$(".owl-1").owlCarousel({items: 1, singleItem:true, loop: true});

$(".owl-2").owlCarousel({items: 1, singleItem:true, loop: true,mouseDrag: false, touchDrag: false, pullDrag: false, freeDrag: false});

$(".owl-1").on('change.owl.carousel', function(event) {
 if (event.namespace && event.property.name === 'position') {
 var target = event.relatedTarget.relative(event.property.value, true);
     $(".owl-2").owlCarousel('to', target, 300, true);
 }
});
</code>```

When I load the page when it is my owl html structure works very well, but when I try to use owl carousel inside my vue component it show me the next error.

```<code>$(...).owlCarousel is not a function.
</code>```

I have the next code on the bottom of my html

```<code><script src="/assets/js/owl.carousel.min.js"></script>
<script src="/assets/js/main.js"></script>
</code>```

I'm don't know if I need to intall it with npm, I was looking in npm and I didn't find it then I add the css and js files in my assets files.

Any ideas?
Thanks in advance.

答:
I think this is what you are looking for:

https://www.npmjs.com/package/owl.carousel

They also have instruction about using it with webpack, hope that helps!

Body:
I have the next issue.

I'm using Laravel 5.4 with vue components. I want to use owl carousel 2 in my app.

I have the next code in a script tag and it works:

$(".owl-1").owlCarousel({items: 1, singleItem:true, loop: true});

$(".owl-2").owlCarousel({items: 1, singleItem:true, loop: true,mouseDrag: false, touchDrag: false, pullDrag: false, freeDrag: false});

$(".owl-1").on('change.owl.carousel', function(event) {
 if (event.namespace && event.property.name === 'position') {
 var target = event.relatedTarget.relative(event.property.value, true);
     $(".owl-2").owlCarousel('to', target, 300, true);
 }
});

When I load the page when it is my owl html structure works very well, but when I try to use owl carousel inside my vue component it show me the next error.

$(...).owlCarousel is not a function.

I have the next code on the bottom of my html

I'm don't know if I need to intall it with npm, I was looking in npm and I didn't find it then I add the css and js files in my assets files.

Any ideas?
Thanks in advance.


问:
Resolving ORA-4031 "unable to allocate x bytes of shared memory"
I need some pointers on how to diagnose and fix this problem. I don't know if this is a simple server setup problem or an application design problem (or both).

Once or twice every few months this Oracle XE database reports ORA-4031 errors. It doesn't point to any particular part of the sga consistently. A recent example is:

ORA-04031: unable to allocate 8208 bytes of shared memory ("large pool","unknown object","sort subheap","sort key")

When this error comes up, if the user keeps refreshing, clicking on different links, they'll generally get more of these kinds of errors at different times, then soon they'll get "404 not found" page errors.

Restarting the database usually resolves the problem for a while, then a month or so later it comes up again, but rarely at the same location in the program (i.e. it doesn't seem linked to any particular portion of code) (the above example error was raised from an Apex page which was sorting 5000+ rows from a table).

I've tried increasing sga_max_size from 140M to 256M and hope this will help things. Of course, I won't know if this has helped since I had to restart the database to change the setting :)

I'm running Oracle XE 10.2.0.1.0 on a Oracle Enterprise Linux 5 box with 512MB of RAM. The server only runs the database, Oracle Apex (v3.1.2) and Apache web server. I installed it with pretty much all default parameters and it's been running quite well for a year or so. Most issues I've been able to resolve myself by tuning the application code; it's not intensively used and isn't a business critical system.

These are some current settings I think may be relevant:

```<code>pga_aggregate_target        41,943,040
sga_max_size              268,435,456
sga_target                146,800,640
shared_pool_reserved_size   5,452,595
shared_pool_size          104,857,600
</code>```

If it's any help here's the current SGA sizes:

```<code>Total System Global Area  268435456 bytes
Fixed Size                  1258392 bytes
Variable Size             251661416 bytes
Database Buffers           12582912 bytes
Redo Buffers                2932736 bytes
</code>```

答:
All of the current answers are addressing the symptom (shared memory pool exhaustion), and not the problem, which is likely not using bind variables in your sql \ JDBC queries, even when it does not seem necessary to do so. Passing queries without bind variables causes Oracle to "hard parse" the query each time, determining its plan of execution, etc.

https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::p11_question_id:528893984337

Some snippets from the above link:

"Java supports bind variables, your developers must start using prepared statements and bind inputs into it. If you want your system to ultimately scale beyond say about 3 or 4 users -- you will do this right now (fix the code). It is not something to think about, it is something you MUST do. A side effect of this - your shared pool problems will pretty much disappear. That is the root cause. "

"The way the Oracle
shared pool (a very important shared memory data structure)
operates is predicated on developers using bind variables."

" Bind variables are SO MASSIVELY important -- I cannot in any way shape or form OVERSTATE their importance. "

Body:
I need some pointers on how to diagnose and fix this problem. I don't know if this is a simple server setup problem or an application design problem (or both).

Once or twice every few months this Oracle XE database reports ORA-4031 errors. It doesn't point to any particular part of the sga consistently. A recent example is:

ORA-04031: unable to allocate 8208 bytes of shared memory ("large pool","unknown object","sort subheap","sort key")

When this error comes up, if the user keeps refreshing, clicking on different links, they'll generally get more of these kinds of errors at different times, then soon they'll get "404 not found" page errors.

Restarting the database usually resolves the problem for a while, then a month or so later it comes up again, but rarely at the same location in the program (i.e. it doesn't seem linked to any particular portion of code) (the above example error was raised from an Apex page which was sorting 5000+ rows from a table).

I've tried increasing sga_max_size from 140M to 256M and hope this will help things. Of course, I won't know if this has helped since I had to restart the database to change the setting :)

I'm running Oracle XE 10.2.0.1.0 on a Oracle Enterprise Linux 5 box with 512MB of RAM. The server only runs the database, Oracle Apex (v3.1.2) and Apache web server. I installed it with pretty much all default parameters and it's been running quite well for a year or so. Most issues I've been able to resolve myself by tuning the application code; it's not intensively used and isn't a business critical system.

These are some current settings I think may be relevant:

pga_aggregate_target        41,943,040
sga_max_size              268,435,456
sga_target                146,800,640
shared_pool_reserved_size   5,452,595
shared_pool_size          104,857,600

If it's any help here's the current SGA sizes:

Total System Global Area  268435456 bytes
Fixed Size                  1258392 bytes
Variable Size             251661416 bytes
Database Buffers           12582912 bytes
Redo Buffers                2932736 bytes


问:
Catching child process exceptions on windows
i'm developing a multi-platform C++ fuzzing application. The app spawns a child process and checks whether it stopped unexpectedly. I've already managed to do this on linux, however, windows exception handling mechanism is making things hard for me.

My code right now does the following:
- Call CreateProcess to spawn the process.
- WaitForSingleObject to wait for it to terminate.
- Then call GetExitCodeProcess and check if the exit code corresponds to an exception.

Everything works as it should, i've tested it with a null dereferencing test application, and i can catch the exception gracefully. However, each time i test this, a Windows error message box spawns telling me to Send or Not Send the error report. Since the fuzzer is supposed to be an automatic testing application, i'd need to somehow disable this notification, so that even if an exception is caught, the fuzzer can continue testing.

I've already tried installing a SEH handler, but had no luck(apparently these handlers aren't inherited by child processes). I've read something about using vectored exception handling, but suppose it would be the same, i believe vector handlers aren't inherited.

Could anybody help me with this problem? I don't know what to search for, i've already googled a lot and haven't found anyhing.

Thanks!

答:
Try to inject the following code into your child process:

```<code>SetErrorMode(SEM_NOGPFAULTERRORBOX);
</code>```

Lookup the details of SetErrorMode in MSDN.

Read about injection technique here:
Injective Code inside Import Table

Body:
Try to inject the following code into your child process:

SetErrorMode(SEM_NOGPFAULTERRORBOX);

Lookup the details of SetErrorMode in MSDN.

Read about injection technique here:
Injective Code inside Import Table


问:
Is it possibile set up Storm on a single raspberry pi 3?
I've seen on StackOverflow that's possibile develop a cluster composed of a single node.
My challenge is maybe harder: setting an apache storm environment on a single raspberry pi 3. I know that is a very limited machine to do stream computing, but mine is a research interest. Until now, I have not found system requirements to setup storm on a machine, someone can help me?

Thanks to all

答:
Yes, Ideally it should be possible once you have Linux OS installed for e.g. Ubuntu Mate on Raspberry Pi 3.

You may be required to make sure you have these packages installed:

Java 7

Python 2.

Then follow below link for a basic setup of Storm:

https://github.com/vrmorusu/Storm/wiki/Apache-Storm-on-Cloudera-VM

You may build uberjar files containing Storm topology files on your local machines to avoid installation of maven and other build tool dependencies.

It would be great if you can try this and post your success story or issues seen in this forum. It will help getting more focused answer(s) for problem(s).


问:
PHPExcel getCellCollection is always points to lastsheet in my excel
I am using PHPExcel plugin in codeigniter
and my requirement is i have a excel file with multiple sheets

by using below code i am trying to get some data from excel sheets
in looping with getAllSheets,getCellCollection is always pointing to the last only

example my out

```<code>Array ( [0] => Array ( [timing] => Array ( [0] => 10:30 PM [1] => 7:30 AM ) [header] => Array ( [4] => Array ( [D] => 2017-03-27 [E] => 2017-03-28 [F] => 2017-03-29 [G] => 2017-03-30 [H] => 2017-03-31 ) ) [arr_data] => Array ( [5] => Array ( [A] => Damojipurapu Venkata Raghavendra Praveen [B] => Array ( [0] => Railway new colony [1] => 9052932938 ) [C] => 08:50 PM [G] => OFF ) [6] => Array ( [A] => Seerapu Venkata Rao [B] => Array ( [0] => Maharanipeta [1] => 9701964583 ) [C] => 09:00 PM ) [7] => Array ( [A] => Challa Vinod Kumar [B] => Array ( [0] => Chinna Walter [1] => 9963463234 ) [C] => 09:10 PM [D] => 6:00AM [E] => OFF ) [8] => Array ( [A] => Satish Kumar [B] => Array ( [0] => Maruthi Paradise, Opp Vilas Rest,PM palem [1] => 9731347726 ) [C] => 09:20 PM ) [9] => Array ( [A] => Bandi Saketh Reddy [B] => Array ( [0] => Madhurwada [1] => 8501999751 ) [C] => 09:40 PM [H] => OFF ) [10] => Array ( [A] => D Selvaa Murugan [B] => Array ( [0] => Car Shed Madhurwada [1] => 9043287087 ) [C] => 09:50 PM ) ) ) [1] => Array ( [timing] => Array ( [0] => 10:30 PM [1] => 7:30 AM ) [header] => Array ( [4] => Array ( [D] => 2017-03-27 [E] => 2017-03-28 [F] => 2017-03-29 [G] => 2017-03-30 [H] => 2017-03-31 ) ) [arr_data] => Array ( [5] => Array ( [A] => Damojipurapu Venkata Raghavendra Praveen [B] => Array ( [0] => Railway new colony [1] => 9052932938 ) [C] => 08:50 PM [G] => OFF ) [6] => Array ( [A] => Seerapu Venkata Rao [B] => Array ( [0] => Maharanipeta [1] => 9701964583 ) [C] => 09:00 PM ) [7] => Array ( [A] => Challa Vinod Kumar [B] => Array ( [0] => Chinna Walter [1] => 9963463234 ) [C] => 09:10 PM [D] => 6:00AM [E] => OFF ) [8] => Array ( [A] => Satish Kumar [B] => Array ( [0] => Maruthi Paradise, Opp Vilas Rest,PM palem [1] => 9731347726 ) [C] => 09:20 PM ) [9] => Array ( [A] => Bandi Saketh Reddy [B] => Array ( [0] => Madhurwada [1] => 8501999751 ) [C] => 09:40 PM [H] => OFF ) [10] => Array ( [A] => D Selvaa Murugan [B] => Array ( [0] => Car Shed Madhurwada [1] => 9043287087 ) [C] => 09:50 PM ) ) ) )
</code>```

and my code is

```<code>try {
                $fileType = PHPExcel_IOFactory::identify($file["tmp_name"]);
                $objReader = PHPExcel_IOFactory::createReader($fileType);
                $objPHPExcel = $objReader->load($file["tmp_name"]);
                $all_data=array();
                foreach ($objPHPExcel->getAllSheets() as $sheet) {
                    //echo $sheet->getTitle()."<br>";
                    $cell_collection = $sheet->getCellCollection();
                    //print_r($cell_collection);
                    foreach ($cell_collection as $cell) {
                        $c=$objPHPExcel->getActiveSheet()->getCell($cell);
                        $column = $c->getColumn();
                        $row = $c->getRow();
                        $data_value = $c->getValue();
                        if(strstr($data_value,'=')==true)
                        {
                            $data_value = $c->getOldCalculatedValue();
                        }
                        if ($row == 3) {
                            if(count($data_value)>0){
                                $a = explode("Shift: ",$data_value);
                                $data["timing"] =array_map('trim',explode("-",$a[1]));
                            }
                        }else if ($row == 4){
                            if($column!='A'&&$column!='B'&&$column!='C'){
                                if (PHPExcel_Shared_Date::isDateTime($c)) {
                                    $data_value = PHPExcel_Shared_Date::ExcelToPHPObject($c->getValue())->format('Y-m-d');
                                }
                                if(count($data_value)>0)
                                    $data["header"][$row][$column] = $data_value;
                            }

                        }else if ($row > 4){
                            if($column=='B'){
                                if(count($data_value)>0)
                                $data_value=array_map('trim',explode("/",$data_value));
                            }
                            if($column=='C'){
                                if (PHPExcel_Shared_Date::isDateTime($c)) {
                                    $data_value = PHPExcel_Shared_Date::ExcelToPHPObject($c->getValue())->format('h:i A');
                                }
                            }
                            if(count($data_value)>0)
                            $data["arr_data"][$row][$column] = $data_value;
                        }
                    }
                    array_push($all_data, $data);
                    $data=array();

                }
                //echo "```";
                print_r($all_data);
                exit;
            }catch (Exception $ex) {}
```

答:
Thank you,
I found Solution

Actually i need to get data $sheet not with $objPHPExcel->getActiveSheet(),
by doing this it causes to always read data from the sheet where we last saved that excel file,
I just change this line

```<code>$c=$objPHPExcel->getActiveSheet()->getCell($cell);
</code>```

to

```<code>$c=$sheet->getCell($cell);
</code>```

then its fixed for me

Once agian thanks to all

Body:
I am using PHPExcel plugin in codeigniter
and my requirement is i have a excel file with multiple sheets

by using below code i am trying to get some data from excel sheets
in looping with getAllSheets,getCellCollection is always pointing to the last only

example my out

Array ( [0] => Array ( [timing] => Array ( [0] => 10:30 PM [1] => 7:30 AM ) [header] => Array ( [4] => Array ( [D] => 2017-03-27 [E] => 2017-03-28 [F] => 2017-03-29 [G] => 2017-03-30 [H] => 2017-03-31 ) ) [arr_data] => Array ( [5] => Array ( [A] => Damojipurapu Venkata Raghavendra Praveen [B] => Array ( [0] => Railway new colony [1] => 9052932938 ) [C] => 08:50 PM [G] => OFF ) [6] => Array ( [A] => Seerapu Venkata Rao [B] => Array ( [0] => Maharanipeta [1] => 9701964583 ) [C] => 09:00 PM ) [7] => Array ( [A] => Challa Vinod Kumar [B] => Array ( [0] => Chinna Walter [1] => 9963463234 ) [C] => 09:10 PM [D] => 6:00AM [E] => OFF ) [8] => Array ( [A] => Satish Kumar [B] => Array ( [0] => Maruthi Paradise, Opp Vilas Rest,PM palem [1] => 9731347726 ) [C] => 09:20 PM ) [9] => Array ( [A] => Bandi Saketh Reddy [B] => Array ( [0] => Madhurwada [1] => 8501999751 ) [C] => 09:40 PM [H] => OFF ) [10] => Array ( [A] => D Selvaa Murugan [B] => Array ( [0] => Car Shed Madhurwada [1] => 9043287087 ) [C] => 09:50 PM ) ) ) [1] => Array ( [timing] => Array ( [0] => 10:30 PM [1] => 7:30 AM ) [header] => Array ( [4] => Array ( [D] => 2017-03-27 [E] => 2017-03-28 [F] => 2017-03-29 [G] => 2017-03-30 [H] => 2017-03-31 ) ) [arr_data] => Array ( [5] => Array ( [A] => Damojipurapu Venkata Raghavendra Praveen [B] => Array ( [0] => Railway new colony [1] => 9052932938 ) [C] => 08:50 PM [G] => OFF ) [6] => Array ( [A] => Seerapu Venkata Rao [B] => Array ( [0] => Maharanipeta [1] => 9701964583 ) [C] => 09:00 PM ) [7] => Array ( [A] => Challa Vinod Kumar [B] => Array ( [0] => Chinna Walter [1] => 9963463234 ) [C] => 09:10 PM [D] => 6:00AM [E] => OFF ) [8] => Array ( [A] => Satish Kumar [B] => Array ( [0] => Maruthi Paradise, Opp Vilas Rest,PM palem [1] => 9731347726 ) [C] => 09:20 PM ) [9] => Array ( [A] => Bandi Saketh Reddy [B] => Array ( [0] => Madhurwada [1] => 8501999751 ) [C] => 09:40 PM [H] => OFF ) [10] => Array ( [A] => D Selvaa Murugan [B] => Array ( [0] => Car Shed Madhurwada [1] => 9043287087 ) [C] => 09:50 PM ) ) ) )

and my code is

try {
                $fileType = PHPExcel_IOFactory::identify($file["tmp_name"]);
                $objReader = PHPExcel_IOFactory::createReader($fileType);
                $objPHPExcel = $objReader->load($file["tmp_name"]);
                $all_data=array();
                foreach ($objPHPExcel->getAllSheets() as $sheet) {
                    //echo $sheet->getTitle()."
";
                    $cell_collection = $sheet->getCellCollection();
                    //print_r($cell_collection);
                    foreach ($cell_collection as $cell) {
                        $c=$objPHPExcel->getActiveSheet()->getCell($cell);
                        $column = $c->getColumn();
                        $row = $c->getRow();
                        $data_value = $c->getValue();
                        if(strstr($data_value,'=')==true)
                        {
                            $data_value = $c->getOldCalculatedValue();
                        }
                        if ($row == 3) {
                            if(count($data_value)>0){
                                $a = explode("Shift: ",$data_value);
                                $data["timing"] =array_map('trim',explode("-",$a[1]));
                            }
                        }else if ($row == 4){
                            if($column!='A'&&$column!='B'&&$column!='C'){
                                if (PHPExcel_Shared_Date::isDateTime($c)) {
                                    $data_value = PHPExcel_Shared_Date::ExcelToPHPObject($c->getValue())->format('Y-m-d');
                                }
                                if(count($data_value)>0)
                                    $data["header"][$row][$column] = $data_value;
                            }

                        }else if ($row > 4){
                            if($column=='B'){
                                if(count($data_value)>0)
                                $data_value=array_map('trim',explode("/",$data_value));
                            }
                            if($column=='C'){
                                if (PHPExcel_Shared_Date::isDateTime($c)) {
                                    $data_value = PHPExcel_Shared_Date::ExcelToPHPObject($c->getValue())->format('h:i A');
                                }
                            }
                            if(count($data_value)>0)
                            $data["arr_data"][$row][$column] = $data_value;
                        }
                    }
                    array_push($all_data, $data);
                    $data=array();

                }
                //echo "
";
                print_r($all_data);
                exit;
            }catch (Exception $ex) {}

Body:
Thank you,
I found Solution

Actually i need to get data $sheet not with $objPHPExcel->getActiveSheet(),
by doing this it causes to always read data from the sheet where we last saved that excel file,
I just change this line

$c=$objPHPExcel->getActiveSheet()->getCell($cell);

to

$c=$sheet->getCell($cell);

then its fixed for me

Once agian thanks to all


问:
Mock deep level methods
I´m using Moq to mock some objects of my application, and for now, I need to mock this call:

```<code>accessor.HttpContext.Session.GetInt32("offset");
</code>```

I have tried to do this way, but not works:

```<code>var mock = new Mock<HttpContextAccessor>();
        mock.Setup(x => x.HttpContext.Session.GetInt32("offset"))
            .Returns(0);
</code>```

It fires this error:

System.NotSupportedException : Expression references a method that does not belong to the mocked object: x => x.HttpContext.Session.GetInt32("offset")

答: GetInt32 is an extension method that operates on the ISession interface. You need to mock the ISession interface so that the TryGetValue method returns the expected value (GetInt32 call Get which calls TryGetValue on the ISession interface) and then return the mock from the HttpContext.Session

Title: Mock deep level methods

Body:
I´m using Moq to mock some objects of my application, and for now, I need to mock this call:

accessor.HttpContext.Session.GetInt32("offset");

I have tried to do this way, but not works:

var mock = new Mock<HttpContextAccessor>();
        mock.Setup(x => x.HttpContext.Session.GetInt32("offset"))
            .Returns(0);

It fires this error:

System.NotSupportedException : Expression references a method that does not belong to the mocked object: x => x.HttpContext.Session.GetInt32("offset")


问:
Evenly sized columns between rows using grid/flex
Consider the following snippet:

#container{
  border: solid 1px black;
  display: inline-grid;
  grid-template-columns: repeat(3, auto);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div class="row">
    <div class="item">A1111</div>
    <div class="item">B1</div>
    <div class="item">C1</div>
  </div>
  <div class="row">
    <div class="item">A2</div>
    <div class="item">B2222</div>
    <div class="item">C2</div>
  </div>
  <div class="row">
    <div class="item">A3</div>
    <div class="item">B3</div>
    <div class="item">C3333</div>
  </div>
</div></code>```

The end result is a table-like display where each item of every row is the width of the widest item in that column.

```<code>A1111 A2    A3
B1    B2222 B3
C1    C2    C3333
</code>```

Which is great - but I need the table laid out as rows...

```<code>A1111 B1    C1
A2    B2222 C2
A3    B3    C3333
</code>```

display: table solves this - but table has some drawbacks around spacing, alignments and so-on. Therefore, grid and flex looks attractive.

Alas I cannot figure out how to get the information laid out as desired.

Adding display: grid to .row helps the order of information, but doesn't retain the equal column widths.

The item content will vary, and so cannot use fixed widths and it is not desired that the grid/flex spans the entire page/containing width.

答:
Your main problem is your markup is too deep. You have table-like markup, three levels deep: table, rows, and cells. For grid layout, you don’t need the “row” elements at all.

When you use display: grid or display: inline-grid on an element, it makes that element a grid container. Each of its child elements then become grid items. Grid items will be laid out in the grid defined by their container.

You also said you want columns of equal width. For this, you should use the fr unit rather than auto for your column sizes:

```<code>grid-template-columns: repeat(3, 1fr);
</code>```

…this will make each column one “fraction” unit wide.

#container{
  border: solid 1px black;
  display: inline-grid;
  grid-template-columns: repeat(3, 1fr);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div class="item">A1111</div>
  <div class="item">B1</div>
  <div class="item">C1</div>
  <div class="item">A2</div>
  <div class="item">B2222</div>
  <div class="item">C2</div>
  <div class="item">A3</div>
  <div class="item">B3</div>
  <div class="item">C3333</div>
</div></code>```

Body:
Consider the following snippet:

#container{
  border: solid 1px black;
  display: inline-grid;
  grid-template-columns: repeat(3, auto);
}

A1111

B1

C1

A2

B2222

C2

A3

B3

C3333

The end result is a table-like display where each item of every row is the width of the widest item in that column.

A1111 A2    A3
B1    B2222 B3
C1    C2    C3333

Which is great - but I need the table laid out as rows...

A1111 B1    C1
A2    B2222 C2
A3    B3    C3333

display: table solves this - but table has some drawbacks around spacing, alignments and so-on. Therefore, grid and flex looks attractive.

Alas I cannot figure out how to get the information laid out as desired.

Adding display: grid to .row helps the order of information, but doesn't retain the equal column widths.

The item content will vary, and so cannot use fixed widths and it is not desired that the grid/flex spans the entire page/containing width.

Body:
Your main problem is your markup is too deep. You have table-like markup, three levels deep: table, rows, and cells. For grid layout, you don’t need the “row” elements at all.

When you use display: grid or display: inline-grid on an element, it makes that element a grid container. Each of its child elements then become grid items. Grid items will be laid out in the grid defined by their container.

You also said you want columns of equal width. For this, you should use the fr unit rather than auto for your column sizes:

grid-template-columns: repeat(3, 1fr);

…this will make each column one “fraction” unit wide.

#container{
  border: solid 1px black;
  display: inline-grid;
  grid-template-columns: repeat(3, 1fr);
}

<div id="container">
  <div class="item">A1111</div>
  <div class="item">B1</div>
  <div class="item">C1</div>
  <div class="item">A2</div>
  <div class="item">B2222</div>
  <div class="item">C2</div>
  <div class="item">A3</div>
  <div class="item">B3</div>
  <div class="item">C3333</div>
</div>


问:
Programmatically adjusting the number of rows in a grid with C#
I'm currently teaching myself XAML/C# and writing a calendar application. Right now it's creating a grid and then applying user control elements to the grid. It is correctly building my calendar but, instead of defining the number of rows in XAML, I want to be able to set the number via C# dynamically. Some months use more or less weeks (March needs 5 but April needs 6). I'm wondering how to do that or if I should be using a different control than grid.

This is what the UI looks like.

XAML code

```<code><UserControl x:Class="CMS.Control.MonthView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">

    <Grid VerticalAlignment="Stretch">
        <Grid.RowDefinitions>
            <RowDefinition Height="40"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal" Background="AliceBlue">
            <Image x:Name="MonthPrev" Source="/Images/Previous.png" Height="24" Margin="16,0,6,0" MouseLeftButtonUp="MonthPrev_MouseLeftButtonUp"/>
            <Image x:Name="MonthNext" Source="/Images/Next.png" Height="24" Margin="6,0,16,0" MouseLeftButtonUp="MonthNext_MouseLeftButtonUp"/>
            <Label x:Name="DateLabel" Content="January 2017" FontSize="16" FontFamily="Bold" VerticalAlignment="Center"/>
        </StackPanel>
        <Grid Grid.Row="1" Background="AliceBlue">
            <Grid.ColumnDefinitions>

                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
            </Grid.ColumnDefinitions>
            <Label Grid.Column="0" Content="Sunday" FontSize="9" Margin="2,0,0,2" Padding="0,1,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="0,0,1,0"/>
            <Label Grid.Column="1" Content="Monday" FontSize="9" Margin="2,0,0,2" Padding="0,1,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="0,0,1,0"/>
            <Label Grid.Column="2" Content="Tuesday" FontSize="9" Margin="2,0,0,2" Padding="0,1,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="0,0,1,0"/>
            <Label Grid.Column="3" Content="Wednesday" FontSize="9" Margin="2,0,0,2" Padding="0,1,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="0,0,1,0"/>
            <Label Grid.Column="4" Content="Thursday" FontSize="9" Margin="2,0,0,2" Padding="0,1,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="0,0,1,0"/>
            <Label Grid.Column="5" Content="Friday" FontSize="9" Margin="2,0,0,2" Padding="0,1,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="0,0,1,0"/>
            <Label Grid.Column="6" Content="Saturday" FontSize="9" Margin="2,0,0,2" Padding="0,1,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="0,0,1,0"/>
        </Grid>

        <Grid x:Name="WeekRowGrid" Grid.Row="2">
            <Grid.ColumnDefinitions>

                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>

            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
        </Grid>
    </Grid>
</UserControl>
</code>```

C# Code

```<code>namespace CMS.Control
{
    /// <summary>
    /// Interaction logic for MonthView.xaml
    /// </summary>
    public partial class MonthView : UserControl
    {
        private DateTime _DispayDate;

        public MonthView()
        {
            InitializeComponent();
            _DispayDate = DateTime.Now;
            DrawMonth();
        }

        //Generates the
        private void DrawMonth()
        {
            DateTime FirstDayOfMonth = new DateTime(_DispayDate.Year, _DispayDate.Month, 1);
            int DisplayFrontPadding = (int)FirstDayOfMonth.DayOfWeek; // # of days that need to be displayed before the 1st of the month
            int DaysInDisplayMonth = DateTime.DaysInMonth(_DispayDate.Year, _DispayDate.Month);
            int DaysInDisplay = DisplayFrontPadding + DaysInDisplayMonth;
            DaysInDisplay += 7 - DaysInDisplay%7; // Rounds up the displayed days to a multiple of 7

            DateLabel.Content = _DispayDate.ToString("MMMM") + " " + _DispayDate.Year;

            for (int i = 0; i<DaysInDisplay; i++)
            {
                DateTime DisplayDay = FirstDayOfMonth.AddDays(i - DisplayFrontPadding);
                DayBox DB = DayBox.GetDay();   // DayBox factory
                DB.DrawDay(DisplayDay);

                Grid.SetRow(DB, i / 7);
                WeekRowGrid.Children.Add(DB);
                Grid.SetColumn(DB, i%7);
            }
        }

        //Generates a calendar for the previous month on button click.
        private void MonthPrev_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _DispayDate = _DispayDate.AddMonths(-1);
            DrawMonth();
        }

        //Generates a calendar for the next month on button click.
        private void MonthNext_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _DispayDate = _DispayDate.AddMonths(1);
            DrawMonth();
        }
    }
}
</code>```

I know I should really be using MVVM but I'm still wrapping my brain around programming in MVVM pattern and want to get this working. I'll probably refactor it once I'm more comfortable with it.

答:
You could create a method that adjust the number of rows automatically based on the number of weeks (rows). This method always remove all the rows and then add the correct number of rows you need. </p>

```<code>private void AdjustRowDefinitions(int numberOfWeeks)
{
    WeekRowGrid.RowDefinitions.Clear();
    for (int i = 0; i < numberOfWeeks; i++)
    {
        RowDefinition rowDef = new RowDefinition();
        rowDef.Height = new GridLength(1, GridUnitType.Star); //this sets the height of the row to *
        WeekRowGrid.RowDefinitions.Add(rowDef);
    }
}
</code>```

Body:
I'm currently teaching myself XAML/C# and writing a calendar application. Right now it's creating a grid and then applying user control elements to the grid. It is correctly building my calendar but, instead of defining the number of rows in XAML, I want to be able to set the number via C# dynamically. Some months use more or less weeks (March needs 5 but April needs 6). I'm wondering how to do that or if I should be using a different control than grid.

This is what the UI looks like.

XAML code

<UserControl x:Class="CMS.Control.MonthView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">

    <Grid VerticalAlignment="Stretch">
        <Grid.RowDefinitions>
            <RowDefinition Height="40"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal" Background="AliceBlue">
            <Image x:Name="MonthPrev" Source="/Images/Previous.png" Height="24" Margin="16,0,6,0" MouseLeftButtonUp="MonthPrev_MouseLeftButtonUp"/>
            <Image x:Name="MonthNext" Source="/Images/Next.png" Height="24" Margin="6,0,16,0" MouseLeftButtonUp="MonthNext_MouseLeftButtonUp"/>

        </StackPanel>
        <Grid Grid.Row="1" Background="AliceBlue">
            <Grid.ColumnDefinitions>

                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
            </Grid.ColumnDefinitions>

        </Grid>

        <Grid x:Name="WeekRowGrid" Grid.Row="2">
            <Grid.ColumnDefinitions>

                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>

            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
        </Grid>
    </Grid>
</UserControl>

C# Code

namespace CMS.Control
{
    ///
    /// Interaction logic for MonthView.xaml
    ///
    public partial class MonthView : UserControl
    {
        private DateTime _DispayDate;

        public MonthView()
        {
            InitializeComponent();
            _DispayDate = DateTime.Now;
            DrawMonth();
        }

        //Generates the
        private void DrawMonth()
        {
            DateTime FirstDayOfMonth = new DateTime(_DispayDate.Year, _DispayDate.Month, 1);
            int DisplayFrontPadding = (int)FirstDayOfMonth.DayOfWeek; // # of days that need to be displayed before the 1st of the month
            int DaysInDisplayMonth = DateTime.DaysInMonth(_DispayDate.Year, _DispayDate.Month);
            int DaysInDisplay = DisplayFrontPadding + DaysInDisplayMonth;
            DaysInDisplay += 7 - DaysInDisplay%7; // Rounds up the displayed days to a multiple of 7

            DateLabel.Content = _DispayDate.ToString("MMMM") + " " + _DispayDate.Year;

            for (int i = 0; i<DaysInDisplay; i++)
            {
                DateTime DisplayDay = FirstDayOfMonth.AddDays(i - DisplayFrontPadding);
                DayBox DB = DayBox.GetDay();   // DayBox factory
                DB.DrawDay(DisplayDay);

                Grid.SetRow(DB, i / 7);
                WeekRowGrid.Children.Add(DB);
                Grid.SetColumn(DB, i%7);
            }
        }

        //Generates a calendar for the previous month on button click.
        private void MonthPrev_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _DispayDate = _DispayDate.AddMonths(-1);
            DrawMonth();
        }

        //Generates a calendar for the next month on button click.
        private void MonthNext_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _DispayDate = _DispayDate.AddMonths(1);
            DrawMonth();
        }
    }
}

I know I should really be using MVVM but I'm still wrapping my brain around programming in MVVM pattern and want to get this working. I'll probably refactor it once I'm more comfortable with it.

Body:
You could create a method that adjust the number of rows automatically based on the number of weeks (rows). This method always remove all the rows and then add the correct number of rows you need.

private void AdjustRowDefinitions(int numberOfWeeks)
{
    WeekRowGrid.RowDefinitions.Clear();
    for (int i = 0; i < numberOfWeeks; i++)
    {
        RowDefinition rowDef = new RowDefinition();
        rowDef.Height = new GridLength(1, GridUnitType.Star); //this sets the height of the row to *
        WeekRowGrid.RowDefinitions.Add(rowDef);
    }
}


问:
Updating SDK to 25 starts giving ClassNotFoundException error message
I was using SDK 23 in my project and everything was working fine.

This was my gradle file when everything was working fine.

```<code>    compileSdkVersion 23
    buildToolsVersion "23.0.3"

defaultConfig {
      applicationId 'com.example.app'
        minSdkVersion 21
        targetSdkVersion 23
        multiDexEnabled true
}

dependencies {
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'com.android.support:support-v4:23.3.0'
    compile 'com.android.support:cardview-v7:23.3.0'
    compile 'com.android.support:recyclerview-v7:23.3.0'
}
</code>```

I have updated it to API 25

```<code>compileSdkVersion 25
buildToolsVersion "25.0.0"

defaultConfig {
      applicationId 'com.example.app'
        minSdkVersion 21
        targetSdkVersion 25
        multiDexEnabled true
}

dependencies {
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.android.support:design:25.0.0'
compile 'com.android.support:support-v4:25.0.0'
compile 'com.android.support:cardview-v7:25.0.0'
 compile 'com.android.support:recyclerview-v7:25.0.0'
}
</code>```

So now it runs the project successfully, but one of my activity which is  using Google VR has started giving me following error messages.

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
                                                                 Process: com.example.app, PID: 32413
                                                                 java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/vr/sdk/widgets/video/VrVideoView$Options;
                                                                     at com.example.app.ThreeSixtyActivity.<init>(ThreeSixtyActivity.java:97)
                                                                     at java.lang.reflect.Constructor.newInstance(Native Method)
                                                                     at java.lang.Class.newInstance(Class.java:1650)

 Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.vr.sdk.widgets.video.VrVideoView$Options" on path: DexPathList[[zip file "/data/app/com.example.app-2/base.apk"],nativeLibraryDirectories=[/data/app/com.example.app-2/lib/arm, /vendor/lib, /system/lib]]
                                                                     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                                     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)

   Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
</code>```

This is the line where its giving error message

```<code>/** Configuration information for the video. **/
private Options videoOptions = new Options();
</code>```

The error is  only happening on lollipop devices, Marshmallow is working fine.

答:
The only thing that really helps to use latest libraries is here:

```<code>public class AppClass extends Application {

//this will initialize multidex in your own Application class
@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
}
</code>```

}

Body:
I was using SDK 23 in my project and everything was working fine.

This was my gradle file when everything was working fine.

    compileSdkVersion 23
    buildToolsVersion "23.0.3"

defaultConfig {
      applicationId 'com.example.app'
        minSdkVersion 21
        targetSdkVersion 23
        multiDexEnabled true
}

dependencies {
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'com.android.support:support-v4:23.3.0'
    compile 'com.android.support:cardview-v7:23.3.0'
    compile 'com.android.support:recyclerview-v7:23.3.0'
}

I have updated it to API 25

compileSdkVersion 25
buildToolsVersion "25.0.0"

defaultConfig {
      applicationId 'com.example.app'
        minSdkVersion 21
        targetSdkVersion 25
        multiDexEnabled true
}

dependencies {
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.android.support:design:25.0.0'
compile 'com.android.support:support-v4:25.0.0'
compile 'com.android.support:cardview-v7:25.0.0'
 compile 'com.android.support:recyclerview-v7:25.0.0'
}

So now it runs the project successfully, but one of my activity which is  using Google VR has started giving me following error messages.

E/AndroidRuntime: FATAL EXCEPTION: main
                                                                 Process: com.example.app, PID: 32413
                                                                 java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/vr/sdk/widgets/video/VrVideoView$Options;
                                                                     at com.example.app.ThreeSixtyActivity.<init>(ThreeSixtyActivity.java:97)
                                                                     at java.lang.reflect.Constructor.newInstance(Native Method)
                                                                     at java.lang.Class.newInstance(Class.java:1650)

 Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.vr.sdk.widgets.video.VrVideoView$Options" on path: DexPathList[[zip file "/data/app/com.example.app-2/base.apk"],nativeLibraryDirectories=[/data/app/com.example.app-2/lib/arm, /vendor/lib, /system/lib]]
                                                                     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                                     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)

   Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

This is the line where its giving error message

/** Configuration information for the video. **/
private Options videoOptions = new Options();

The error is  only happening on lollipop devices, Marshmallow is working fine.

Body:
The only thing that really helps to use latest libraries is here:

public class AppClass extends Application {

//this will initialize multidex in your own Application class
@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
}

}


问:
min-width doesn't work
I want to create a div that able to expand the width when user input the text

I tried to set
  width:100%;
  max-width:600px;
  min-width:300px;

But some how this div just stay at 600px, is that any way to keep the width stay at 300px and able to expand to 600px base on the length of the content?

Really appreciate if you can help. Thanks

答:
I just update the "min-width" page on MDN with this information:

In some browsers, on iOS, a <button> element in its native (default) configuration will not respond to min-width.    This problem is due to native buttons.  A  inside a native button will exhibit the same problem, despite having display:inline-block set.  When changes are made to other style parameters and the browser is forced to abandon the native button, the min-width setting takes affect.

Title: min-width doesn't work

Body:
I just update the "min-width" page on MDN with this information:

In some browsers, on iOS, a <button> element in its native (default) configuration will not respond to min-width.    This problem is due to native buttons.  A <span> inside a native button will exhibit the same problem, despite having display:inline-block set.  When changes are made to other style parameters and the browser is forced to abandon the native button, the min-width setting takes affect.


问:
Adding matching labels to a dataframe after filter()
how can I match and add the associated strings in a column after using filter()?

```<code>x<- c("1","2","3","4")
y<- c("yes","no","maybe","NA")
df3<-cbind.data.frame(x,y)
unx<- unique(df3$x)
x<- c(1:10)
y<- LETTERS[1:10]
df4<-cbind.data.frame(x,y )
all<- df4 %>% filter(x %in% unx)
</code>```

To "all" I would like to add a column with the matching responses in y.

I am out of thoughts, what is the most efficient way of doing it? I would like to apply it to a large dataset. Any help will be much appreciated.

Thank you

答:
```<code>all$response <- df3$y[match(all$x, df3$x)]
</code>```

Body:
how can I match and add the associated strings in a column after using filter()?

x<- c("1","2","3","4")
y<- c("yes","no","maybe","NA")
df3<-cbind.data.frame(x,y)
unx<- unique(df3$x)
x<- c(1:10)
y<- LETTERS[1:10]
df4<-cbind.data.frame(x,y )
all<- df4 %>% filter(x %in% unx)

To "all" I would like to add a column with the matching responses in y.

I am out of thoughts, what is the most efficient way of doing it? I would like to apply it to a large dataset. Any help will be much appreciated.

Thank you


问:
How to scrape a Table with Selenium and Python 3.6 on windows 10
I am trying my hard to scrape data from a website and write data to CSV file.
then after writing to file change page to continue the process till last page.
i am getting data from first row only. I am doing something wrong .
Kindly correct me.

```<code>import re
import os
import csv
import sys
import time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains
driver =webdriver.PhantomJS()
driver.get('http://www.census2011.co.in/district.php')
driver.maximize_window()

select = Select(driver.find_element_by_xpath(".//div[@id='DataTables_Table_0_length']/label/div/select") )
select.select_by_visible_text("100")

for i in range(1,101,1) :
    sNo = driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[1]")
    district = driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[2]/a")
    districtName = driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[2]").text
    state= driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[3]").text
    population= driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[4]").text
    growth= driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[5]").text
    sexRatio= driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[6]").text
    districtLink = district.get_attribute("href")
    print(districtName,state,population,growth,sexRatio,districtLink)

with open(r"D:\python36_files\censusDistrictData.csv",'a',newline = "\n", encoding='utf-8') as csvfile:
    fieldnames = ["DistrictName", "State", "Population",  "Growth","SexRatio","DistrictLink"]
    writer = csv.DictWriter(csvfile, fieldnames = ["DistrictName", "State", "Population",  "Growth","SexRatio", "DistrictLink"],restval='none',delimiter = ';')
    writer.writerow({'DistrictName': districtName, 'State': state, 'Population':population,  'Growth':growth, 'SexRatio':sexRatio, 'DistrictLink': districtLink})

print ("OK")
driver.quit()
</code>```

and another question:
I have tried by scraping CSS Selector but not able to put a separator after col.

```<code>import re
import os
import csv
import sys
import time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains

driver =webdriver.PhantomJS()
driver.get('http://www.census2011.co.in/district.php')
driver.maximize_window()

select = Select(driver.find_element_by_xpath(".//div[@id='DataTables_Table_0_length']/label/div/select") )
select.select_by_visible_text("100")
districtTable = driver.find_elements_by_css_selector("#DataTables_Table_0")
for row in districtTable:
    print(row.text)
with open(r"D:\python36_files\censusDistrictData1.csv",'a',newline = "\n", encoding='utf-8') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames = ["Row"],restval='none',delimiter = ';')
    writer.writerow({"Row":row.text}) #pl.let me know how to insert ; after a data to a csvfile

print ("OK")
driver.quit()
</code>```

答:
It looks like you've just left out the indent under the for loop

```<code>for i in range(1,101):
    trXpath = "//table[@id='DataTables_Table_0']/tbody/tr[" + str(i) + "]"
    sNo = driver.find_element_by_xpath(trXpath + "/td[1]")
    districtLink = driver.find_element_by_xpath(trXpath + "/td[2]/a").get_attribute("href")
    districtName = driver.find_element_by_xpath(trXpath + "/td[2]").text
    state= driver.find_element_by_xpath(trXpath + "/td[3]").text
    population= driver.find_element_by_xpath(trXpath + "/td[4]").text
    growth= driver.find_element_by_xpath(trXpath + "/td[5]").text
    sexRatio= driver.find_element_by_xpath(trXpath + "/td[6]").text
    print(districtName, state, population, growth, sexRatio, districtLink)
</code>```

I've simplified the code a little to make it easier to read and maintain.

Body:
I am trying my hard to scrape data from a website and write data to CSV file.
then after writing to file change page to continue the process till last page.
i am getting data from first row only. I am doing something wrong .
Kindly correct me.

import re
import os
import csv
import sys
import time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains
driver =webdriver.PhantomJS()
driver.get('http://www.census2011.co.in/district.php')
driver.maximize_window()

select = Select(driver.find_element_by_xpath(".//div[@id='DataTables_Table_0_length']/label/div/select") )
select.select_by_visible_text("100")

for i in range(1,101,1) :
    sNo = driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[1]")
    district = driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[2]/a")
    districtName = driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[2]").text
    state= driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[3]").text
    population= driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[4]").text
    growth= driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[5]").text
    sexRatio= driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[6]").text
    districtLink = district.get_attribute("href")
    print(districtName,state,population,growth,sexRatio,districtLink)

with open(r"D:\python36_files\censusDistrictData.csv",'a',newline = "\n", encoding='utf-8') as csvfile:
    fieldnames = ["DistrictName", "State", "Population",  "Growth","SexRatio","DistrictLink"]
    writer = csv.DictWriter(csvfile, fieldnames = ["DistrictName", "State", "Population",  "Growth","SexRatio", "DistrictLink"],restval='none',delimiter = ';')
    writer.writerow({'DistrictName': districtName, 'State': state, 'Population':population,  'Growth':growth, 'SexRatio':sexRatio, 'DistrictLink': districtLink})

print ("OK")
driver.quit()

and another question:
I have tried by scraping CSS Selector but not able to put a separator after col.

import re
import os
import csv
import sys
import time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains

driver =webdriver.PhantomJS()
driver.get('http://www.census2011.co.in/district.php')
driver.maximize_window()

select = Select(driver.find_element_by_xpath(".//div[@id='DataTables_Table_0_length']/label/div/select") )
select.select_by_visible_text("100")
districtTable = driver.find_elements_by_css_selector("#DataTables_Table_0")
for row in districtTable:
    print(row.text)
with open(r"D:\python36_files\censusDistrictData1.csv",'a',newline = "\n", encoding='utf-8') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames = ["Row"],restval='none',delimiter = ';')
    writer.writerow({"Row":row.text}) #pl.let me know how to insert ; after a data to a csvfile

print ("OK")
driver.quit()

Body:
It looks like you've just left out the indent under the for loop

for i in range(1,101):
    trXpath = "//table[@id='DataTables_Table_0']/tbody/tr[" + str(i) + "]"
    sNo = driver.find_element_by_xpath(trXpath + "/td[1]")
    districtLink = driver.find_element_by_xpath(trXpath + "/td[2]/a").get_attribute("href")
    districtName = driver.find_element_by_xpath(trXpath + "/td[2]").text
    state= driver.find_element_by_xpath(trXpath + "/td[3]").text
    population= driver.find_element_by_xpath(trXpath + "/td[4]").text
    growth= driver.find_element_by_xpath(trXpath + "/td[5]").text
    sexRatio= driver.find_element_by_xpath(trXpath + "/td[6]").text
    print(districtName, state, population, growth, sexRatio, districtLink)

I've simplified the code a little to make it easier to read and maintain.


问:
X11 Forwarding under Windows?
Which X11 forwarding under Windows solution do you recommmend ?
I'd like to get the X11 display (lxde) from my dedicated hosting Ubuntu Server
on my Windows home computer so I can remote administrate (I'm a linux newbie).</p>

答: You don't need the whole desktop. Use PuTTY's X forwarding and run the appropriate command via SSH.</p>

Title: X11 Forwarding under Windows?


问:
Android Studio - Why all controls are all in upper left
Why all my controls(buttons, textfields) are all in upper left of my emulator when I test run it?  </p>

答: It Looks like you may be using a constraintLayout.  Make sure that in your layout you have a vertical and horizontal constraint set on each control.</p>


问:
How to use Enum in Camel Route?
I have the following route:

```<code>.choise()
   .when()
      .simple("${body.messageType} == 105")
          .to(...)
   .when()
      .simple("${body.messageType} == 106")
          .to(...)
</code>```

I want to use this enum to compare.

```<code>  package myPackage;

  public enum Code {
     CODE_A("105"),
     CODE_B("106")

     private String value;

    Code(String value) {
        this.value = value;
    }

    public String value() {
        return value;
    }
}
</code>```

I tried to do something like this, but it doesn't works..

```<code>.simple("${body.messageType} == ${type:myPackage.Code.CODE_A.value()}")
</code>```

Any idea to solve this problem?

答:
I solved it by doing the following:

```<code>.setHeader("codeA",constant(myPackage.Code.CODE_A.value()))
.setHeader("codeB",constant(myPackage.Code.CODE_B.value()))
.choise()
   .when()
      .simple("${body.messageType} == ${header.codeA}")
          .to(...)
   .when()
      .simple("${body.messageType} == ${header.codeB}")
          .to(...)
</code>```

Thanks!

Title: How to use Enum in Camel Route?

Body:
I have the following route:

.choise()
   .when()
      .simple("${body.messageType} == 105")
          .to(...)
   .when()
      .simple("${body.messageType} == 106")
          .to(...)

I want to use this enum to compare.

  package myPackage;

  public enum Code {
     CODE_A("105"),
     CODE_B("106")

     private String value;

    Code(String value) {
        this.value = value;
    }

    public String value() {
        return value;
    }
}

I tried to do something like this, but it doesn't works..

.simple("${body.messageType} == ${type:myPackage.Code.CODE_A.value()}")

Any idea to solve this problem?

Body:
I solved it by doing the following:

.setHeader("codeA",constant(myPackage.Code.CODE_A.value()))
.setHeader("codeB",constant(myPackage.Code.CODE_B.value()))
.choise()
   .when()
      .simple("${body.messageType} == ${header.codeA}")
          .to(...)
   .when()
      .simple("${body.messageType} == ${header.codeB}")
          .to(...)

Thanks!


问:
How to load style from resource
I am facing a problem when I try to load a resource style from file to a UIElement.
My Resource file contains a copy of ToggleSwitch's default style, I changed just some colors.
I tried the following Resource references:

```<code><Page.Resources>
    <ResourceDictionary x:Key="GreenToggleResourceDictionary">
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="GreenToggleSwitch.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Page.Resources>
</code>```

And my ToggleSwitch looks like this but it won't use the style in the referenced resource "GreenToggleSwitch.xaml":

```<code><ToggleSwitch x:Name="ToggleSwitch"
      Style="{StaticResource GreenToggleSwitchStyle}"
      HorizontalAlignment="Right"
      VerticalAlignment="Center"
      Toggled="ToggleSwitch_Toggled"
</ToggleSwitch>
</code>```

This is the GreenToggleSwitch.xaml, it's pretty much the ToggleSwitch default template:

```<code><ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:CUE">

<x:Double x:Key="ToggleSwitchOnStrokeThickness">0</x:Double>
<Style TargetType="ToggleSwitch" x:Key="GreenToggleSwitchStyle">
    .
    .
    .
</Style>
</ResourceDictionary>
</code>```

This code won't work, because of the Style 'GreenToggleSwitch' that I want to use.

How has the code to be like to work?

Basically I want to change the blue coloring around the toggle thumb(/knob) to green. If I put the code from my Resource file into my MainPage.xaml, it will work.

Appreciate your help,
Viktor

答:
Right, a resource dictionary isn't a style. What is the x:Key property of the style you want? Use that. If it's x:Key="Planxty", use Style="{StaticResource Planxty}". If it's x:Key="ImALittleTeapot", use Style="{StaticResource ImALittleTeapot}".

If it doesn't have a key, it's the implicit style and it should apply without any further effort on your part.

Secondly, you should merge the dictionary you're loading into the dictionary in your window/page/usercontrol/whatever.

Like so:

```<code><Page.Resources>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="GreenToggleSwitch.xaml"/>
    </ResourceDictionary.MergedDictionaries>
</Page.Resources>
</code>```

Update

GreenToggleSwitchResource isn't defined anywhere. The XAML parser will not try to guess your intent when you throw weird random strings at it. It will say "Dammit, Jim, I'm a parser, not a parapsychologist!"

Use the identifier that you defined. This is programming. We call things by the identifiers we give them. You called it GreenToggleSwitchStyle. So that's how you refer to it.

```<code><ToggleSwitch x:Name="ToggleSwitch"
    Style="{StaticResource GreenToggleSwitchStyle}"
    HorizontalAlignment="Right"
    VerticalAlignment="Center"
    Toggled="ToggleSwitch_Toggled"
</ToggleSwitch>
</code>```

I don't know what you're getting at with all the theme stuff and you didn't say, so I didn't address that.

Title: How to load style from resource

Body:
I am facing a problem when I try to load a resource style from file to a UIElement.
My Resource file contains a copy of ToggleSwitch's default style, I changed just some colors.
I tried the following Resource references:

<Page.Resources>
    <ResourceDictionary x:Key="GreenToggleResourceDictionary">
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="GreenToggleSwitch.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Page.Resources>

And my ToggleSwitch looks like this but it won't use the style in the referenced resource "GreenToggleSwitch.xaml":

<ToggleSwitch x:Name="ToggleSwitch"
      Style="{StaticResource GreenToggleSwitchStyle}"
      HorizontalAlignment="Right"
      VerticalAlignment="Center"
      Toggled="ToggleSwitch_Toggled"
</ToggleSwitch>

This is the GreenToggleSwitch.xaml, it's pretty much the ToggleSwitch default template:

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:CUE">

<x:Double x:Key="ToggleSwitchOnStrokeThickness">0</x:Double>

</ResourceDictionary>

This code won't work, because of the Style 'GreenToggleSwitch' that I want to use.

How has the code to be like to work?

Basically I want to change the blue coloring around the toggle thumb(/knob) to green. If I put the code from my Resource file into my MainPage.xaml, it will work.

Appreciate your help,
Viktor

Body:
Right, a resource dictionary isn't a style. What is the x:Key property of the style you want? Use that. If it's x:Key="Planxty", use Style="{StaticResource Planxty}". If it's x:Key="ImALittleTeapot", use Style="{StaticResource ImALittleTeapot}".

If it doesn't have a key, it's the implicit style and it should apply without any further effort on your part.

Secondly, you should merge the dictionary you're loading into the dictionary in your window/page/usercontrol/whatever.

Like so:

<Page.Resources>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="GreenToggleSwitch.xaml"/>
    </ResourceDictionary.MergedDictionaries>
</Page.Resources>

Update

GreenToggleSwitchResource isn't defined anywhere. The XAML parser will not try to guess your intent when you throw weird random strings at it. It will say "Dammit, Jim, I'm a parser, not a parapsychologist!"

Use the identifier that you defined. This is programming. We call things by the identifiers we give them. You called it GreenToggleSwitchStyle. So that's how you refer to it.

<ToggleSwitch x:Name="ToggleSwitch"
    Style="{StaticResource GreenToggleSwitchStyle}"
    HorizontalAlignment="Right"
    VerticalAlignment="Center"
    Toggled="ToggleSwitch_Toggled"
</ToggleSwitch>

I don't know what you're getting at with all the theme stuff and you didn't say, so I didn't address that.


问:
Google Sheet `MailApp.sendEmail`: how to create multi-line message body?
I am looking for a simple answer. I have created a script to send an email through Google Sheet Script Editor:

```<code>function mailtest() { MailApp.sendEmail("name.surname@etteachers.com",
                                        "Availability Change",
                                        "Hi Please note that...."); }
</code>```

The body of the email however keeps all the text in one row starting at the top of the email body. How do I get the part "Please note that" two rows below "Hi" in the email?

答:
Add two new lines to your message like this:</p>

```<code>function mailtest() {
    MailApp.sendEmail(""name.surname@etteachers.com", "Availability Change", "Hi\n\nPlease note that....");
  }
</code>```

Body:
I am looking for a simple answer. I have created a script to send an email through Google Sheet Script Editor:

function mailtest() { MailApp.sendEmail("name.surname@etteachers.com",
                                        "Availability Change",
                                        "Hi Please note that...."); }

The body of the email however keeps all the text in one row starting at the top of the email body. How do I get the part "Please note that" two rows below "Hi" in the email?

Body:
Add two new lines to your message like this:

function mailtest() {
    MailApp.sendEmail(""name.surname@etteachers.com", "Availability Change", "Hi\n\nPlease note that....");
  }


问:
How to change font of textbox drop-down menu in HTML using Alpha Anywhere
I am writing a mobile app for Android and iOS using the Alpha Anywhere framework. I have a dropdown textbox which currently displays two options "King Kong" and "Peter Jackson". How do I change the font size of these names in Alpha Anywhere?

If you know of a solution using JavaScript or Xbasic in the software suite that would also useful, and appreciated.

答: Are you using a ControlBar control? If so, that is where you would style it. On the other hand, if it is simply a drop-down control in a header, you could click on the object in the UX editor, and edit it's style in the Properties column on the right. </p>