问:
Should I make different layout (xml files) for different android mobiles
Should I create different layout folders to store my xml layout files. To support my application over different screen sizes?

I developed an application and when adding drawables it automatically creates different sizes like xdpi ldpi and more but layouts xml file are not auto created to support different screen sizes. should I do it? and also i will edit manifest file to support different sizes by using support-screen tag. and is this all?? And will it also support my landscape or portrait mode.  Please confirm me. I am new to stack and android development.

Edit:
I believe different layout files in different folders.. will just be a copy of each other with only folder name change ad shown in code

```<code>res/layout/my_layout.xml             // layout for normal screen size ("default")
res/layout-small/my_layout.xml       // layout for small screen size
res/layout-large/my_layout.xml       // layout for large screen size
res/layout-xlarge/my_layout.xml      // layout for extra large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation
</code>```

This is my layout xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/app_bar_main"
    tools:context="com.example.root.meeransunday.MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:text="Send Mobile"
        android:drawableLeft="@mipmap/sms"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="-1dp"
        android:layout_marginLeft="-3dp"
        android:layout_marginBottom="-4dp"
        android:onClick="message"/>
    <Button
        android:id="@+id/button2"
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:text="QR Code"
        android:drawableLeft="@mipmap/qr"
        android:layout_marginLeft="190dp"
        android:layout_marginRight="-20dp"
        android:layout_marginBottom="-4dp"
        android:layout_alignParentBottom="true"
        android:onClick="scan"
        />
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:layout_centerHorizontal="true"
    android:text="        My Account Balance"
    android:textColor="#0D47A1"
    />
    <TextView
        android:text="PKR 1527.87"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_centerHorizontal="true"
          android:drawableLeft="@mipmap/money"
        android:textSize="35sp"
        android:id="@+id/textView2"

        />
</RelativeLayout>
</code>```

Manifest file:

```<code><supports-screens android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:xlargeScreens="true"
            android:anyDensity="true"
            android:resizeable="true"/>
</code>```

but it does not work on 4 inch screen.

答:
No need to design all the Layouts,If you are making app for Phone as well as Tablets then you can design 2 Layouts. Otherwise design only these
1. Portrait
2. Landscape </p>

Body:
Should I create different layout folders to store my xml layout files. To support my application over different screen sizes?

I developed an application and when adding drawables it automatically creates different sizes like xdpi ldpi and more but layouts xml file are not auto created to support different screen sizes. should I do it? and also i will edit manifest file to support different sizes by using support-screen tag. and is this all?? And will it also support my landscape or portrait mode.  Please confirm me. I am new to stack and android development.

Edit:
I believe different layout files in different folders.. will just be a copy of each other with only folder name change ad shown in code

res/layout/my_layout.xml             // layout for normal screen size ("default")
res/layout-small/my_layout.xml       // layout for small screen size
res/layout-large/my_layout.xml       // layout for large screen size
res/layout-xlarge/my_layout.xml      // layout for extra large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation

This is my layout xml file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/app_bar_main"
    tools:context="com.example.root.meeransunday.MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:text="Send Mobile"
        android:drawableLeft="@mipmap/sms"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="-1dp"
        android:layout_marginLeft="-3dp"
        android:layout_marginBottom="-4dp"
        android:onClick="message"/>
    <Button
        android:id="@+id/button2"
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:text="QR Code"
        android:drawableLeft="@mipmap/qr"
        android:layout_marginLeft="190dp"
        android:layout_marginRight="-20dp"
        android:layout_marginBottom="-4dp"
        android:layout_alignParentBottom="true"
        android:onClick="scan"
        />
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:layout_centerHorizontal="true"
    android:text="        My Account Balance"
    android:textColor="#0D47A1"
    />
    <TextView
        android:text="PKR 1527.87"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_centerHorizontal="true"
          android:drawableLeft="@mipmap/money"
        android:textSize="35sp"
        android:id="@+id/textView2"

        />
</RelativeLayout>

Manifest file:

<supports-screens android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:xlargeScreens="true"
            android:anyDensity="true"
            android:resizeable="true"/>

but it does not work on 4 inch screen.


来源: stackexchange

问:
Replace character depend on the data
```<code>$defaultdata = "abcdef00000000000000000000000000";

$data1 = "271";

$output = "abcdef00000000000000000000000271";
</code>```

How can I replace the string based on the data. For example, if the default data is abcdef00000000000000000000000000 , so it will replace when the data1 got value. So the output will be abcdef00000000000000000000000271. How can I do this?

答:
```<code> $output = substr($defaultdata, 0, strlen($defaultdata) - strlen($data1));
$output .= $data1
</code>```

ContentLicense: CC BY-SA 3.0

Title: Replace character depend on the data

Body:
$defaultdata = "abcdef00000000000000000000000000";

$data1 = "271";

$output = "abcdef00000000000000000000000271";

How can I replace the string based on the data. For example, if the default data is abcdef00000000000000000000000000 , so it will replace when the data1 got value. So the output will be abcdef00000000000000000000000271. How can I do this?


问:
How to get SIM ip address for ipad
I need to know the source IP for my iPad using my SIM network. Is there any way to get source IP address for SIM network</p>

答: Go to a website like e.g. http://www.whatsmyip.org and there you can see your public IP address.</p>

Title: How to get SIM ip address for ipad


问:
Android Manifest configChanges error in Android Studio 2.3
I'm using android studio 2.3 latest stable version. I'm getting this 5 errors when I add activities with configChanges. The interesting thing that I could run application. So I think this is some kind of bug of the new version, but I'm not sure.

I've also tried to change order of these 3 configChanges keyboardHidden|orientation|screenSize but it still shows 5 errors like this screenSize" />

When I delete one of them from configChanges, I don't see any error.
So keyboardHidden|orientation does not cause any error.

Does anyone know why I'm getting this kind of error? Thank you.

Manifest file that cause error.

Updated

build.gradle file:

```<code>apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.test.test"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 200
        versionName "2.0"
        multiDexEnabled true
        vectorDrawables.useSupportLibrary = true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        manifestPlaceholders = [manifestApplicationId          : "${applicationId}",
                                onesignal_app_id               : "713123123123131313",
                                onesignal_google_project_number: "123123123"]
    }
    signingConfigs {
        config {
            keyAlias 'android'
            keyPassword 'android'
            storeFile file('/Users/test/.android/debug.keystore')
            storePassword 'android'
        }
        config_staging {
            keyAlias 'asdadsStaging'
            keyPassword '13123131'
            storeFile file('../asdasdasd.jks')
            storePassword '13123123'
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }
        debug {
            minifyEnabled false
            debuggable true

        }
        staging {
            minifyEnabled false
            debuggable true
            applicationIdSuffix ".staging"

            // one signal staging
            manifestPlaceholders = [manifestApplicationId          : "com.test.test.staging",
                                    onesignal_app_id               : "04123123123123123",
                                    onesignal_google_project_number: "1232131231"]

            signingConfig signingConfigs.config_staging
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12'

    compile project(':volley')
    compile project(path: ':customtabs')
    compile('com.crashlytics.sdk.android:crashlytics:2.6.6@aar') { transitive = true; }
    compile 'com.onesignal:OneSignal:3.4.0@aar'
    compile 'com.miguelcatalan:materialsearchview:1.4.0'
    compile 'com.ToxicBakery.viewpager.transforms:view-pager-transforms:1.2.32@aar'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:support-v13:25.2.0'
    compile 'com.android.support:gridlayout-v7:25.2.0'
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support:recyclerview-v7:25.2.0'
    compile 'com.android.support:cardview-v7:25.2.0'
    compile 'com.android.support:design:25.2.0'
    compile 'com.android.support:preference-v7:25.2.0'
    compile 'com.android.support:customtabs:25.2.0'
    compile 'com.android.support:support-v4:25.2.0'
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.squareup.okhttp:okhttp:2.7.5'
    compile 'com.squareup.okhttp:okhttp-urlconnection:2.7.5'
    compile 'com.facebook.android:facebook-android-sdk:4.18.0'
    compile 'com.facebook.android:audience-network-sdk:4.18.0'
    compile 'com.google.android.gms:play-services-gcm:10.2.0'
    compile 'com.google.android.gms:play-services-analytics:10.2.0'
    compile 'com.google.android.gms:play-services-ads:10.2.0'
    compile 'com.google.android.gms:play-services-auth:10.2.0'
    compile 'com.google.firebase:firebase-core:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.google.firebase:firebase-database:10.2.0'
    compile 'com.google.firebase:firebase-ads:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.google.firebase:firebase-config:10.2.0'
    compile 'com.appnext.sdk:native-ads-mediation-mopub:1.7.6'
//    compile 'com.flurry.android:ads:6.5.0'
//    compile 'com.inmobi.monetization:inmobi-ads:5.3.1'
//    compile 'net.pubnative:library:2.2.0'
//    compile 'com.github.mobfox:MobFox-Android-SDK-Core:2.1.3'
//    compile 'com.flurry.android:analytics:6.5.0'
    compile('com.mopub:mopub-sdk:4.12.0@aar') { transitive = true; }
    compile('io.fabric.sdk.android:fabric:1.3.11@aar') { transitive = true; }
    compile("com.twitter.sdk.android:twitter:2.3.2@aar") { transitive = true }
    compile 'com.android.support.constraint:constraint-layout:1.0.0'
}

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

buildscript {
    repositories {
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
    dependencies {
        classpath 'io.fabric.tools:gradle:1.21.6'
    }
}

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

答:
Same problem here. I'm having this errors when I added MoPub activities.
Even those errors are reported, the app is compiled correctly and works as expected.</p>

Body:
I'm using android studio 2.3 latest stable version. I'm getting this 5 errors when I add activities with configChanges. The interesting thing that I could run application. So I think this is some kind of bug of the new version, but I'm not sure.

I've also tried to change order of these 3 configChanges keyboardHidden|orientation|screenSize but it still shows 5 errors like this screenSize" />

When I delete one of them from configChanges, I don't see any error.
So keyboardHidden|orientation does not cause any error.

Does anyone know why I'm getting this kind of error? Thank you.

Manifest file that cause error.

Updated

build.gradle file:

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.test.test"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 200
        versionName "2.0"
        multiDexEnabled true
        vectorDrawables.useSupportLibrary = true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        manifestPlaceholders = [manifestApplicationId          : "${applicationId}",
                                onesignal_app_id               : "713123123123131313",
                                onesignal_google_project_number: "123123123"]
    }
    signingConfigs {
        config {
            keyAlias 'android'
            keyPassword 'android'
            storeFile file('/Users/test/.android/debug.keystore')
            storePassword 'android'
        }
        config_staging {
            keyAlias 'asdadsStaging'
            keyPassword '13123131'
            storeFile file('../asdasdasd.jks')
            storePassword '13123123'
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }
        debug {
            minifyEnabled false
            debuggable true

        }
        staging {
            minifyEnabled false
            debuggable true
            applicationIdSuffix ".staging"

            // one signal staging
            manifestPlaceholders = [manifestApplicationId          : "com.test.test.staging",
                                    onesignal_app_id               : "04123123123123123",
                                    onesignal_google_project_number: "1232131231"]

            signingConfig signingConfigs.config_staging
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12'

    compile project(':volley')
    compile project(path: ':customtabs')
    compile('com.crashlytics.sdk.android:crashlytics:2.6.6@aar') { transitive = true; }
    compile 'com.onesignal:OneSignal:3.4.0@aar'
    compile 'com.miguelcatalan:materialsearchview:1.4.0'
    compile 'com.ToxicBakery.viewpager.transforms:view-pager-transforms:1.2.32@aar'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:support-v13:25.2.0'
    compile 'com.android.support:gridlayout-v7:25.2.0'
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support:recyclerview-v7:25.2.0'
    compile 'com.android.support:cardview-v7:25.2.0'
    compile 'com.android.support:design:25.2.0'
    compile 'com.android.support:preference-v7:25.2.0'
    compile 'com.android.support:customtabs:25.2.0'
    compile 'com.android.support:support-v4:25.2.0'
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.squareup.okhttp:okhttp:2.7.5'
    compile 'com.squareup.okhttp:okhttp-urlconnection:2.7.5'
    compile 'com.facebook.android:facebook-android-sdk:4.18.0'
    compile 'com.facebook.android:audience-network-sdk:4.18.0'
    compile 'com.google.android.gms:play-services-gcm:10.2.0'
    compile 'com.google.android.gms:play-services-analytics:10.2.0'
    compile 'com.google.android.gms:play-services-ads:10.2.0'
    compile 'com.google.android.gms:play-services-auth:10.2.0'
    compile 'com.google.firebase:firebase-core:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.google.firebase:firebase-database:10.2.0'
    compile 'com.google.firebase:firebase-ads:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.google.firebase:firebase-config:10.2.0'
    compile 'com.appnext.sdk:native-ads-mediation-mopub:1.7.6'
//    compile 'com.flurry.android:ads:6.5.0'
//    compile 'com.inmobi.monetization:inmobi-ads:5.3.1'
//    compile 'net.pubnative:library:2.2.0'
//    compile 'com.github.mobfox:MobFox-Android-SDK-Core:2.1.3'
//    compile 'com.flurry.android:analytics:6.5.0'
    compile('com.mopub:mopub-sdk:4.12.0@aar') { transitive = true; }
    compile('io.fabric.sdk.android:fabric:1.3.11@aar') { transitive = true; }
    compile("com.twitter.sdk.android:twitter:2.3.2@aar") { transitive = true }
    compile 'com.android.support.constraint:constraint-layout:1.0.0'
}

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

buildscript {
    repositories {
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
    dependencies {
        classpath 'io.fabric.tools:gradle:1.21.6'
    }
}

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


问:
how to update data of a struct and save it in chaincode?
The following is an excerpt of the chaincode where I have created a customer struct that saves basic info. I wish to write an update function that first fetches the details of the customer with the UID(args[0]) and then appends/updates the Country as per the second arguement of the function update and finally saves the updated data.
What am I doing wrong?  Also I would like to know the concept of Marshal and Unmarshal.</p>

```<code>type Customer struct {
  UID     string
  Name    string
  Address struct {
    StreetNo string
    Country  string
  }
}
func (t *SimpleChaincode) update(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

if len(args) != 2 {
    return nil, errors.New("Incorrect number of arguments. Expecting name of the key to query")
}
  //args[0] to get the UID of customer whose details to be updated
  //args[1] data that needs to be updated

data,err:= stub.GetState(ars[0])
if err != nil {
     return nil, err
}
json.Unmarshal(data, &uid)
//append
data.Country= append(data.Country,args[1])
fmt.Printf("Risk Fag set for UID %s",data)

raw, err := json.Marshal(data)
  if err != nil {
     return nil, err
  }

  stub.PutState(data.UID, raw)

return nil,nil

}
</code>```

答:
You need to provide a variable where the JSON package can put the decoded data.For example this will hold a map of strings to arbitrary data types:

```<code>map[string]interface{}

byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
if err := json.Unmarshal(byt, &dat); err != nil {
    panic(err)
}
fmt.Println(dat)
</code>```

the result is  :

```<code>map[num:6.13 strs:[a b]]
</code>```

Body:
The following is an excerpt of the chaincode where I have created a customer struct that saves basic info. I wish to write an update function that first fetches the details of the customer with the UID(args[0]) and then appends/updates the Country as per the second arguement of the function update and finally saves the updated data.
What am I doing wrong?  Also I would like to know the concept of Marshal and Unmarshal.

type Customer struct {
  UID     string
  Name    string
  Address struct {
    StreetNo string
    Country  string
  }
}
func (t *SimpleChaincode) update(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

if len(args) != 2 {
    return nil, errors.New("Incorrect number of arguments. Expecting name of the key to query")
}
  //args[0] to get the UID of customer whose details to be updated
  //args[1] data that needs to be updated

data,err:= stub.GetState(ars[0])
if err != nil {
     return nil, err
}
json.Unmarshal(data, &uid)
//append
data.Country= append(data.Country,args[1])
fmt.Printf("Risk Fag set for UID %s",data)

raw, err := json.Marshal(data)
  if err != nil {
     return nil, err
  }

  stub.PutState(data.UID, raw)

return nil,nil

}

Body:
You need to provide a variable where the JSON package can put the decoded data.For example this will hold a map of strings to arbitrary data types:

map[string]interface{}

byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
if err := json.Unmarshal(byt, &dat); err != nil {
    panic(err)
}
fmt.Println(dat)

the result is  :

map[num:6.13 strs:[a b]]


问:
Convert existing value from one type to another during EntityFramework migration?
I have:

```<code>    [Required]
    public string Proportion { get; set; }
</code>```

which is a string property. I have to apply some simple logic to convert it to the integer.
So my goal is to 1) save existing proportions, 2) drop string-column and create new int column with saved and converted to int values instead. Is it possible?

答:
If I get your intention correctly, you could delete your Proportion entity from the model than migrate your database with update-database -force which will delete the column from your db. than re-create the Proportion entity to int and migrate the db again.

Now you will have the Model and db to be corresponding to int type for the Proportion entity. Of course, you will have to use another variable to store the string value and than to parse it to int and store it to Proportion.

In your question you talk about values in plural. In my answer I referred to int property which get only one integer. If you have some thing like width*height i would suggest parsing into two separate properties.

Body:
I have:

    [Required]
    public string Proportion { get; set; }

which is a string property. I have to apply some simple logic to convert it to the integer.
So my goal is to 1) save existing proportions, 2) drop string-column and create new int column with saved and converted to int values instead. Is it possible?

ContentLicense: CC BY-SA 4.0


问:
How to judge long variable is null, or can if() contain an exception judgment in Java?
In my case, results[i] might not exist in HBase table, so using getTimestamp() to get results[i]'s timestamp might cause an exception. Timestamp in HBase is a long variable, so following two ways I tried do not works.

```<code>if((results[i].listCells().get(0).getTimestamp()) != null){
    rowkeytime = results[i].listCells().get(0).getTimestamp();
}

if(((Long)(results[i].listCells().get(0).getTimestamp())) != null){
    rowkeytime = results[i].listCells().get(0).getTimestamp();
}
</code>```

I want to know whether there is an usage like below in Java?

```<code>if ((results[i].listCells().get(0).getTimestamp()) throws an exception){
    rowkeytime = results[i].listCells().get(0).getTimestamp();
}
</code>```

答:
...in my case, results[i] might not exist...

is you mean results[i] can be null then it would be good to check whether the reference is pointing to null or not,

this will be done as:

```<code>results[i] == null
</code>```

that returns true is your results[i] is null,

Body:
In my case, results[i] might not exist in HBase table, so using getTimestamp() to get results[i]'s timestamp might cause an exception. Timestamp in HBase is a long variable, so following two ways I tried do not works.

if((results[i].listCells().get(0).getTimestamp()) != null){
    rowkeytime = results[i].listCells().get(0).getTimestamp();
}

if(((Long)(results[i].listCells().get(0).getTimestamp())) != null){
    rowkeytime = results[i].listCells().get(0).getTimestamp();
}

I want to know whether there is an usage like below in Java?

if ((results[i].listCells().get(0).getTimestamp()) throws an exception){
    rowkeytime = results[i].listCells().get(0).getTimestamp();
}

Body:
...in my case, results[i] might not exist...

is you mean results[i] can be null then it would be good to check whether the reference is pointing to null or not,

this will be done as:

results[i] == null

that returns true is your results[i] is null,


答:
I'd use substr:

```<code>$output = substr($defaultdata,0,strlen($defaultdata)-strlen($data1)) . $data1;
</code>```

Applying it to your code

```<code><?php
$defaultdata = "abcdef00000000000000000000000000";
$data1 = "271";
$output = substr($defaultdata,0,strlen($defaultdata)-strlen($data1)) . $data1;
echo $output;
?>
</code>```

Title: Replace character depend on the data

Body:
I'd use substr:

$output = substr($defaultdata,0,strlen($defaultdata)-strlen($data1)) . $data1;

Applying it to your code

<?php
$defaultdata = "abcdef00000000000000000000000000";
$data1 = "271";
$output = substr($defaultdata,0,strlen($defaultdata)-strlen($data1)) . $data1;
echo $output;
?>


问:
PL/SQL procedure problems
I am trying to write a PL/SQL procedure to count the number of employees in a department by department name. Each department has a department number associated with it that each employee is assigned upon entry. This is my attempt so far. After a lot of practice, I'm still very shaky with PL/SQL. Do I have a blatant logic or syntax error in here anywhere? I'm not asking anyone to do the debugging for me here, but oracle sql's error report doesn't offer much help. Thank you to anyone who answers.</p>

```<code>create or replace function NumOfEmployee_ByDept
    ( dept_name in department.Dname%type )
    return number
as
    empCount number;

begin
    select count(*) into empCount
    from   department, employee
    where  dno = dnumber
    and    dname = dept_name;

    return(empCount);
end;
</code>```

答:
The syntax seems to be good. Perhaps there is a problem with the grants on the tables. Verify that the schema, in which you're trying to compile this function, got the correct rights for the tables.
I would recommend you to insert an exception block and to log the delivered error.</p>

Title: PL/SQL procedure problems

Body:
I am trying to write a PL/SQL procedure to count the number of employees in a department by department name. Each department has a department number associated with it that each employee is assigned upon entry. This is my attempt so far. After a lot of practice, I'm still very shaky with PL/SQL. Do I have a blatant logic or syntax error in here anywhere? I'm not asking anyone to do the debugging for me here, but oracle sql's error report doesn't offer much help. Thank you to anyone who answers.

create or replace function NumOfEmployee_ByDept
    ( dept_name in department.Dname%type )
    return number
as
    empCount number;

begin
    select count(*) into empCount
    from   department, employee
    where  dno = dnumber
    and    dname = dept_name;

    return(empCount);
end;


问:
Windows Vista Desaturated: Grayscale UI
Occasionally working in Windows Vista the O.S. will desaturate the screen, rendering all colors as grayscale. Is there a way to do this programatically? Failing that, is there a way to do it by tweaking Vista settings?

Thanks.

答: Umm, if I had to guess, I'd say that Vista (and XP, by the way) are simply applying some sort of overlay to the whole screen. I'm guessing it's done by rendering an opaque rectangle with a blend mode of some sort. This is only my guess, though.

ContentLicense: CC BY-SA 2.5

Title: Windows Vista Desaturated: Grayscale UI

OwnerDisplayName: Dmitri Nesteruk


问:
Qt: Passing an argument in the selectionchanged() signal
I want to pass a parameter to the selection changed SLOT like the following:

```<code>connect(selectionModel, SIGNAL(selectionChanged (const QItemSelection &, const QItemSelection &, MyParameter)),
    this, SLOT(OnSelection(const QItemSelection &, const QItemSelection &, MyParameter)));
</code>```

Or at least like:

```<code>connect(selectionModel, SIGNAL(selectionChanged (MyParameter)),
    this, SLOT(OnSelection(MyParameter)));
</code>```

I want to use the MyParameter in the SLOT. Is there a way to do it? Is it possible to build a custom selectionChanged() Signal?

答:
You can inherit from your selectionModel class and implement its own signal with the required parameters. Then create a slot that connects to the default signal, and in which to collect the parameters and emit your signal.

Like this:

```<code>MySelectionModel: public SelectionModel{
public:
    MySelectionModel(){
        connect(this,
            SIGNAL(selectionChanged(const QItemSelection & , const QItemSelection & )),
            this,
            SLOT(myPrivateSlot(const QItemSelection & , const QItemSelection & )));
    }
private slots:
    void myPrivateSlot(const QItemSelection & selected, const QItemSelection & deselected){
        //collect or calculate params you want
        emit mySignal(selected, deselected, yourParams);
    }
signals:
    void mySignal(const QItemSelection & selected, const QItemSelection & deselected, MyParams params);
}
</code>```

It is not working code. It is just explain how you can done it.

Body:
I want to pass a parameter to the selection changed SLOT like the following:

connect(selectionModel, SIGNAL(selectionChanged (const QItemSelection &, const QItemSelection &, MyParameter)),
    this, SLOT(OnSelection(const QItemSelection &, const QItemSelection &, MyParameter)));

Or at least like:

connect(selectionModel, SIGNAL(selectionChanged (MyParameter)),
    this, SLOT(OnSelection(MyParameter)));

I want to use the MyParameter in the SLOT. Is there a way to do it? Is it possible to build a custom selectionChanged() Signal?

Body:
You can inherit from your selectionModel class and implement its own signal with the required parameters. Then create a slot that connects to the default signal, and in which to collect the parameters and emit your signal.

Like this:

MySelectionModel: public SelectionModel{
public:
    MySelectionModel(){
        connect(this,
            SIGNAL(selectionChanged(const QItemSelection & , const QItemSelection & )),
            this,
            SLOT(myPrivateSlot(const QItemSelection & , const QItemSelection & )));
    }
private slots:
    void myPrivateSlot(const QItemSelection & selected, const QItemSelection & deselected){
        //collect or calculate params you want
        emit mySignal(selected, deselected, yourParams);
    }
signals:
    void mySignal(const QItemSelection & selected, const QItemSelection & deselected, MyParams params);
}

It is not working code. It is just explain how you can done it.


问:
How to Create Custom Notification with Standard Height in Android 7?
I created a custom notification with standard height (not the expanded version described with bigContentView) which works fine with Android 4 up to 6.

In Android 7 the design of the notifications was changed, the third line which used to be at the bottom is now at the top, and the notifications are higher than before. But for unknown reason my custom notification is not enlarged accordingly and now looks like a foreign object between the other notifications.

I am using android:layout_height="match_parent" and also experimented with fixed height, but without success.

Is there a way in Android 7 to let my notifications look great again, or is there a bug in that OS version?

The picture the link points to shows three notifications. The first and last ones are 99 pixels high, while my custom notification is 85 pixels high.

Custom Notification

答: I was having a problem with my notification layout on Android 7. Setting the parent with fixed height such as 64dp and having its childen's height set to match parent was resulting in a weird UI with empty spaces on the top and bottom. I resolved it by setting the children's height to 64dp instead of match_parent. Hope this helps. </p>


问:
C# Actions/Classes

I have to design a program that operates like this.  I've got done the basic code for the robot movement, however the directions require that I use an "Action" class with a display method.

Add a new class called Action that will expose the following pieces of data:|

1.) ActionType
2.) Direction
3.) Distance
3.) Display()

o The Display method of the Action class should emit RobotDirection.X where X is the full name for the direction

or MoveRobot(X) where the X is the distance selected.
o Add a list of type Action to keep track of the Direction and Movement instructions entered by the user

o Add a listbox and for every item in the list of Actions, call the Display() method and add that information to the
listbox

As of right now, I have an enums class as:

```<code>public enum ActionType
{
    Movement,
    Direction
}
public enum RobotDirection
{
    North,
    South,
    East,
    West
}
</code>```

And in my Actions class:

```<code> public String Display(Action x)
    {
        String robotAction = null;

        if(x.ActionType == ActionType.Direction)
        {
            if(x.Direction == RobotDirection.North)
            {
                robotAction = "RobotDirection.North";
            }
            else if(x.Direction == RobotDirection.East)
            {
                robotAction = "RobotDirection.East";
            }
            else if(x.Direction == RobotDirection.South)
            {
                robotAction = "RobotDirection.South";
            }
            else if(x.Direction == RobotDirection.West)
            {
                robotAction = "RobotDirection.West";
            }

        }

        else if (x.ActionType == ActionType.Movement)
        {
            robotAction = "MoveRobot(" + Distance + ")";
        }

        return robotAction;

    }
}
</code>```

How would I call the Display method to populate the listbox?

Thank you!

答:
You should call this method to a string:

```<code>string specificAction = Display(/*any action*/)
</code>```

And then add the string to your ListBox:

```<code>yourListBox.Items.Add(specificAction)
</code>```

Hope it helped!

Title: C# Actions/Classes

Body:
I have to design a program that operates like this.  I've got done the basic code for the robot movement, however the directions require that I use an "Action" class with a display method.

Add a new class called Action that will expose the following pieces of data:|

1.) ActionType
2.) Direction
3.) Distance
3.) Display()

o The Display method of the Action class should emit RobotDirection.X where X is the full name for the direction

or MoveRobot(X) where the X is the distance selected.
o Add a list of type Action to keep track of the Direction and Movement instructions entered by the user

o Add a listbox and for every item in the list of Actions, call the Display() method and add that information to the
listbox

As of right now, I have an enums class as:

public enum ActionType
{
    Movement,
    Direction
}
public enum RobotDirection
{
    North,
    South,
    East,
    West
}

And in my Actions class:

 public String Display(Action x)
    {
        String robotAction = null;

        if(x.ActionType == ActionType.Direction)
        {
            if(x.Direction == RobotDirection.North)
            {
                robotAction = "RobotDirection.North";
            }
            else if(x.Direction == RobotDirection.East)
            {
                robotAction = "RobotDirection.East";
            }
            else if(x.Direction == RobotDirection.South)
            {
                robotAction = "RobotDirection.South";
            }
            else if(x.Direction == RobotDirection.West)
            {
                robotAction = "RobotDirection.West";
            }

        }

        else if (x.ActionType == ActionType.Movement)
        {
            robotAction = "MoveRobot(" + Distance + ")";
        }

        return robotAction;

    }
}

How would I call the Display method to populate the listbox?

Thank you!

Body:
You should call this method to a string:

string specificAction = Display(/*any action*/)

And then add the string to your ListBox:

yourListBox.Items.Add(specificAction)

Hope it helped!


问:
How to exclude properties from DTO in REST based on parameter
I have a class like below.

```<code>    public class MyDto {

    private int id;
    private String name;
    private String address;
    // getters and setters .....
    }
</code>```

I have a MS4J service like below with returns a JSON from this object.

```<code>import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.example.service.dto.MyDto;
import org.wso2.msf4j.Request;

    @Path("/hello/1.[\\d]/version")
    public class HelloService {

        @GET
        @Path("/{version}")
        @Produces({"application/json"})
        public Response hello(@PathParam("version") int version, @Context Request request) {
            MyDto dtoObject = new MyDto(1, "TestObjName", "TestObjAddress");
            if (version < 1) {
                //return object without address
            } else {
                //return object with address
            }
        }
    }
</code>```

At the runtime, I need to exclude properties from java class based on version. ie. if version >1 object without address else object with the address property.

Setting null for address field is not an option. I tried to do this with JacksonView and JacksonFilter yet unable to fit it to this scenario.

Any idea or sample code to fix this?

答:
You can create a subclass of MyDto with the proper annotation to ignore the property:

```<code>public class OldVersionDto extends MyDto
{
    @JsonIgnore
    protected String address;

    public OldVersionDto(int id, String name, String address) {
        super(id, name, address);
    }
}
</code>```

it can even be an inner class of the service if it serves only ad-hoc purpose (just be sure to make it static). Now you instantiate the local variable according to the argument

```<code>        MyDto dtoObject;
        if (version < 1) {
            dtoObject = new MyDto(1, "TestObjName", "TestObjAddress");
        } else {
            dtoObject = new OldVersionDto(1, "TestObjName", "TestObjAddress");
        }
</code>```

of course, the address property will have to be protected in the base class order for this to succeed.

Body:
I have a class like below.

    public class MyDto {

    private int id;
    private String name;
    private String address;
    // getters and setters .....
    }

I have a MS4J service like below with returns a JSON from this object.

import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.example.service.dto.MyDto;
import org.wso2.msf4j.Request;

    @Path("/hello/1.[\\d]/version")
    public class HelloService {

        @GET
        @Path("/{version}")
        @Produces({"application/json"})
        public Response hello(@PathParam("version") int version, @Context Request request) {
            MyDto dtoObject = new MyDto(1, "TestObjName", "TestObjAddress");
            if (version < 1) {
                //return object without address
            } else {
                //return object with address
            }
        }
    }

At the runtime, I need to exclude properties from java class based on version. ie. if version >1 object without address else object with the address property.

Setting null for address field is not an option. I tried to do this with JacksonView and JacksonFilter yet unable to fit it to this scenario.

Any idea or sample code to fix this?

Body:
You can create a subclass of MyDto with the proper annotation to ignore the property:

public class OldVersionDto extends MyDto
{
    @JsonIgnore
    protected String address;

    public OldVersionDto(int id, String name, String address) {
        super(id, name, address);
    }
}

it can even be an inner class of the service if it serves only ad-hoc purpose (just be sure to make it static). Now you instantiate the local variable according to the argument

        MyDto dtoObject;
        if (version < 1) {
            dtoObject = new MyDto(1, "TestObjName", "TestObjAddress");
        } else {
            dtoObject = new OldVersionDto(1, "TestObjName", "TestObjAddress");
        }

of course, the address property will have to be protected in the base class order for this to succeed.


问:
content narration in web page, on tab press not going to speak anything if current task(speak anything) not completed
I am using articulate.js(http://www.jqueryscript.net/demo/Lightweight-jQuery-Based-Text-To-Speech-Engine-Articulate-js/) to read content from page and speak it. It is working fine, just not works if it is speaking something and I have press tab then it stops but not reads tab selected content.
some pre-define functions

```<code><script>
function speak(obj) {
  $(obj).articulate('speak');
};

function pause() {
  $().articulate('pause');
};

function resume() {
  $().articulate('resume');
};

function stop() {
  $().articulate('stop');
};
</script>
</code>```

what I have tried

```<code><script>
  $(document).ready(function() {
    var counter = 0;
    setTimeout(function(){
      counter +=1;
      if (counter == 1){
        explode();
      }
    },1000);
    function explode(){
      //$('body').articulate('speak'); // Default for play whole content
      $('h1').articulate('speak');
    }

    $('body').keyup(function (e) {
    $().articulate('stop');
      if (e.which == 9) { // on tab press start speaking selected element
        var i=document.activeElement.id;
        $('#'+i).articulate('pause').articulate('stop').articulate('speak');
      }
      else{ // trying to speak what key has been pressed except tab, but not working
          var i=document.activeElement.id;
          $('#'+i).val().articulate('speak');
      }
    });

  });
</script>
</code>```

I am also trying to make it audible(to speak keypress) on text box, which is not working

答:
I have make some changes now it is working, but it has certain limitation like it not reads backspace, ctrl, space etc but speak a to z,1 to 0, very well. please improve it</p>

```<code><script>
  $(document).ready(function() {
    var counter = 0;
    setTimeout(function(){
      counter +=1;
      if (counter == 1){
        explode();
      }
    },1000);
    function explode(){
      //$('body').articulate('speak'); // Default for play whole content
      $('h1').articulate('speak');
    }

    $('body').keyup(function (e) {
        var speaking = $().articulate('isSpeaking');
        var paused = $().articulate('isPaused');
//  $().articulate('stop');
      if (e.which == 9) {
          if (speaking) {
              $().articulate('pause');
              $().articulate('stop');
          }

          var check =0;
          setTimeout(function(){
              check +=1;
              if (check == 1){
                  comeback();
              }
          },1000);
          function comeback() {
              var i=document.activeElement.id;
              $('#'+i).articulate('speak');

          }
      }
      else{
          var i=document.activeElement.id;
          var m=0;
          setTimeout(function () {
              m+=1;
              if(m==1){
                  magic();
              }
          },500);
          function magic() {
              var tempval=$('#'+i).val();
              var lastChar = tempval.substr(tempval.length - 1);
              var ht ='<div>'+lastChar+'</div>';
              $(ht).articulate('speak');
          }
      }
    });

  });
</script>
</code>```

Body:
I am using articulate.js(http://www.jqueryscript.net/demo/Lightweight-jQuery-Based-Text-To-Speech-Engine-Articulate-js/) to read content from page and speak it. It is working fine, just not works if it is speaking something and I have press tab then it stops but not reads tab selected content.
some pre-define functions

what I have tried

I am also trying to make it audible(to speak keypress) on text box, which is not working

Body:
I have make some changes now it is working, but it has certain limitation like it not reads backspace, ctrl, space etc but speak a to z,1 to 0, very well. please improve it

<script>
  $(document).ready(function() {
    var counter = 0;
    setTimeout(function(){
      counter +=1;
      if (counter == 1){
        explode();
      }
    },1000);
    function explode(){
      //$('body').articulate('speak'); // Default for play whole content
      $('h1').articulate('speak');
    }

    $('body').keyup(function (e) {
        var speaking = $().articulate('isSpeaking');
        var paused = $().articulate('isPaused');
//  $().articulate('stop');
      if (e.which == 9) {
          if (speaking) {
              $().articulate('pause');
              $().articulate('stop');
          }

          var check =0;
          setTimeout(function(){
              check +=1;
              if (check == 1){
                  comeback();
              }
          },1000);
          function comeback() {
              var i=document.activeElement.id;
              $('#'+i).articulate('speak');

          }
      }
      else{
          var i=document.activeElement.id;
          var m=0;
          setTimeout(function () {
              m+=1;
              if(m==1){
                  magic();
              }
          },500);
          function magic() {
              var tempval=$('#'+i).val();
              var lastChar = tempval.substr(tempval.length - 1);
              var ht ='<div>'+lastChar+'</div>';
              $(ht).articulate('speak');
          }
      }
    });

  });
</script>


问:
Unable to encrypt using SQLCipher
I'm currently working on a simple account management app for the iPhone. I'm using sqlcipher to encrypt and decrypt the database.

Currently i have an unencrypted database in the application bundle, which i want to either copy to the iPhone document directory and then get it encrypted, or get it encrypted before i copy it over to the document directory.

The problem that i'm facing is that no matter what i do, i seem to get an unencrypted database, no matter what method of encryption i try to use, be it the "ATTACH" database method or the "key()/rekey()" method.

I tried using the "ATTACH" database method in terminal but the result was an unencrypted database. I tried using the "key()/rekey()" method programmatically as seen here:

```<code> sqlite3 *db;
 NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"KeyCrypt.sqlite"];
 if (sqlite3_open([defaultDBPath UTF8String],&db)==SQLITE_OK) {
  NSLog (@"Running keying.");
  sqlite3_key(db, "1234", 4);
  if (sqlite3_exec(db, (const char*) "SELECT count(*) FROM sqlite_master;", NULL, NULL, NULL) == SQLITE_OK) {
   // password is correct, or, database has been initialized
   NSLog (@"This has occured correctly?");
  }
  else
  {
   // incorrect password!
   NSLog (@"This has occured incorrectly?");
  }
 }
</code>```

Am i doing something wrong, somewhere?
I've tried researching online for one whole day and couldn't come close to finding a solution for why my database isn't encrypted before or during runtime :(

If you require any extra information i am willing to provide it to you, please help a student out!

THANK YOU!

EDIT:

Excerpt of method used to key my db.

```<code> //Initializing the sqlite3_key function.
        int sqlite3_key(sqlite3 *db, const void *pKey, int nKey);
        sqlite3_key(db, "1234", 4);
</code>```

Apparently i didn't initialize the sqlite3_key -_-".
Also eventhough the file is encrypted the check still says something occurred incorrectly and database wasn't successfully opened.

Regarding the opening of databases, every instance i open my database i have to run the sqlite3_key right? And during that instance I can access the database as per normal right?

Thank you for all the help.

答:
Using rekey to convert an unencrypted database to an encrypted database is no longer supported by SQLCipher due to several complexities involved with changing the page size and reserved bytes required for per-page initialization vectors. Thus, the code you provided will not operate on any recent version of SQLCipher. Based on what you want to do, there are two options:

Our current guidance for adding encryption to a database is to use ATTACH. In short, you attach an encrypted database to your standard SQLite database, and then copy data between the two. Here is a post describing the approach: How to encrypt a plaintext SQLite database to use SQLCipher

Instead of distributing an unencrypted database in the application bundle, just include an encrypted copy of the the database in the that is using a known key. Then, on startup, copy the database into place, open it with the known default key, and and run rekey with the new per-user key data. This would rewrite the database to use the new key as you wanted.

Title: Unable to encrypt using SQLCipher

Body:
I'm currently working on a simple account management app for the iPhone. I'm using sqlcipher to encrypt and decrypt the database.

Currently i have an unencrypted database in the application bundle, which i want to either copy to the iPhone document directory and then get it encrypted, or get it encrypted before i copy it over to the document directory.

The problem that i'm facing is that no matter what i do, i seem to get an unencrypted database, no matter what method of encryption i try to use, be it the "ATTACH" database method or the "key()/rekey()" method.

I tried using the "ATTACH" database method in terminal but the result was an unencrypted database. I tried using the "key()/rekey()" method programmatically as seen here:

 sqlite3 *db;
 NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"KeyCrypt.sqlite"];
 if (sqlite3_open([defaultDBPath UTF8String],&db)==SQLITE_OK) {
  NSLog (@"Running keying.");
  sqlite3_key(db, "1234", 4);
  if (sqlite3_exec(db, (const char*) "SELECT count(*) FROM sqlite_master;", NULL, NULL, NULL) == SQLITE_OK) {
   // password is correct, or, database has been initialized
   NSLog (@"This has occured correctly?");
  }
  else
  {
   // incorrect password!
   NSLog (@"This has occured incorrectly?");
  }
 }

Am i doing something wrong, somewhere?
I've tried researching online for one whole day and couldn't come close to finding a solution for why my database isn't encrypted before or during runtime :(

If you require any extra information i am willing to provide it to you, please help a student out!

THANK YOU!

EDIT:

Excerpt of method used to key my db.

 //Initializing the sqlite3_key function.
        int sqlite3_key(sqlite3 *db, const void *pKey, int nKey);
        sqlite3_key(db, "1234", 4);

Apparently i didn't initialize the sqlite3_key -_-".
Also eventhough the file is encrypted the check still says something occurred incorrectly and database wasn't successfully opened.

Regarding the opening of databases, every instance i open my database i have to run the sqlite3_key right? And during that instance I can access the database as per normal right?

Thank you for all the help.


问:
How to copy and paste text in MongoDB shell
How to copy and paste text in MongoDB shell?

I tried Ctrl+C and Ctrl+V but it didn't work.

Thanks, Michael.

答:
If you are using Windows then Command:

```<code>Copy = Ctrl + Insert
Paste = Shift + Insert
</code>```

This works for Windows as well as Linux:

```<code>1. Select your text using Mouse
2. Press Mouse-Right button to Copy & Paste
3. Press Mouse-Right button to Paste copied text from Clipboard
</code>```

Body:
If you are using Windows then Command:

Copy = Ctrl + Insert
Paste = Shift + Insert

This works for Windows as well as Linux:

1. Select your text using Mouse
2. Press Mouse-Right button to Copy & Paste
3. Press Mouse-Right button to Paste copied text from Clipboard


问:
Reading GoogleService-Info.plist file gives an error
I got a merge conflict while merging a branch in app.xcodeproj/project.pbxproj file. Conflict was with references related to GoogleService-Info.plist. I followed this answer
https://stackoverflow.com/a/2007358/4863339
to resolve the conflict. Now XCode was showing two same files. Deleting one file would show that entire file has been deleted. I went back to app.xcodeproj/project.pbxproj file and deleted the redundant file reference (Costly mistake). Now ,even when I add that GoogleService-Info.plist back XCode gives me following error.

Copy Plist File error:
  /Users/user/Documents/app/app/GoogleService-Info.plist:0: error:
  reading data: The file “GoogleService-Info.plist” couldn’t be opened
  because there is no such file.

I'm using XCode 8 and info.Plist is pointing to the location where it is supposed to be.

I've tried clean + build even that isn't helping. Can someone please help me with this?

答: I resolved this issue by deleting one of the references in app.xcodeproj/project.pbxproj file , so there wouldn't be duplicate entries for the same file while merging.</p>


问:
Escape characters in Matlab
I am reading a file using fileread() which returns me the entire file. Now I need to read line by line and convert them into process the data. Can I know how I would be able to detect the newline character in Matlab? I tried '\n' and '\r\n' and it doesn't work.

Thanks in advance

答:
You can read the file line by line (see fgetl):</p>

```<code>fid = fopen ( 'file', 'r' );
% Check that it opened okay
if fid ~= -1
  while ( true )
    line = fgetl ( fid );
    % Check for end of file
    if line == -1; break; end
    %Do stuff with line;
  end
  fclose ( fid );
end
</code>```

Title: Escape characters in Matlab

Body:
You can read the file line by line (see fgetl):

fid = fopen ( 'file', 'r' );
% Check that it opened okay
if fid ~= -1
  while ( true )
    line = fgetl ( fid );
    % Check for end of file
    if line == -1; break; end
    %Do stuff with line;
  end
  fclose ( fid );
end


问:
How to extract this information php
How can I correctly extract this information in php?
For example, I need information about the customer and the id.

contents
shipping_address
currency
customer
....

Thank you

```<code>"sessiontoken|s:32:"6450a6e3ced9cdbc38c82e51376efc0f";ClicShoppingCart|a:5:{s:8:"contents";a:1:{i:21;a:1:{s:3:"qty";i:5;}}s:14:"sub_total_cost";i:0;s:10:"total_cost";i:0;s:12:"total_weight";d:0;s:16:"shipping_address";a:2:{s:7:"zone_id";s:3:"265";s:10:"country_id";s:2:"73";}}language|s:2:"fr";currency|s:3:"USD";new_products_id_in_cart|i:21;cart_country_id|s:2:"73";Shop|a:1:{s:17:"NavigationHistory";a:1:{s:8:"snapshot";N;}cart_address_id|N;sendto|i:24;customer_group_id|a:1:{s:18:"customers_group_id";s:1:"0";}customer|a:8:{s:2:"id";i:11;s:10:"first_name";s:4:"XXX";s:9:"last_name";s:7:"XXXXXX";s:13:"email_address";s:21:"xxx.xxxx@xxxxxx.fr";s:9:"telephone";N;s:10:"country_id";i:38;s:7:"zone_id";i:76;s:18:"default_address_id";i:24;}cartID|s:5:"57448";billto|i:24;payment|s:21:"Payment\Desjardins\HO";comments|s:0:"";shipping|a:3:{s:2:"id";s:45:"colispostalprioritaire_colispostalprioritaire";s:5:"title";s:70:"Colis International Prioritaire (France) (Livraison vers CA : 0 Kg(s))";s:4:"cost";i:18;}coupon|s:0:"";"
</code>```

答:
Because I can't find any documentation on the web that uses pipes to designate top-level keys in the serialized data, I have to assume this is a home-grown concoction.  To make matters worse there are a few errors in what is otherwise a nearly-regular serialized data string.  This being the case, your string must be custom parsed into an array for reliable handling.

I have done that job for you.  My script will correct your sample data (no guaranteed on it being 100% effective for your other home grown strings) and convert it to an array.  From the resulting array, you can either access the elements directly by key or loop.  You can also choose to use serialize() to convert it into a valid serialized data string for proper future storage/handling.

Demo

Code:

```<code>$serialstring='sessiontoken|s:32:"6450a6e3ced9cdbc38c82e51376efc0f";ClicShoppingCart|a:5:{s:8:"contents";a:1:{i:21;a:1:{s:3:"qty";i:5;}}s:14:"sub_total_cost";i:0;s:10:"total_cost";i:0;s:12:"total_weight";d:0;s:16:"shipping_address";a:2:{s:7:"zone_id";s:3:"265";s:10:"country_id";s:2:"73";}}language|s:2:"fr";currency|s:3:"USD";new_products_id_in_cart|i:21;cart_country_id|s:2:"73";Shop|a:1:{s:17:"NavigationHistory";a:1:{s:8:"snapshot";N;}cart_address_id|N;sendto|i:24;customer_group_id|a:1:{s:18:"customers_group_id";s:1:"0";}customer|a:8:{s:2:"id";i:11;s:10:"first_name";s:4:"XXX";s:9:"last_name";s:7:"XXXXXX";s:13:"email_address";s:21:"xxx.xxxx@xxxxxx.fr";s:9:"telephone";N;s:10:"country_id";i:38;s:7:"zone_id";i:76;s:18:"default_address_id";i:24;}cartID|s:5:"57448";billto|i:24;payment|s:21:"Payment\Desjardins\HO";comments|s:0:"";shipping|a:3:{s:2:"id";s:45:"colispostalprioritaire_colispostalprioritaire";s:5:"title";s:70:"Colis International Prioritaire (France) (Livraison vers CA : 0 Kg(s))";s:4:"cost";i:18;}coupon|s:0:""';
//var_export(unserialize($serialstring));  this fails because the string has errors in it

if(preg_match_all('/(\w+)\|(.*?)(?=(\w+)\||$)/',$serialstring,$matches)){
    foreach($matches[1] as $i=>$k){
        $v=$matches[2][$i];  // post-pipe group
        if(preg_match_all('/s:(\d+):"([^"]*?)"/',$v,$matches2)){ // capture string lengths and values
            foreach($matches2[1] as $i=>$len){
                if(($newlen=strlen($matches2[2][$i]))!=$len){  // if bad string length count, fix it
                    $v=str_replace("s:{$len}:\"{$matches2[2][$i]}\"","s:{$newlen}:\"{$matches2[2][$i]}\"",$v);
                }
            }
        }
        if(substr_count($v,"{")>substr_count($v,"}")){ // if insufficient closing curly brackets, fix it
            $v.=str_repeat("}",substr_count($v,"{")-substr_count($v,"}"));
        }
        if(!in_array(substr($v,-1),[";","}"])){
            $v.=";"; // append semicolon where not ending in } or ;
        }
        $result[$k]=unserialize($v);
    }
}
var_export($result);  // this is the array
echo "\n\n";
echo serialize($result);  // this is the valid serialized data string
</code>```

Title: How to extract this information php

Body:
How can I correctly extract this information in php?
For example, I need information about the customer and the id.

contents
shipping_address
currency
customer
....

Thank you

"sessiontoken|s:32:"6450a6e3ced9cdbc38c82e51376efc0f";ClicShoppingCart|a:5:{s:8:"contents";a:1:{i:21;a:1:{s:3:"qty";i:5;}}s:14:"sub_total_cost";i:0;s:10:"total_cost";i:0;s:12:"total_weight";d:0;s:16:"shipping_address";a:2:{s:7:"zone_id";s:3:"265";s:10:"country_id";s:2:"73";}}language|s:2:"fr";currency|s:3:"USD";new_products_id_in_cart|i:21;cart_country_id|s:2:"73";Shop|a:1:{s:17:"NavigationHistory";a:1:{s:8:"snapshot";N;}cart_address_id|N;sendto|i:24;customer_group_id|a:1:{s:18:"customers_group_id";s:1:"0";}customer|a:8:{s:2:"id";i:11;s:10:"first_name";s:4:"XXX";s:9:"last_name";s:7:"XXXXXX";s:13:"email_address";s:21:"xxx.xxxx@xxxxxx.fr";s:9:"telephone";N;s:10:"country_id";i:38;s:7:"zone_id";i:76;s:18:"default_address_id";i:24;}cartID|s:5:"57448";billto|i:24;payment|s:21:"Payment\Desjardins\HO";comments|s:0:"";shipping|a:3:{s:2:"id";s:45:"colispostalprioritaire_colispostalprioritaire";s:5:"title";s:70:"Colis International Prioritaire (France) (Livraison vers CA : 0 Kg(s))";s:4:"cost";i:18;}coupon|s:0:"";"

Body:
Because I can't find any documentation on the web that uses pipes to designate top-level keys in the serialized data, I have to assume this is a home-grown concoction.  To make matters worse there are a few errors in what is otherwise a nearly-regular serialized data string.  This being the case, your string must be custom parsed into an array for reliable handling.

I have done that job for you.  My script will correct your sample data (no guaranteed on it being 100% effective for your other home grown strings) and convert it to an array.  From the resulting array, you can either access the elements directly by key or loop.  You can also choose to use serialize() to convert it into a valid serialized data string for proper future storage/handling.

Demo

Code:

$serialstring='sessiontoken|s:32:"6450a6e3ced9cdbc38c82e51376efc0f";ClicShoppingCart|a:5:{s:8:"contents";a:1:{i:21;a:1:{s:3:"qty";i:5;}}s:14:"sub_total_cost";i:0;s:10:"total_cost";i:0;s:12:"total_weight";d:0;s:16:"shipping_address";a:2:{s:7:"zone_id";s:3:"265";s:10:"country_id";s:2:"73";}}language|s:2:"fr";currency|s:3:"USD";new_products_id_in_cart|i:21;cart_country_id|s:2:"73";Shop|a:1:{s:17:"NavigationHistory";a:1:{s:8:"snapshot";N;}cart_address_id|N;sendto|i:24;customer_group_id|a:1:{s:18:"customers_group_id";s:1:"0";}customer|a:8:{s:2:"id";i:11;s:10:"first_name";s:4:"XXX";s:9:"last_name";s:7:"XXXXXX";s:13:"email_address";s:21:"xxx.xxxx@xxxxxx.fr";s:9:"telephone";N;s:10:"country_id";i:38;s:7:"zone_id";i:76;s:18:"default_address_id";i:24;}cartID|s:5:"57448";billto|i:24;payment|s:21:"Payment\Desjardins\HO";comments|s:0:"";shipping|a:3:{s:2:"id";s:45:"colispostalprioritaire_colispostalprioritaire";s:5:"title";s:70:"Colis International Prioritaire (France) (Livraison vers CA : 0 Kg(s))";s:4:"cost";i:18;}coupon|s:0:""';
//var_export(unserialize($serialstring));  this fails because the string has errors in it

if(preg_match_all('/(\w+)\|(.*?)(?=(\w+)\||$)/',$serialstring,$matches)){
    foreach($matches[1] as $i=>$k){
        $v=$matches[2][$i];  // post-pipe group
        if(preg_match_all('/s:(\d+):"([^"]*?)"/',$v,$matches2)){ // capture string lengths and values
            foreach($matches2[1] as $i=>$len){
                if(($newlen=strlen($matches2[2][$i]))!=$len){  // if bad string length count, fix it
                    $v=str_replace("s:{$len}:\"{$matches2[2][$i]}\"","s:{$newlen}:\"{$matches2[2][$i]}\"",$v);
                }
            }
        }
        if(substr_count($v,"{")>substr_count($v,"}")){ // if insufficient closing curly brackets, fix it
            $v.=str_repeat("}",substr_count($v,"{")-substr_count($v,"}"));
        }
        if(!in_array(substr($v,-1),[";","}"])){
            $v.=";"; // append semicolon where not ending in } or ;
        }
        $result[$k]=unserialize($v);
    }
}
var_export($result);  // this is the array
echo "\n\n";
echo serialize($result);  // this is the valid serialized data string


问:
tensorflow, how to join the tf.string SparseTensor to 1-D dense tensor
tensorflow has tf.string_split function that can split dense tensor to SparseTensor, but not provided the opposite function.

anyone knows how to do it? thanks~

for example:
SparseTensor:

```<code>[["a", "b", "c"]
 ["d", "e"]
 ["f", "g", "h", "i"]]
</code>```

join SparseTensor with separator " " to dense tensor:

```<code>["a b c",
 "d e",
 "f g h i"]
</code>```

tensorflow中SparseTensor格式：

```<code># indices = tf.constant([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [2, 0], [2, 1], [2, 2], [2, 3]], dtype=tf.int64)
# values = tf.constant(["a", "b", "c", "d", "e", "f", "g", "h", "i"], dtype=tf.string)
# dense_shape = tf.constant([3, 4], dtype=tf.int64)
# tf.SparseTensor(indices=indices, values=values, dense_shape=dense_shape)
</code>```

update question:

```<code>join_words_list = []
slice_words_list = tf.sparse_split(sp_input=sparse_words, num_split=3, axis=0)
# slice_words_list = tf.sparse_split(sp_input=sparse_words, num_split=sparse_words.dense_shape[0], axis=0)
for slice_words in slice_words_list:
  slice_words = slice_words.values
  join_words = tf.reduce_join(slice_words, reduction_indices=0, separator=" ")
  join_words_list.append(join_words)
join_str = tf.stack(join_words_list)
</code>```

now, this create the new problem, tensorflow, split tf.string SparseTensor to the list of dense Tensor in dim 0

答:
Take a look at string_join</p>

```<code>output = tf.string_join([input0, input1])
</code>```

Body:
tensorflow has tf.string_split function that can split dense tensor to SparseTensor, but not provided the opposite function.

anyone knows how to do it? thanks~

for example:
SparseTensor:

[["a", "b", "c"]
 ["d", "e"]
 ["f", "g", "h", "i"]]

join SparseTensor with separator " " to dense tensor:

["a b c",
 "d e",
 "f g h i"]

tensorflow中SparseTensor格式：

# indices = tf.constant([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [2, 0], [2, 1], [2, 2], [2, 3]], dtype=tf.int64)
# values = tf.constant(["a", "b", "c", "d", "e", "f", "g", "h", "i"], dtype=tf.string)
# dense_shape = tf.constant([3, 4], dtype=tf.int64)
# tf.SparseTensor(indices=indices, values=values, dense_shape=dense_shape)

update question:

join_words_list = []
slice_words_list = tf.sparse_split(sp_input=sparse_words, num_split=3, axis=0)
# slice_words_list = tf.sparse_split(sp_input=sparse_words, num_split=sparse_words.dense_shape[0], axis=0)
for slice_words in slice_words_list:
  slice_words = slice_words.values
  join_words = tf.reduce_join(slice_words, reduction_indices=0, separator=" ")
  join_words_list.append(join_words)
join_str = tf.stack(join_words_list)

now, this create the new problem, tensorflow, split tf.string SparseTensor to the list of dense Tensor in dim 0

Body:
Take a look at string_join

output = tf.string_join([input0, input1])


问:
close the ftp connection after using urlretrieve
```<code>from six.moves.urllib.request import urlopen, urlretrieve
urlretrieve('ftp://ftp.cdc.noaa.gov/Datasets/ncep.reanalysis.dailyavgs/surface/air.sig995.1949.nc', filename='C:\\desktop\\')
</code>```

Do I need to close the ftp connection after using urlretrieve like this? If yes, then how?

答:
No, urlretrievewill do that for you. If you were using urlopen, you should/could close the connection (see this question), but urlretrieve handles this four you as a convenient wrapper.

Internally, urlretrieve uses an URLOpener instance, which calls close when its reference count drops to 0, which is at the end of the urlretrieve call.

Body:
from six.moves.urllib.request import urlopen, urlretrieve
urlretrieve('ftp://ftp.cdc.noaa.gov/Datasets/ncep.reanalysis.dailyavgs/surface/air.sig995.1949.nc', filename='C:\\desktop\\')

Do I need to close the ftp connection after using urlretrieve like this? If yes, then how?


问:
GCC -O2 and __attribute__((weak))
It looks like GCC with -O2 and __attribute__((weak)) produces different results depending on how you reference your weak symbols. Consider this:

$ cat weak.c

```<code>#include <stdio.h>

extern const int weaksym1;
const int weaksym1 __attribute__(( weak )) = 0;

extern const int weaksym2;
const int weaksym2 __attribute__(( weak )) = 0;

extern int weaksym3;
int weaksym3 __attribute__(( weak )) = 0;

void testweak(void)
{
    if ( weaksym1 == 0 )
    {
        printf( "0\n" );
    }
    else
    {
        printf( "1\n" );
    }

    printf( "%d\n", weaksym2 );

    if ( weaksym3 == 0 )
    {
        printf( "0\n" );
    }
    else
    {
        printf( "1\n" );
    }
}
</code>```

$ cat test.c

```<code>extern const int weaksym1;
const int weaksym1 = 1;

extern const int weaksym2;
const int weaksym2 = 1;

extern int weaksym3;
int weaksym3 = 1;

extern void testweak(void);

void main(void)
{
    testweak();
}
</code>```

$ make

```<code>gcc  -c weak.c
gcc  -c test.c
gcc  -o test test.o weak.o
</code>```

$ ./test

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

$ make ADD_FLAGS="-O2"

```<code>gcc -O2 -c weak.c
gcc -O2 -c test.c
gcc -O2 -o test test.o weak.o
</code>```

$ ./test

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

The question is, why the last "./test" produces "0 1 1", not "1 1 1"?

gcc version 5.4.0 (GCC)

答:
Summary:

Weak symbols only work correctly if you do not initialize them to a value. The linker takes care of the initialization (and it always initializes them to zero if no normal symbol of the same name exists).

If you try to initialize a weak symbol to any value, even to zero as OP did, the C compiler is free to make weird assumptions about its value. The compiler has no distinction between weak and normal symbols; it is all (dynamic) linker magic.

To fix, remove the initialization (= 0) from any symbol you declare weak:

```<code>extern const int weaksym1;
const int weaksym1 __attribute__((__weak__));

extern const int weaksym2;
const int weaksym2 __attribute__((__weak__));

extern int weaksym3;
int weaksym3 __attribute__((__weak__));
</code>```

Detailed description:

The C language has no concept of a "weak symbol". It is a functionality provided by the ELF file format, and (dynamic) linkers that use the ELF file format.

As the man 1 nm man page describes at the "V" section,

When a weak defined symbol is linked with a normal defined symbol, the
  normal defined symbol is used with no error.  When a weak undefined symbol
  is linked and the symbol is not defined, the value of the weak symbol
  becomes zero with no error.

the weak symbol declaration should not be initialized to any value, because it will have value zero if the process is not linked with a normal symbol of the same name. ("defined" in the man 1 nm page refers to a symbol existing in the ELF symbol table.)

The "weak symbol" feature was designed to work with existing C compilers. Remember, the C compilers do not have any distinction between "weak" and "normal" symbols.

To ensure this would work without running afoul of the C compiler behaviour, the "weak" symbol must be uninitialized, so that the C compiler cannot make any assumptions as to its value. Instead, it will generate code that obtains the address of the symbol as usual -- and that's where the normal/weak symbol lookup magic happens.

This also means that weak symbols can only be "auto-initialized" to zero, and not any other value, unless "overridden" by a normal, initialized symbol of the same name.

Title: GCC -O2 and __attribute__((weak))

Body:
It looks like GCC with -O2 and __attribute__((weak)) produces different results depending on how you reference your weak symbols. Consider this:

$ cat weak.c

#include <stdio.h>

extern const int weaksym1;
const int weaksym1 __attribute__(( weak )) = 0;

extern const int weaksym2;
const int weaksym2 __attribute__(( weak )) = 0;

extern int weaksym3;
int weaksym3 __attribute__(( weak )) = 0;

void testweak(void)
{
    if ( weaksym1 == 0 )
    {
        printf( "0\n" );
    }
    else
    {
        printf( "1\n" );
    }

    printf( "%d\n", weaksym2 );

    if ( weaksym3 == 0 )
    {
        printf( "0\n" );
    }
    else
    {
        printf( "1\n" );
    }
}

$ cat test.c

extern const int weaksym1;
const int weaksym1 = 1;

extern const int weaksym2;
const int weaksym2 = 1;

extern int weaksym3;
int weaksym3 = 1;

extern void testweak(void);

void main(void)
{
    testweak();
}

$ make

gcc  -c weak.c
gcc  -c test.c
gcc  -o test test.o weak.o

$ ./test

1
1
1

$ make ADD_FLAGS="-O2"

gcc -O2 -c weak.c
gcc -O2 -c test.c
gcc -O2 -o test test.o weak.o

$ ./test

0
1
1

The question is, why the last "./test" produces "0 1 1", not "1 1 1"?

gcc version 5.4.0 (GCC)

Body:
Summary:

Weak symbols only work correctly if you do not initialize them to a value. The linker takes care of the initialization (and it always initializes them to zero if no normal symbol of the same name exists).

If you try to initialize a weak symbol to any value, even to zero as OP did, the C compiler is free to make weird assumptions about its value. The compiler has no distinction between weak and normal symbols; it is all (dynamic) linker magic.

To fix, remove the initialization (= 0) from any symbol you declare weak:

extern const int weaksym1;
const int weaksym1 __attribute__((__weak__));

extern const int weaksym2;
const int weaksym2 __attribute__((__weak__));

extern int weaksym3;
int weaksym3 __attribute__((__weak__));

Detailed description:

The C language has no concept of a "weak symbol". It is a functionality provided by the ELF file format, and (dynamic) linkers that use the ELF file format.

As the man 1 nm man page describes at the "V" section,

When a weak defined symbol is linked with a normal defined symbol, the
  normal defined symbol is used with no error.  When a weak undefined symbol
  is linked and the symbol is not defined, the value of the weak symbol
  becomes zero with no error.

the weak symbol declaration should not be initialized to any value, because it will have value zero if the process is not linked with a normal symbol of the same name. ("defined" in the man 1 nm page refers to a symbol existing in the ELF symbol table.)

The "weak symbol" feature was designed to work with existing C compilers. Remember, the C compilers do not have any distinction between "weak" and "normal" symbols.

To ensure this would work without running afoul of the C compiler behaviour, the "weak" symbol must be uninitialized, so that the C compiler cannot make any assumptions as to its value. Instead, it will generate code that obtains the address of the symbol as usual -- and that's where the normal/weak symbol lookup magic happens.

This also means that weak symbols can only be "auto-initialized" to zero, and not any other value, unless "overridden" by a normal, initialized symbol of the same name.


问:
Ionic 2 - Landscape orientation enabled for iPad only
I can set the orientation to portrait-only in config.xml as follows:

```<code><preference name="Orientation" value="portrait"/>
</code>```

But how can I allow landscape orientation for iPad builds, while still disabling for iPhone as above?

答:
According to Mike Harrison from Ionic he says:

Other than manually rotating the device, not really. This would be
  something you'd writing a plugin for to modify the main App view in
  cordova

But there is a
Plugin from Ionic 1
. Look at it. Eventually you can use it in Ionic 2 too.

With this Plugin you could do something like:

```<code>if(/(ipad)/i.test(navigator.userAgent)) {
  //THIS IS THE PLUGIN IONIC 1 CODE
  $scope.changeOriantationPortrait = function() {
            screen.lockOrientation('portrait');
        }
}
</code>```

Body:
I can set the orientation to portrait-only in config.xml as follows:

<preference name="Orientation" value="portrait"/>

But how can I allow landscape orientation for iPad builds, while still disabling for iPhone as above?

Body:
According to Mike Harrison from Ionic he says:

Other than manually rotating the device, not really. This would be
  something you'd writing a plugin for to modify the main App view in
  cordova

But there is a
Plugin from Ionic 1
. Look at it. Eventually you can use it in Ionic 2 too.

With this Plugin you could do something like:

if(/(ipad)/i.test(navigator.userAgent)) {
  //THIS IS THE PLUGIN IONIC 1 CODE
  $scope.changeOriantationPortrait = function() {
            screen.lockOrientation('portrait');
        }
}


问:
writing to text file in blackberry
is there any way out that we can make the data in text file persistent? everytime a user finishes playing a game, in my program his name and respective score is written to a text file. When the next player comes the previous one gets overwritten. since am writing in write mode, I am not sure whether append mode is supported to save scores of this sort in blackberry...any suggestions are welcome</p>

答:
You should really use the PersistentStore to store this type of information - it's much easier to use and probably more reliable than trying to write files.

However, if you insist on writing files, here's the general code to open a file for appending:

```<code>private OutputStream openFileForWriting(String filePath) {
    try {
        FileConnection fconn = (FileConnection) Connector.open(filePath);
        // If no exception is thrown, then the URI is valid, but the file may or may not exist.
        if (!fconn.exists()) {
            fconn.create();  // create the file if it doesn't exist
        }
        return fconn.openOutputStream(fconn.fileSize());
    } catch (IOException ioe) {
        System.out.println("Could not open " + filePath + " for writing");
    }
    return null;
}
</code>```

Title: writing to text file in blackberry

Body:
You should really use the PersistentStore to store this type of information - it's much easier to use and probably more reliable than trying to write files.

However, if you insist on writing files, here's the general code to open a file for appending:

private OutputStream openFileForWriting(String filePath) {
    try {
        FileConnection fconn = (FileConnection) Connector.open(filePath);
        // If no exception is thrown, then the URI is valid, but the file may or may not exist.
        if (!fconn.exists()) {
            fconn.create();  // create the file if it doesn't exist
        }
        return fconn.openOutputStream(fconn.fileSize());
    } catch (IOException ioe) {
        System.out.println("Could not open " + filePath + " for writing");
    }
    return null;
}


问:
create evenly spaced and vertically centered nav bar
I apply position:absolute styling to elements and they move horizontally to the right. I need them to not do that...

nav ul {
  list-style-type: none;
  display: flex;
  justify-content: space-between;
}

nav li {
  display: inline-block;
}

nav a {
  position: absolute;
  top: 50%;
  transform: translate(0, -50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <ul>
    <li><a>Logo</a></li>
    <li><a>What</a></li>
    <li><a>How</a></li>
    <li><a>Why</a></li>
    <li><a>Supporters</a></li>
    <li><a>Blog</a></li>
    <li><a>Contact</a></li>
  </ul>
</nav></code>```

or if there is an entirely better way to make a vertically aligned and evenly spaced out nav bar, I'm open to starting fresh.

答:
You can make your list item stretch at equal sizes (i.e. justified) like this:

nav ul {
  display: table;
  width: 100%;
  table-layout: fixed;
  border-collapse: separate;
  margin: 0;
  padding: 0;
}

nav li {
  display: table-cell;
  float: none;
  width: 1%;
  height: 100px;
  border: 1px solid #ccc;
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <ul>
    <li><a>Logo</a></li>
    <li><a>What</a></li>
    <li><a>How</a></li>
    <li><a>Why</a></li>
    <li><a>Supporters</a></li>
    <li><a>Blog</a></li>
    <li><a>Contact</a></li>
  </ul>
</nav></code>```

Body:
I apply position:absolute styling to elements and they move horizontally to the right. I need them to not do that...

nav ul {
  list-style-type: none;
  display: flex;
  justify-content: space-between;
}

nav li {
  display: inline-block;
}

nav a {
  position: absolute;
  top: 50%;
  transform: translate(0, -50%);
}

Logo

What

How

Why

Supporters

Blog

Contact

or if there is an entirely better way to make a vertically aligned and evenly spaced out nav bar, I'm open to starting fresh.

Body:
You can make your list item stretch at equal sizes (i.e. justified) like this:

nav ul {
  display: table;
  width: 100%;
  table-layout: fixed;
  border-collapse: separate;
  margin: 0;
  padding: 0;
}

nav li {
  display: table-cell;
  float: none;
  width: 1%;
  height: 100px;
  border: 1px solid #ccc;
  vertical-align: middle;
}

<nav>
  <ul>
    <li><a>Logo</a></li>
    <li><a>What</a></li>
    <li><a>How</a></li>
    <li><a>Why</a></li>
    <li><a>Supporters</a></li>
    <li><a>Blog</a></li>
    <li><a>Contact</a></li>
  </ul>
</nav>


问:
selected and deselected checkbox in Swift
How to know my button selected or not in swift 3 .selected property  not found.

when i type checkBtn.selected not found in Swift 3 (Xcode 8.0)

```<code> if let button = sender as? UIButton {
        if button.selected {
            // set selected
            button.selected = true
        } else {
            // set deselected
            button.selected = false
        }
    }
</code>```

答:
```<code>if let button = sender as? UIButton {
    if button.isSelected {
        //for selected input
    } else {
        //for not selected input
    }
    button.isSelected = !button.isSelected //toggle the text box
}
</code>```

Body:
How to know my button selected or not in swift 3 .selected property  not found.

when i type checkBtn.selected not found in Swift 3 (Xcode 8.0)

 if let button = sender as? UIButton {
        if button.selected {
            // set selected
            button.selected = true
        } else {
            // set deselected
            button.selected = false
        }
    }


问:
How to set background color to button in table layout programatically?
I am making Tic Tac Toe game. And I have used buttons for tic tac toe board and set in table layout dynamically.
Problem is that, I can't set background property of the button.
My code is here.

```<code>TableLayout table = (TableLayout) findViewById(R.id.tableLayout1);
    table.removeAllViewsInLayout();

    int id = 0;

    for (int f = 0; f < board_size; f++) {
        TableRow tr = new TableRow(this);
        for (int c = 0; c < board_size; c++) {
            Button b = new Button(this);
            b.setId(id);
            b.setTextSize(15.0f);

       //below code assign color to whole table background
            //b.setBackground(Color.WHITE);
            b.setOnClickListener(this);
            id++;
            tr.addView(b, screenWidth / board_size, screenWidth / board_size);
        }
        table.addView(tr);
    }
</code>```

Please guide me. Thanks in Advance.

答:
Just call:</p>

```<code>LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(5, 5, 5, 5);
b.setLayoutParams(params);
b.setBackgroundColor(Color.GREEN); // From android.graphics.Color
</code>```

Body:
I am making Tic Tac Toe game. And I have used buttons for tic tac toe board and set in table layout dynamically.
Problem is that, I can't set background property of the button.
My code is here.

TableLayout table = (TableLayout) findViewById(R.id.tableLayout1);
    table.removeAllViewsInLayout();

    int id = 0;

    for (int f = 0; f < board_size; f++) {
        TableRow tr = new TableRow(this);
        for (int c = 0; c < board_size; c++) {
            Button b = new Button(this);
            b.setId(id);
            b.setTextSize(15.0f);

       //below code assign color to whole table background
            //b.setBackground(Color.WHITE);
            b.setOnClickListener(this);
            id++;
            tr.addView(b, screenWidth / board_size, screenWidth / board_size);
        }
        table.addView(tr);
    }

Please guide me. Thanks in Advance.

Body:
Just call:

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(5, 5, 5, 5);
b.setLayoutParams(params);
b.setBackgroundColor(Color.GREEN); // From android.graphics.Color


问:
URL regex validation
i made that:

```<code> /^(http[s]?://){0,1}(www.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}
</code>```

and checked it with a validator but on my page it is not working:

```<code>var re = /^(http[s]?://){0,1}(www.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1};
if (!re.test(url)) {
    alert("url error");
    return false;
}
</code>```

i get this error

```<code>Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
Timestamp: Tue, 30 Nov 2010 14:23:10 UTC

Message: Expected ')' in regular expression
Line: 781
Char: 23
Code: 0
URI: http://*************************
</code>```

答:
I will post, although the question has been accepted.

That regex is still incomplete.

http://www.-1-.de is not a valid domain name but would pass your test.

Here's what I use:

```<code>~^
(?:ht|f)tps?://

(?:[a-z0-9] (?:[a-z0-9-]*[a-z0-9])?      \.)*

(?:[a-z0-9][a-z0-9-]{0,62}[a-z0-9])
(?:\.[a-z]{2,5}){1,2}

$~ix
</code>```

Covers http(s), ftp(s) and .co.uk TLDs and the like. Also covers subdomains which can be 1 character in length (m.example.com for mobile versions of webpages) but will not allow m-.example.com.

Surely some might object as to the regex's completeness, since .pro TLDs require at least 4 characters as a domain name. ;-)

Also IDN domain names will only pass my regex after conversion (i.e. in the "xn--" format).

Title: URL regex validation

Body:
i made that:

 /^(http[s]?://){0,1}(www.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}

and checked it with a validator but on my page it is not working:

var re = /^(http[s]?://){0,1}(www.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1};
if (!re.test(url)) {
    alert("url error");
    return false;
}

i get this error

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
Timestamp: Tue, 30 Nov 2010 14:23:10 UTC

Message: Expected ')' in regular expression
Line: 781
Char: 23
Code: 0
URI: http://*************************

Body:
I will post, although the question has been accepted.

That regex is still incomplete.

http://www.-1-.de is not a valid domain name but would pass your test.

Here's what I use:

~^
(?:ht|f)tps?://

(?:[a-z0-9] (?:[a-z0-9-]*[a-z0-9])?      \.)*

(?:[a-z0-9][a-z0-9-]{0,62}[a-z0-9])
(?:\.[a-z]{2,5}){1,2}

$~ix

Covers http(s), ftp(s) and .co.uk TLDs and the like. Also covers subdomains which can be 1 character in length (m.example.com for mobile versions of webpages) but will not allow m-.example.com.

Surely some might object as to the regex's completeness, since .pro TLDs require at least 4 characters as a domain name. ;-)

Also IDN domain names will only pass my regex after conversion (i.e. in the "xn--" format).


问:
Set Vary: Accept-Encoding Header (nginx)
I have an nginx server and can't seem to find any information on how to send Vary: Accept-Encoding headers for CSS and JS files. Does anyone have info about this?

Thanks!

答:
If you've tried the other answers and are still seeing vary off (e.g. if you are testing speed of your page using GTMetrix), the following might help:

Make sure all your gzip_types are also set in /etc/nginx/nginx.conf http section.

The server block in /etc/nginx/sites-available/* is one place where you can set the vary header and gzip_types, but depending on how you have your site setup you may be processing and returning files before they reach that bit of config.

In /etc/nginx/nginx.conf you will find an 'http' section - in here, there is also a gzip_types and gzip_vary.

For me - CSS and JS are static files and were being served up before hitting the (wordpress) nginx sites-available file (I have varnish in front of it).

So adding the full list of gzip_types to the http section in nginx.conf fixed my issue.


问:
defining url for access within Laravel
I have a directory of Laravel projects on a NGNIX server. I would like to access each project with this kind of format

```<code>http://<domain>/<project_name>
</code>```

I would like for Laravel to recognize this as well - but -  the only to access the project (as of now) is by writing

```<code>http://<domain>/<project_name>/public
</code>```

My problem is similar to this one - but not quite so:
How can I remove "public/index.php" in the url generated laravel?

In the Server Configuration file for the domain (under NGNIX), I have the following defined:

```<code>server {
[... snip ...]
root /var/www/cons.cclv.nancys.club/;
[... snip ...]
}
</code>```

Can I perhaps use something like

```<code>server {
[... snip ...]
root /var/www/cons.cclv.nancys.club/*/public;
[... snip ...]
}
</code>```

to resolve the issue?
TIA

答:
I think you should go with Laravel Homestead.
Here is the DOC</p>

Title: defining url for access within Laravel

Body:
I have a directory of Laravel projects on a NGNIX server. I would like to access each project with this kind of format

http://<domain>/<project_name>

I would like for Laravel to recognize this as well - but -  the only to access the project (as of now) is by writing

http://<domain>/<project_name>/public

My problem is similar to this one - but not quite so:
How can I remove "public/index.php" in the url generated laravel?

In the Server Configuration file for the domain (under NGNIX), I have the following defined:

server {
[... snip ...]
root /var/www/cons.cclv.nancys.club/;
[... snip ...]
}

Can I perhaps use something like

server {
[... snip ...]
root /var/www/cons.cclv.nancys.club/*/public;
[... snip ...]
}

to resolve the issue?
TIA


问:
With java 9 ea, Eclipse fails to install and show error "An error has occurred, see the log file null"
I know this problem occurs many time, but I have find a similar situation like I have.

Every time I click the Eclipse Installer, I will get a prompt:An error has occurred, see the log file null. I can't even install Eclipse.

I guess the problem is due to "JDK 9-ea", so I am planing to uninstall jdk 9-ea and use jdk8, but maybe you can help me to solve this problem directly, thanks !

答:
First, you need to get the correct install most probably, here is the Oxygen 4.7 M6 link : http://download.eclipse.org/eclipse/downloads/drops4/S-4.7M6-201703082000/

Or the direct link to the .tar.gz

Then (after you untar the archive), go to :

```<code>Eclipse.app/Contents/Eclipse/eclipse.ini
</code>```

and add one parameter after -vmargs. It should look like this:

```<code>-vmargs
--add-modules=java.se.ee
</code>```

This will allow you to start the Eclipse under jdk-9.

In case you want to install the jdk-9 plugin (so that you could compile code under jdk-9):  you need to install the Experimental Plugin for jdk-9. There were some problems with that (I filed a bug that was closed), see this thread. At the end there is the link for on how to get the plugin.

Then you need to follow the exact instructions here for it to actually work.

Body:
First, you need to get the correct install most probably, here is the Oxygen 4.7 M6 link : http://download.eclipse.org/eclipse/downloads/drops4/S-4.7M6-201703082000/

Or the direct link to the .tar.gz

Then (after you untar the archive), go to :

Eclipse.app/Contents/Eclipse/eclipse.ini

and add one parameter after -vmargs. It should look like this:

-vmargs
--add-modules=java.se.ee

This will allow you to start the Eclipse under jdk-9.

In case you want to install the jdk-9 plugin (so that you could compile code under jdk-9):  you need to install the Experimental Plugin for jdk-9. There were some problems with that (I filed a bug that was closed), see this thread. At the end there is the link for on how to get the plugin.

Then you need to follow the exact instructions here for it to actually work.


问:
C language yes or no if statement with a char?
```<code>#include <stdio.h>
int main(void)
{
    char fever, cough; /*Sets the chars.*/

    printf("Are you running a fever? (y/n)\n"); /*Asks if they have a fever and saves their input.*/
    scanf("%c",&fever);

    printf("Do you have a runny nose/cough? (y/n)\n"); /*Asks if they have a cough and saves their input.*/
    scanf(" %c",&cough);

    printf("Please verify the folling information.\nFever: %c \nRunny nose/cough: %c \n",fever,cough); /*Asks if the following info is correct.*/

    if ((fever=y) && (cough=y))
    printf("Your recommendation is to see a doctor.");

    else if ((fever=n) && (cough=y))
    printf("Your recommendation is to get some rest.");

    else if ((fever=y) && (cough=n)
    printf("Your recommendation is to see a doctor.");

    else
    printf("Your are healthy.");
return 0;
}
</code>```

I get errors for the y's and n's

答:
1 - in C programming language and many others equal ( = ) mean assignment operator. it means you give value to variable then  if you need to say fever is equal to y you have to use == ,double equal mean equal.

2 - when you wanna say var equal to character ,you must write character in quotes like 'y'.

here you can see the correct way :

```<code>if ((fever == 'y') && (cough == 'y'))
printf("Your recommendation is to see a doctor.");
</code>```

Body:
#include <stdio.h>
int main(void)
{
    char fever, cough; /*Sets the chars.*/

    printf("Are you running a fever? (y/n)\n"); /*Asks if they have a fever and saves their input.*/
    scanf("%c",&fever);

    printf("Do you have a runny nose/cough? (y/n)\n"); /*Asks if they have a cough and saves their input.*/
    scanf(" %c",&cough);

    printf("Please verify the folling information.\nFever: %c \nRunny nose/cough: %c \n",fever,cough); /*Asks if the following info is correct.*/

    if ((fever=y) && (cough=y))
    printf("Your recommendation is to see a doctor.");

    else if ((fever=n) && (cough=y))
    printf("Your recommendation is to get some rest.");

    else if ((fever=y) && (cough=n)
    printf("Your recommendation is to see a doctor.");

    else
    printf("Your are healthy.");
return 0;
}

I get errors for the y's and n's

Body:
1 - in C programming language and many others equal ( = ) mean assignment operator. it means you give value to variable then  if you need to say fever is equal to y you have to use == ,double equal mean equal.

2 - when you wanna say var equal to character ,you must write character in quotes like 'y'.

here you can see the correct way :

if ((fever == 'y') && (cough == 'y'))
printf("Your recommendation is to see a doctor.");


问:
Single Quotes Instead of Double Quotes?
Since both are acceptable by HTML as well as languages like ASP.NET and PHP when using attributes or strings, why is it that some people use single quotes and double quotes interchangeably?

It is my understanding that it is syntactically correct to use double quotes where possible, single when you need to embed a double quote for inline logic.

Is there something I am missing?

For examples:

HTML

```<code><a href='http://google.com'>Google</a>
</code>```

PHP

```<code><? echo 'Hello World!'; ?>
</code>```

ASP.NET

```<code><form id='myForm' runat='server'></form>
</code>```

答:
Technically, in PHP single quotes are faster since you don't need to parse the content within.

edit:
So double quotes are automatically converted to single quotes, but if you have variable substitution going on within your double quoted string, that's when you take a performance hit:

http://www.codeforest.net/php-myth-busters-using-single-quotes-on-string-is-faster-then-double-quotes

Either ways, to answer OP's question while the jury is out on this, play it safe (TM) and use single quotes :)

Title: Single Quotes Instead of Double Quotes?

Body:
Since both are acceptable by HTML as well as languages like ASP.NET and PHP when using attributes or strings, why is it that some people use single quotes and double quotes interchangeably?

It is my understanding that it is syntactically correct to use double quotes where possible, single when you need to embed a double quote for inline logic.

Is there something I am missing?

For examples:

HTML

Google

PHP

<? echo 'Hello World!'; ?>

ASP.NET

<form id='myForm' runat='server'></form>