问:
Firebase dataSnapshot.getValue( .class) Crash
I need help with my code, I can save to my database. But when i go to get value to my app i get crash. Its my code.

```<code>      alanRef.child("").addValueEventListener(new ValueEventListener(){
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                Marcadores_info_carga group = dataSnapshot.getValue(Marcadores_info_carga.class);
                System.out.println(group);

                }

public class Marcadores_info_carga {

        // Se definen las variable para enviar
        private int nroreclamocarga;
        private String titulocarga;
        private String informacioncarga;
        private String direccioncarga;
        private double latitudcarga;
        private double longitudcarga;

        public Marcadores_info_carga() {
        }

        public Marcadores_info_carga(int nroreclamocarga, String titulocarga, String informacioncarga, String direccioncarga, double latitudcarga, double longitudcarga){

            this.nroreclamocarga = nroreclamocarga;
            this.titulocarga = titulocarga;
            this.informacioncarga = informacioncarga;
            this.direccioncarga = direccioncarga;
            this.latitudcarga = latitudcarga;
            this.longitudcarga = longitudcarga;
        }

        public int getNroreclamocarga() {

            return nroreclamocarga;
        }

        public String getTitulocarga() {

            return titulocarga;
        }
        public String getInformacioncarga() {

            return informacioncarga;
        }

        public String getDireccioncarga() {

            return direccioncarga;
        }

        public double getLatitud() {

           return latitudcarga;
       }

        public double getLongitud() {

            return longitudcarga;
       }

    }
</code>```

I get crash when this update. I was trying and debugging and connecting well to the database but I did not get it to work

UPDATED:

```<code>MY LOGCAT LOGCAT:
</code>```

 03-29 23:09:06.223 397-414/? W/ActivityManager: Activity pause timeout for ActivityRecord{4a9a09e4 u0 com.example.lays.myapplication/.MapsActivity t63 f}
03-29 23:09:06.233 697-697/? D/FirebaseApp: Notifying background state change listeners.
03-29 23:09:06.253 697-697/? W/EGL_emulation: eglSurfaceAttrib not implemented
03-29 23:09:06.703 397-520/? W/NetworkManagementSocketTagger: setKernelCountSet(10037, 0) failed with errno -13
03-29 23:09:16.713 397-414/? W/ActivityManager: Activity destroy timeout for ActivityRecord{4a9a09e4 u0 com.example.lays.myapplication/.MapsActivity t63 f}
03-29 23:09:38.903 683-689/? D/dalvikvm: GC_CONCURRENT freed 396K, 13% free 3328K/3796K, paused 0ms+0ms, total 2ms```
</div>
</div>
</p>
<p>MY DATABASE:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    {
  "direccion" : "213",
  "informacion" : "123",
  "latitud" : -60.726239047944546,
  "longitud" : -32.886316425298524,
  "nroreclamo" : "213",
  "titulo" : "2132"
}</code>```

答:
Change the 'private' fields to 'public' in your JavaBeans,and change your javabean's fields:

```<code>ppublic class Marcadores_info_carga {

/**
 * direccion : 213
 * informacion : 123
 * latitud : 60.726239047944546
 * longitud : -32.886316425298524
 * nroreclamo : 213
 * titulo : 2132
 */

public String direccion;
public String informacion;
public double latitud;
public double longitud;
public String nroreclamo;
public String titulo;

public String getDireccion() {
    return direccion;
}

public void setDireccion(String direccion) {
    this.direccion = direccion;
}

public String getInformacion() {
    return informacion;
}

public void setInformacion(String informacion) {
    this.informacion = informacion;
}

public double getLatitud() {
    return latitud;
}

public void setLatitud(double latitud) {
    this.latitud = latitud;
}

public double getLongitud() {
    return longitud;
}

public void setLongitud(double longitud) {
    this.longitud = longitud;
}

public String getNroreclamo() {
    return nroreclamo;
}

public void setNroreclamo(String nroreclamo) {
    this.nroreclamo = nroreclamo;
}

public String getTitulo() {
    return titulo;
}

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

UPDATE:
Your java bean not match the database json field:

```<code>{
"direccion" : "213",
"informacion" : "123",
"latitud" : 60.726239047944546,
"longitud" : -32.886316425298524,
"nroreclamo" : "213",
"titulo" : "2132"
}
</code>```

Body:
I need help with my code, I can save to my database. But when i go to get value to my app i get crash. Its my code.

      alanRef.child("").addValueEventListener(new ValueEventListener(){
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                Marcadores_info_carga group = dataSnapshot.getValue(Marcadores_info_carga.class);
                System.out.println(group);

                }

public class Marcadores_info_carga {

        // Se definen las variable para enviar
        private int nroreclamocarga;
        private String titulocarga;
        private String informacioncarga;
        private String direccioncarga;
        private double latitudcarga;
        private double longitudcarga;

        public Marcadores_info_carga() {
        }

        public Marcadores_info_carga(int nroreclamocarga, String titulocarga, String informacioncarga, String direccioncarga, double latitudcarga, double longitudcarga){

            this.nroreclamocarga = nroreclamocarga;
            this.titulocarga = titulocarga;
            this.informacioncarga = informacioncarga;
            this.direccioncarga = direccioncarga;
            this.latitudcarga = latitudcarga;
            this.longitudcarga = longitudcarga;
        }

        public int getNroreclamocarga() {

            return nroreclamocarga;
        }

        public String getTitulocarga() {

            return titulocarga;
        }
        public String getInformacioncarga() {

            return informacioncarga;
        }

        public String getDireccioncarga() {

            return direccioncarga;
        }

        public double getLatitud() {

           return latitudcarga;
       }

        public double getLongitud() {

            return longitudcarga;
       }

    }

I get crash when this update. I was trying and debugging and connecting well to the database but I did not get it to work

UPDATED:

MY LOGCAT LOGCAT:

 03-29 23:09:06.223 397-414/? W/ActivityManager: Activity pause timeout for ActivityRecord{4a9a09e4 u0 com.example.lays.myapplication/.MapsActivity t63 f}
03-29 23:09:06.233 697-697/? D/FirebaseApp: Notifying background state change listeners.
03-29 23:09:06.253 697-697/? W/EGL_emulation: eglSurfaceAttrib not implemented
03-29 23:09:06.703 397-520/? W/NetworkManagementSocketTagger: setKernelCountSet(10037, 0) failed with errno -13
03-29 23:09:16.713 397-414/? W/ActivityManager: Activity destroy timeout for ActivityRecord{4a9a09e4 u0 com.example.lays.myapplication/.MapsActivity t63 f}
03-29 23:09:38.903 683-689/? D/dalvikvm: GC_CONCURRENT freed 396K, 13% free 3328K/3796K, paused 0ms+0ms, total 2ms

MY DATABASE:

    {
  "direccion" : "213",
  "informacion" : "123",
  "latitud" : -60.726239047944546,
  "longitud" : -32.886316425298524,
  "nroreclamo" : "213",
  "titulo" : "2132"
}

Body:
Change the 'private' fields to 'public' in your JavaBeans,and change your javabean's fields:

ppublic class Marcadores_info_carga {

/**
 * direccion : 213
 * informacion : 123
 * latitud : 60.726239047944546
 * longitud : -32.886316425298524
 * nroreclamo : 213
 * titulo : 2132
 */

public String direccion;
public String informacion;
public double latitud;
public double longitud;
public String nroreclamo;
public String titulo;

public String getDireccion() {
    return direccion;
}

public void setDireccion(String direccion) {
    this.direccion = direccion;
}

public String getInformacion() {
    return informacion;
}

public void setInformacion(String informacion) {
    this.informacion = informacion;
}

public double getLatitud() {
    return latitud;
}

public void setLatitud(double latitud) {
    this.latitud = latitud;
}

public double getLongitud() {
    return longitud;
}

public void setLongitud(double longitud) {
    this.longitud = longitud;
}

public String getNroreclamo() {
    return nroreclamo;
}

public void setNroreclamo(String nroreclamo) {
    this.nroreclamo = nroreclamo;
}

public String getTitulo() {
    return titulo;
}

public void setTitulo(String titulo) {
    this.titulo = titulo;
}
}

UPDATE:
Your java bean not match the database json field:

{
"direccion" : "213",
"informacion" : "123",
"latitud" : 60.726239047944546,
"longitud" : -32.886316425298524,
"nroreclamo" : "213",
"titulo" : "2132"
}


来源: stackexchange

问:
git push showing "Everything up-to-date" but compare shows differences
Hello I have this problem I contribute to an opensource repo. Each time I work from the master branch even if what am working on is not for the master branch usually when the code is merged I will pull upstream (The original repo) to get my master branch back to normal. This has caused me problems recently after creating some changes and committed I pulled upstream to get back at the same level with the original repository when I push to my cloned repo it says everything is up to date. But When I do compare on github it shows differences with upstream.
I have tried

git checkout master

pulling upstream again committing and then
pushing again

that did not  work!
I tried checking out commits

```<code> 1. git checkout HEAD~5
 2. git pull upstream master
 3. git add
 4. git commit
 5. git push
</code>```

Did not work still.

I will also like to know a simple way to create a quick-fix branch for every issue and avoid doing everything from my master branch thanks.

答:
To make your origin/master is same with upstream/master needs force pull/push (maybe upstream/master changed the history commits). So before that, you need to push the branches which checked out from your local master branch to origin so that changes on these branch will not lost. Then sync origin/master with upstream/master with below steps:

```<code>git checkout master
git pull -f upstream master
git reset --hard upstream/master
git push -f origin master
</code>```

Now origin/master is sync with upstream/master. You can double check with below commands:

```<code>git log origin/master..upstream/master
git log upstream/master..origin/master
</code>```

If both of the two commands have no output, that means origin/master and upstream/master at the same level (synchronized).

ContentLicense: CC BY-SA 3.0

Body:
Hello I have this problem I contribute to an opensource repo. Each time I work from the master branch even if what am working on is not for the master branch usually when the code is merged I will pull upstream (The original repo) to get my master branch back to normal. This has caused me problems recently after creating some changes and committed I pulled upstream to get back at the same level with the original repository when I push to my cloned repo it says everything is up to date. But When I do compare on github it shows differences with upstream.
I have tried

git checkout master

pulling upstream again committing and then
pushing again

that did not  work!
I tried checking out commits

 1. git checkout HEAD~5
 2. git pull upstream master
 3. git add
 4. git commit
 5. git push

Did not work still.

I will also like to know a simple way to create a quick-fix branch for every issue and avoid doing everything from my master branch thanks.

Body:
To make your origin/master is same with upstream/master needs force pull/push (maybe upstream/master changed the history commits). So before that, you need to push the branches which checked out from your local master branch to origin so that changes on these branch will not lost. Then sync origin/master with upstream/master with below steps:

git checkout master
git pull -f upstream master
git reset --hard upstream/master
git push -f origin master

Now origin/master is sync with upstream/master. You can double check with below commands:

git log origin/master..upstream/master
git log upstream/master..origin/master

If both of the two commands have no output, that means origin/master and upstream/master at the same level (synchronized).


问:
Xcode 8.3 can't support Swift 2.3
I'm using Swift 2.3 in my project. Yesterday, I updated Xcode to version 8.3 but my project can't build successfully any more. I got this error message.

“Swift Language Version” (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit > Convert > To Current Swift Syntax…] menu to choose a Swift version or use the Build Settings editor to configure the build setting directly.

Please help me! Thanks!

答:
That's true.
You have to convert your code to Swift 3. Or try to download a lower version of Xcode.</p>

Title: Xcode 8.3 can't support Swift 2.3


问:
How to calculate T-test from two Pandas data frame row-by-row
I have the following two data frames:

```<code>import pandas as pd
import scipy.stats
import numpy as np
df_a = pd.DataFrame({
               's1': [10,10,12,13,14,15],
               's2': [100,100,112,1.3,14,125],
               's2': [13,200,10,13,14.5,10.5],
               'gene_symbol': ['a', 'b', 'c', 'd', 'e', 'f'],
               })

df_b = pd.DataFrame({
               's1': [15,20,123,13,14,15,1],
               's2': [130,100,72,1.3,14,125,2],
               's2': [213,200,35.4,13,414.5,130.5,3],
               'gene_symbol': ['a', 'b', 'c', 'd', 'e', 'f','g'],
               })

df_a.set_index('gene_symbol', inplace=True)
df_b.set_index('gene_symbol', inplace=True)
</code>```

Which looks like this:

```<code>             s1     s2
gene_symbol
a            10   13.0
b            10  200.0
c            12   10.0
d            13   13.0
e            14   14.5
f            15   10.5

In [51]: df_b
Out[51]:
              s1     s2
gene_symbol
a             15  213.0
b             20  200.0
c            123   35.4
d             13   13.0
e             14  414.5
f             15  130.5
g              1    3.0
</code>```

What I want to do is to calculate T-test p-value gene by gene.
For example for gene a we will have

```<code>In [47]: scipy.stats.ttest_ind([ 10,13.0],[15,213.0])
Out[47]: Ttest_indResult(statistic=-1.0352347135782713, pvalue=0.4093249100598676)
</code>```

How can I apply that for all rows that shares common genes for two data frames (e.g. ignore gene g in df_b).

I tried this but it failed:

```<code>scipy.stats.ttest_ind(df_a, df_b,axis=1)
</code>```

答:
You can remove g row using your gene_symbol index by matching two dataframes, or indexes.

You can use pandas.merge() to join two DataFrames on matching columns or indexes, and use the columns of the merged DataFrame on ttest_ind:

```<code># default join is inner
df_m = pd.merge(df_a, df_b, left_index=True, right_index=True)
scipy.stats.ttest_ind(df_m.ix[:, :2], df_m.ix[:, 2:], axis=1)
</code>```

Or you can find the intersection of the indexes and use them to slice your datasets:

```<code>idx = df_a.index.intersection(df_b.index)
scipy.stats.ttest_ind(df_a.loc[idx], df_b.loc[idx], axis=1)
</code>```

Body:
I have the following two data frames:

import pandas as pd
import scipy.stats
import numpy as np
df_a = pd.DataFrame({
               's1': [10,10,12,13,14,15],
               's2': [100,100,112,1.3,14,125],
               's2': [13,200,10,13,14.5,10.5],
               'gene_symbol': ['a', 'b', 'c', 'd', 'e', 'f'],
               })

df_b = pd.DataFrame({
               's1': [15,20,123,13,14,15,1],
               's2': [130,100,72,1.3,14,125,2],
               's2': [213,200,35.4,13,414.5,130.5,3],
               'gene_symbol': ['a', 'b', 'c', 'd', 'e', 'f','g'],
               })

df_a.set_index('gene_symbol', inplace=True)
df_b.set_index('gene_symbol', inplace=True)

Which looks like this:

             s1     s2
gene_symbol
a            10   13.0
b            10  200.0
c            12   10.0
d            13   13.0
e            14   14.5
f            15   10.5

In [51]: df_b
Out[51]:
              s1     s2
gene_symbol
a             15  213.0
b             20  200.0
c            123   35.4
d             13   13.0
e             14  414.5
f             15  130.5
g              1    3.0

What I want to do is to calculate T-test p-value gene by gene.
For example for gene a we will have

In [47]: scipy.stats.ttest_ind([ 10,13.0],[15,213.0])
Out[47]: Ttest_indResult(statistic=-1.0352347135782713, pvalue=0.4093249100598676)

How can I apply that for all rows that shares common genes for two data frames (e.g. ignore gene g in df_b).

I tried this but it failed:

scipy.stats.ttest_ind(df_a, df_b,axis=1)

Body:
You can remove g row using your gene_symbol index by matching two dataframes, or indexes.

You can use pandas.merge() to join two DataFrames on matching columns or indexes, and use the columns of the merged DataFrame on ttest_ind:

# default join is inner
df_m = pd.merge(df_a, df_b, left_index=True, right_index=True)
scipy.stats.ttest_ind(df_m.ix[:, :2], df_m.ix[:, 2:], axis=1)

Or you can find the intersection of the indexes and use them to slice your datasets:

idx = df_a.index.intersection(df_b.index)
scipy.stats.ttest_ind(df_a.loc[idx], df_b.loc[idx], axis=1)


问:
How to get first day of last month?
I need to get the first day of last name everyday.
I used to code it like this:

```<code>echo date('Ym01',strtotime('last month'));
</code>```

But today (March 30,2017), it returned the first day of this month, not last month.

I tried echo date('Y-m-d', strtotime('first day of last month')); from this question but it returned 1970-01-01 instead.

Can someone explain to me why the code return date like that?

答:
this must work even on older versions of php

```<code><?php

$lastmonth= new datetime();
//formating the date
$lastmonth=$lastmonth->format("Ym01");
//subtracting 1 month to make it last month
$lastmonth=date('Ym01',strtotime($lastmonth . '-1 month'));
echo $lastmonth;

?>
</code>```

If it doesn't work then the problem is with your server

Title: How to get first day of last month?

Body:
I need to get the first day of last name everyday.
I used to code it like this:

echo date('Ym01',strtotime('last month'));

But today (March 30,2017), it returned the first day of this month, not last month.

I tried echo date('Y-m-d', strtotime('first day of last month')); from this question but it returned 1970-01-01 instead.

Can someone explain to me why the code return date like that?

Body:
this must work even on older versions of php

<?php

$lastmonth= new datetime();
//formating the date
$lastmonth=$lastmonth->format("Ym01");
//subtracting 1 month to make it last month
$lastmonth=date('Ym01',strtotime($lastmonth . '-1 month'));
echo $lastmonth;

?>

If it doesn't work then the problem is with your server


问:
At what point during the Wordpress Lifecycle can I use wp_get_current_user?
I'm writing an integration piece with a third party system and need to check certain values when a user logs in.

I've tried several different hooks: wp_init, wp_login and wp_loaded, but wp_get_current_user always returns null.

答:
E.g.: To determine if there is a user currently logged in, do this:

```<code><?php
wp_get_current_user();
if ( 0 == $current_user->ID ) {
    // Not logged in.
} else {
    // Logged in.
}
?>
</code>```

default usage
The call to wp_get_current_user() return WP_User object.

```<code><?php
    wp_get_current_user();
    /**
     * @example Safe usage: $current_user = wp_get_current_user();
     * if ( !($current_user instanceof WP_User) )
     *     return;
     */
    echo 'Username: ' . $current_user->user_login . '<br />';
    echo 'User email: ' . $current_user->user_email . '<br />';
    echo 'User level: ' . $current_user->user_level . '<br />';
    echo 'User first name: ' . $current_user->user_firstname . '<br />';
    echo 'User last name: ' . $current_user->user_lastname . '<br />';
    echo 'User display name: ' . $current_user->display_name . '<br />';
    echo 'User ID: ' . $current_user->ID . '<br />';
?>
</code>```

more on this page http://codex.wordpress.org/Function_Reference/wp_get_current_user

ContentLicense: CC BY-SA 2.5

Body:
E.g.: To determine if there is a user currently logged in, do this:

<?php
wp_get_current_user();
if ( 0 == $current_user->ID ) {
    // Not logged in.
} else {
    // Logged in.
}
?>

default usage
The call to wp_get_current_user() return WP_User object.

<?php
    wp_get_current_user();
    /**
     * @example Safe usage: $current_user = wp_get_current_user();
     * if ( !($current_user instanceof WP_User) )
     *     return;
     */
    echo 'Username: ' . $current_user->user_login . '<br />';
    echo 'User email: ' . $current_user->user_email . '<br />';
    echo 'User level: ' . $current_user->user_level . '<br />';
    echo 'User first name: ' . $current_user->user_firstname . '<br />';
    echo 'User last name: ' . $current_user->user_lastname . '<br />';
    echo 'User display name: ' . $current_user->display_name . '<br />';
    echo 'User ID: ' . $current_user->ID . '<br />';
?>

more on this page http://codex.wordpress.org/Function_Reference/wp_get_current_user


问:
How can I change CSS styles as a user reaches a specific point on a page?
I am trying to underline each specific title inside of a fixed navigation bar as a person reaches specific points on a page.

Ex: As a person reaches the Contact Info section of the page, the title "CONTACT INFO" inside of the fixed navigation bar will be the only title with a red underline.

答:
The easiest way for me is to use jQuery.

```<code>$(window).on('scroll', function () {
    if ($(window).scrollTop() > SPECIFIC_POINT_ON_A_PAGE) {
        // if you want to add CSS class to the element:
        $('element-selector-here').addClass('display-block');
        // Or, if you want to add CSS code directly:
        // $('element-selector-here').css('display', 'block');
    } else {
        // It's on you whether you want to remove the CSS if you scroll the page
        // to before the specific point you set
        $('element-selector-here').removeClass('display-block');
    }
});
</code>```

Where SPECIFIC_POINT_ON_A_PAGE could be the Y position of a specific element, e.g. $('element-selector-that-triggers-the-css').offset().top

Edit:

If you want to achieve what you want as you stated on your example, Marcus Lind's answer is the most simple that you can use.

I used Scrollspy too on my personal web page. Here is the way I use it:

```<code>// Highlight the top nav as scrolling occurs
$('body').scrollspy({
    target: '#navbar',
    offset: ($('#navbar').outerHeight()) // you may want to use offset
});
</code>```

And the HTML is like this; You must match the nav item href and the ID of the element:

```<code><nav id="navbar" class="navbar navbar-default navbar-fixed-top">
    <div class="container">
        <div class="page-scroll navbar-header">
            <button class="navbar-toggle" data-target="#bs-example-navbar-collapse-1" data-toggle="collapse" type="button"><span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span></button> <a class="navbar-brand" href="#page-top">Rizki Pratama</a>
        </div>
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav navbar-right">
                <li class="page-scroll active">
                    <a href="#section-1">Section 1</a>
                </li>
                <li class="page-scroll">
                    <a href="#section-2">Section 2</a>
                </li>
                <li class="page-scroll">
                    <a href="#section-3">Section 3</a>
                </li>
            </ul>
        </div>
    </div>
</nav>

....

<div id="section-1">
    <!-- Some content inside -->
</div>
<div id="section-2">
    <!-- Some content inside -->
</div>
<div id="section-3">
    <!-- Some content inside -->
</div>
</code>```

Body:
The easiest way for me is to use jQuery.

$(window).on('scroll', function () {
    if ($(window).scrollTop() > SPECIFIC_POINT_ON_A_PAGE) {
        // if you want to add CSS class to the element:
        $('element-selector-here').addClass('display-block');
        // Or, if you want to add CSS code directly:
        // $('element-selector-here').css('display', 'block');
    } else {
        // It's on you whether you want to remove the CSS if you scroll the page
        // to before the specific point you set
        $('element-selector-here').removeClass('display-block');
    }
});

Where SPECIFIC_POINT_ON_A_PAGE could be the Y position of a specific element, e.g. $('element-selector-that-triggers-the-css').offset().top

Edit:

If you want to achieve what you want as you stated on your example, Marcus Lind's answer is the most simple that you can use.

I used Scrollspy too on my personal web page. Here is the way I use it:

// Highlight the top nav as scrolling occurs
$('body').scrollspy({
    target: '#navbar',
    offset: ($('#navbar').outerHeight()) // you may want to use offset
});

And the HTML is like this; You must match the nav item href and the ID of the element:

<nav id="navbar" class="navbar navbar-default navbar-fixed-top">
    <div class="container">
        <div class="page-scroll navbar-header">
            <button class="navbar-toggle" data-target="#bs-example-navbar-collapse-1" data-toggle="collapse" type="button"><span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span></button> <a class="navbar-brand" href="#page-top">Rizki Pratama</a>
        </div>
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav navbar-right">
                <li class="page-scroll active">
                    <a href="#section-1">Section 1</a>
                </li>
                <li class="page-scroll">
                    <a href="#section-2">Section 2</a>
                </li>
                <li class="page-scroll">
                    <a href="#section-3">Section 3</a>
                </li>
            </ul>
        </div>
    </div>
</nav>

....

<div id="section-1">
    <!-- Some content inside -->
</div>
<div id="section-2">
    <!-- Some content inside -->
</div>
<div id="section-3">
    <!-- Some content inside -->
</div>


问:
Reference build.gradle versionName attribute in xml layout
I'd like to have a layout file which references the versionName attribute in my gradle file:

```<code>...
defaultConfig {
    applicationId "se.test.myapp"
    minSdkVersion 14
    targetSdkVersion 22
    versionCode 1
    versionName "1.0"
}
....
</code>```

Something like

```<code><TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/versionName"
    />
</code>```

Is there a neat way to to this, without having to set up the layout in my code?

答:
Edit: You should not use Jack only for this. As per the official announcement Jack is deprecated (for everything except Java 8 features).

I used a string resource:

```<code><resources>
    <string name="app_ver" translatable="false">1.0.2</string>
    ...
</resources>
</code>```

in the app's build.gradle:

```<code>android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
        ...
        versionName "@string/app_ver"
        jackOptions {
            enabled true
        }
    }
...
}
</code>```

And like this:

```<code><Preference
    android:title="Version"
    android:summary="@string/app_ver"/>
</code>```

This project in GitHub contains a working version of this.

Body:
I'd like to have a layout file which references the versionName attribute in my gradle file:

...
defaultConfig {
    applicationId "se.test.myapp"
    minSdkVersion 14
    targetSdkVersion 22
    versionCode 1
    versionName "1.0"
}
....

Something like

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/versionName"
    />

Is there a neat way to to this, without having to set up the layout in my code?

Body:
Edit: You should not use Jack only for this. As per the official announcement Jack is deprecated (for everything except Java 8 features).

I used a string resource:

<resources>
    <string name="app_ver" translatable="false">1.0.2</string>
    ...
</resources>

in the app's build.gradle:

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
        ...
        versionName "@string/app_ver"
        jackOptions {
            enabled true
        }
    }
...
}

And like this:

<Preference
    android:title="Version"
    android:summary="@string/app_ver"/>

This project in GitHub contains a working version of this.


问:
I'm trying to call a row from an HTML table into a JS function
I started last night so i'm a) sure there is an easy solution and b) not oblivious to the fact that my code is very crappy.
So i pulled this Stat table from a website and I already have a function running so that when I type a team name into the website it returns a number. However, what I'm trying to do is have it so that when i type a team name in it won't return a number, but rather it's respective row on the table. The numbers that are currently called in the function are just placeholders for now. As you can see i tried to call a row at the end of the function using an ID I assigned to the Celtics row but what it returns is [object HTMLTableRowElement].
Any help is appreciated, Thanks!!</p>

```<code> <html>
<canvas id = 'gCanvas' width = '400' height = '600'></canvas>
<script>
var groceryItem = "";

window.onload = function() {
    canvas = document.getElementById('gCanvas');
    ctx = canvas.getContext('2d');
    window.addEventListener('keydown', keyPressed, false);
};

function keyPressed(e) {
    if (e.keyCode != '13') {
        var letter = String.fromCharCode(parseInt(e.keyCode));
        groceryItem += letter;
        console.log(groceryItem);
    }

    if (e.keyCode == '13') {
        grocery();
        groceryItem = "";
    }

}

function grocery() {
    ctx.clearRect(0,0,canvas.width, canvas.height);
    drawBackground();
    ctx.fillStyle = 'black';
    ctx.font="40px Arial";

    switch (groceryItem) {
case 'CELTICS':
    ctx.fillText("1", 50, 50);
    break;
  case 'CAVALIERS':
  case 'CAVS':
    ctx.fillText('2', 50, 50);
    break;
  case 'WIZARDS':
    ctx.fillText('3', 50, 50);
    break;
  case 'RAPTORS':
    ctx.fillText('4', 50, 50);
    break;
  case 'HAWKS':
    ctx.fillText('5', 50, 50);
    break;
    case 'BUCKS':
    ctx.fillText('6', 50, 50);
    break;
     case 'PACERS':
    ctx.fillText('7', 50, 50);
    break;
     case 'HEAT':
    ctx.fillText('8', 50, 50);
    break;
     case 'BULLS':
    ctx.fillText('9', 50, 50);
    break;
     case 'PISTONS':
    ctx.fillText('10', 50, 50);
    break;
     case 'HORNETS':
    ctx.fillText('11', 50, 50);
    break;
     case '76ERS':
    ctx.fillText('12', 50, 50);
    break;
     case 'KNICKS':
    ctx.fillText('13', 50, 50);
    break;
     case 'MAGIC':
    ctx.fillText('14', 50, 50);
    break;
     case 'NETS':
    ctx.fillText('15', 50, 50);
    break;
     case 'WARRIORS':
    ctx.fillText('16', 50, 50);
    break;
     case 'SPURS':
    ctx.fillText(index('23'), 100, 100);
    break;
     case 'ROCKETS':
    ctx.fillText('18', 50, 50);
    break;
     case 'JAZZ':
    ctx.fillText('19', 50, 50);
    break;
     case 'CLIPPERS':
    ctx.fillText('20', 50, 50);
    break;
     case 'THUNDER':
    ctx.fillText('21', 50, 50);
    break;
     case 'GRIZZLIES':
    ctx.fillText('22', 50, 50);
    break;
     case 'TRAILBLAZERS':
    ctx.fillText('23', 50, 50);
    break;
     case 'NUGGETS':
    ctx.fillText('24', 50, 50);
    break;
     case 'MAVERICKS':
    ctx.fillText('25', 50, 50);
    break;
     case 'PELICANS':
    ctx.fillText('26', 50, 50);
    break;
     case 'TIMBERWOLVES':
    ctx.fillText('27', 50, 50);
    break;
     case 'KINGS':
    ctx.fillText('28', 50, 50);
    break;
     case 'SUNS':
    ctx.fillText('29', 50, 50);
    break;
     case 'LAKERS':
    ctx.fillText('30', 50, 50);
    break;
  default:
    ctx.fillText('Invalid Team', 50, 50);
    break;

    }
}
function drawBackground() {
    ctx.fillStyle = 'white';
    ctx.fillRect(0,0,canvas.width, canvas.height);

}
</script>

<div class="nba-stat-table">
  <div class="nba-stat-table__overflow" data-fixed="2" role="grid">
      <table class="table">
        <thead>
          <tr>
            <th></th>
            <th sort="" cf="" data-field="TEAM_NAME" class="text sorted desc" ripple=""><br>TEAM</th>
            <th sort="" cf="" data-field="GP" data-rank="" data-dir="-1" ripple="">GP</th>
            <th sort="" cf="" data-field="W" data-rank="" data-dir="-1" ripple="">W</th>
            <th sort="" cf="" data-field="L" data-rank="" data-dir="-1" ripple="">L</th>
            <th sort="" cf="" data-field="W_PCT" data-rank="" data-dir="-1" ripple="" class="asc">WIN%</th>
            <th sort="" cf="" data-field="MIN" data-rank="" data-dir="-1" ripple="">MIN</th>
            <th sort="" cf="" data-field="EFG_PCT" data-rank="" data-dir="-1" ripple="">eFG%</th>
            <th sort="" cf="" data-field="FTA_RATE" data-rank="" data-dir="-1" ripple="">FTA<br>Rate</th>
            <th sort="" cf="" data-field="TM_TOV_PCT" data-rank="" data-dir="-1" ripple="">TOV%</th>
            <th sort="" cf="" data-field="OREB_PCT" data-rank="" data-dir="-1" ripple="">OREB%</th>
            <th sort="" cf="" data-field="OPP_EFG_PCT" data-rank="" data-dir="-1" ripple="">Opp<br>eFG%</th>
            <th sort="" cf="" data-field="OPP_FTA_RATE" data-rank="" data-dir="-1" ripple="">Opp<br>FTA Rate</th>
            <th sort="" cf="" data-field="OPP_TOV_PCT" data-rank="" data-dir="-1" ripple="">Opp<br>TOV%</th>
            <th sort="" cf="" data-field="OPP_OREB_PCT" data-rank="" data-dir="-1" ripple="">Opp<br>OREB%</th>
            <th sort="" cf="" hidden="" data-field="GP_RANK" ripple="">GP RANK</th>
            <th sort="" cf="" hidden="" data-field="W_RANK" ripple="">W RANK</th>
            <th sort="" cf="" hidden="" data-field="L_RANK" ripple="">L RANK</th>
            <th sort="" cf="" hidden="" data-field="W_PCT_RANK" ripple="">WIN% RANK</th>
            <th sort="" cf="" hidden="" data-field="MIN_RANK" ripple="">MIN RANK</th>
            <th sort="" cf="" hidden="" data-field="EFG_PCT_RANK" ripple="">eFG% RANK</th>
            <th sort="" cf="" hidden="" data-field="FTA_RATE_RANK" ripple="">FTA<br>Rate RANK</th>
            <th sort="" cf="" hidden="" data-field="TM_TOV_PCT_RANK" ripple="">TO<br>Ratio RANK</th>
            <th sort="" cf="" hidden="" data-field="OREB_PCT_RANK" ripple="">OREB% RANK</th>
            <th sort="" cf="" hidden="" data-field="OPP_EFG_PCT_RANK" ripple="">Opp<br>eFG% RANK</th>
            <th sort="" cf="" hidden="" data-field="OPP_FTA_RATE_RANK" ripple="">Opp<br>FTA Rate RANK</th>
            <th sort="" cf="" hidden="" data-field="OPP_TOV_PCT_RANK" ripple="">Opp<br>To Ratio RANK</th>
            <th sort="" cf="" hidden="" data-field="OPP_OREB_PCT_RANK" ripple="">Opp<br>OREB% RANK</th>
          </tr>
        </thead>
        <tbody>
          <!-- ngRepeat: (i, row) in page track by row.$hash --><tr data-ng-repeat="(i, row) in page track by row.$hash" index="5" class="ng-scope">
            <td class="rank ng-binding"></td>
            <td class="team-name first sorted"><a href="/team/#!/1610612764/traditional/?" class="ng-binding">Washington Wizards</a></td>
            <td class="ng-binding">74</td>
            <td class="ng-binding">46</td>
            <td class="ng-binding">28</td>
            <td class="ng-binding">.622</td>
            <td class="ng-binding">3,587</td>
            <td class="ng-binding">52.7</td>
            <td class="ng-binding">0.255</td>
            <td class="ng-binding">14.0</td>
            <td class="ng-binding">24.0</td>
            <td class="ng-binding">52.1</td>
            <td class="ng-binding">0.284</td>
            <td class="ng-binding">15.4</td>
            <td class="ng-binding">24.5</td>
                  </tr><!-- end ngRepeat: (i, row) in page track by row.$hash --><tr data-ng-repeat="(i, row) in page track by row.$hash" index="3" class="ng-scope" id=1>
            <td class="rank ng-binding"></td>
            <td class="team-name first sorted"><a href="/team/#!/1610612738/traditional/?" class="ng-binding">Boston Celtics</a></td>
            <td class="ng-binding">74</td>
            <td class="ng-binding">48</td>
            <td class="ng-binding">26</td>
            <td class="ng-binding">.649</td>
            <td class="ng-binding">3,567</td>
            <td class="ng-binding">52.4</td>
            <td class="ng-binding">0.269</td>
            <td class="ng-binding">13.4</td>
            <td class="ng-binding">21.3</td>
            <td class="ng-binding">50.4</td>
            <td class="ng-binding">0.289</td>
            <td class="ng-binding">14.1</td>
            <td class="ng-binding">25.0</td>
          </tr><!-- end ngRepeat: (i, row) in page track by row.$hash --><tr data-ng-repeat="(i, row) in page track by row.$hash" index="12" class="ng-scope">
            <td class="rank ng-binding"></td>
            <td class="team-name first sorted"><a href="/team/#!/1610612737/traditional/?" class="ng-binding">Atlanta Hawks</a></td>
            <td class="ng-binding">74</td>
            <td class="ng-binding">38</td>
            <td class="ng-binding">36</td>
            <td class="ng-binding">.514</td>
            <td class="ng-binding">3,587</td>
            <td class="ng-binding">50.3</td>
            <td class="ng-binding">0.297</td>
            <td class="ng-binding">15.6</td>
            <td class="ng-binding">23.6</td>
            <td class="ng-binding">50.8</td>
            <td class="ng-binding">0.233</td>
            <td class="ng-binding">15.3</td>
            <td class="ng-binding">24.1</td>
          </tr><!-- end ngRepeat: (i, row) in page track by row.$hash -->
        </tbody>
      </table>
  </div> <!-- .stat-table__overflow -->
</div>
<script>
document.getElementById('1')
document.write(document.getElementById('1'))
</script>
</html>
</code>```

答:
UPDATE 2

PLUNKER

UPDATE 1

✎ in Snippet's comments denotes the update.

Used the .map() method to iterate through each row (team), cell (stat column), and cell content (stat), Details are commented in Snippet.

SNIPPET 1

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">

TEAM
          GP
          W
          L
          WIN%
          MIN
          eFG%
          FTA
Rate
          TOV%
          OREB%
          Opp
eFG%
          Opp
FTA Rate
          Opp
TOV%
          Opp
OREB%

            Washington Wizards

          74
          46
          28
          .622
          3,587
          52.7
          0.255
          14.0
          24.0
          52.1
          0.284
          15.4
          24.5

            Boston Celtics

          74
          48
          26
          .649
          3,567
          52.4
          0.269
          13.4
          21.3
          50.4
          0.289
          14.1
          25.0

            Atlanta Hawks

          74
          38
          36
          .514
          3,587
          50.3
          0.297
          15.6
          23.6
          50.8
          0.233
          15.3
          24.1

```

Body:
I started last night so i'm a) sure there is an easy solution and b) not oblivious to the fact that my code is very crappy.
So i pulled this Stat table from a website and I already have a function running so that when I type a team name into the website it returns a number. However, what I'm trying to do is have it so that when i type a team name in it won't return a number, but rather it's respective row on the table. The numbers that are currently called in the function are just placeholders for now. As you can see i tried to call a row at the end of the function using an ID I assigned to the Celtics row but what it returns is [object HTMLTableRowElement].
Any help is appreciated, Thanks!!

<canvas id = 'gCanvas' width = '400' height = '600'></canvas>

TEAM
            GP
            W
            L
            WIN%
            MIN
            eFG%
            FTA
Rate
            TOV%
            OREB%
            Opp
eFG%
            Opp
FTA Rate
            Opp
TOV%
            Opp
OREB%
            GP RANK
            W RANK
            L RANK
            WIN% RANK
            MIN RANK
            eFG% RANK
            FTA
Rate RANK
            TO
Ratio RANK
            OREB% RANK
            Opp
eFG% RANK
            Opp
FTA Rate RANK
            Opp
To Ratio RANK
            Opp
OREB% RANK

            Washington Wizards
            74
            46
            28
            .622
            3,587
            52.7
            0.255
            14.0
            24.0
            52.1
            0.284
            15.4
            24.5

            Boston Celtics
            74
            48
            26
            .649
            3,567
            52.4
            0.269
            13.4
            21.3
            50.4
            0.289
            14.1
            25.0

            Atlanta Hawks
            74
            38
            36
            .514
            3,587
            50.3
            0.297
            15.6
            23.6
            50.8
            0.233
            15.3
            24.1

Body:
UPDATE 2

PLUNKER

UPDATE 1

✎ in Snippet's comments denotes the update.

Used the .map() method to iterate through each row (team), cell (stat column), and cell content (stat), Details are commented in Snippet.

SNIPPET 1

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
</head>

<body>
  <div class="nba-stat-table">
    <table class="table">
      <thead>
        <tr>
          <th></th>
          <th data-field="TEAM_NAME" class="text sorted desc"><br>TEAM</th>
          <th data-field="GP">GP</th>
          <th data-field="W">W</th>
          <th data-field="L">L</th>
          <th data-field="W_PCT" class="asc">WIN%</th>
          <th data-field="MIN">MIN</th>
          <th data-field="EFG_PCT">eFG%</th>
          <th data-field="FTA_RATE">FTA<br>Rate</th>
          <th data-field="TM_TOV_PCT">TOV%</th>
          <th data-field="OREB_PCT">OREB%</th>
          <th data-field="OPP_EFG_PCT">Opp<br>eFG%</th>
          <th data-field="OPP_FTA_RATE">Opp<br>FTA&nbsp;Rate</th>
          <th data-field="OPP_TOV_PCT">Opp<br>TOV%</th>
          <th data-field="OPP_OREB_PCT">Opp<br>OREB%</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="rank"></td>
          <td class="team-name first sorted">
            <a href="http://stats.nba.com/team/#!/1610612764/traditional/?">Washington Wizards</a>
          </td>
          <td>74</td>
          <td>46</td>
          <td>28</td>
          <td>.622</td>
          <td>3,587</td>
          <td>52.7</td>
          <td>0.255</td>
          <td>14.0</td>
          <td>24.0</td>
          <td>52.1</td>
          <td>0.284</td>
          <td>15.4</td>
          <td>24.5</td>
        </tr>
        <tr>
          <td class="rank"></td>
          <td class="team-name first sorted">
            <a href="http://stats.nba.com/team/#!/1610612738/traditional/?">Boston Celtics</a>
          </td>
          <td>74</td>
          <td>48</td>
          <td>26</td>
          <td>.649</td>
          <td>3,567</td>
          <td>52.4</td>
          <td>0.269</td>
          <td>13.4</td>
          <td>21.3</td>
          <td>50.4</td>
          <td>0.289</td>
          <td>14.1</td>
          <td>25.0</td>
        </tr>
        <tr>
          <td class="rank"></td>
          <td class="team-name first sorted">
            <a href="http://stats.nba.com/team/#!/1610612737/traditional/?">Atlanta Hawks</a>
          </td>
          <td>74</td>
          <td>38</td>
          <td>36</td>
          <td>.514</td>
          <td>3,587</td>
          <td>50.3</td>
          <td>0.297</td>
          <td>15.6</td>
          <td>23.6</td>
          <td>50.8</td>
          <td>0.233</td>
          <td>15.3</td>
          <td>24.1</td>
        </tr>
      </tbody>
    </table>
  </div>

  <script>
    // Reference the table ✎
    var T = document.querySelector('table');

    /* Collect the cells from the 1st row of T
    || then convert HTMLCollection into an array ✎
    */
    var cols = Array.from(T.rows[0].cells);

    /* map() passing cols array
    || returns the array of header titles ✎
    */
    var cats = cols.map(function(th, idx) {
      return th.textContent;
    });

    /* Collect all <tr> in <tbody> in a NodeList
    || Convert NodeList into an array
    */
    var rows = Array.from(document.querySelectorAll('tbody tr'));

    // Use the .map() method to...
    rows.map(function(tr, idx) {

      /* ...iterate through each <tr>
      || and collect it's <td> to a HTMLCollection
      || then convert it to an array
      */
      var cells = Array.from(tr.children);

      // Use the .map() method to...
      cells.map(function(td, idx) {

        // ...get the text from each <td>
        var stat = td.textContent;

        /* Log results ✎
        || The first part is a iteration
        || of the cats array which consists
        || of the text of each category
        || title in the column headers (<th>)
        */
        console.log(cats[idx] + ': ' + stat);

        // return results as a new array of stats
        return stat;
      });

    });
  </script>
</body>

</html>


问:
why can't I convert a field in sql server from not null to null
I have a db table that previously was not null (so every record had a value). I now want to make it nullable so its optional but it seems like SQL won't let you do this without deleting and recreating the table.

Why would it have this restriction if no data will be affected as I am going to a more lenient model (not a stricter one)?

答:
```<code>ALTER TABLE table_name ALTER COLUMN column_name data_type NULL
</code>```


问:
How can I catch an exception that occurs in Tasks when using Task.WhenAll()?
I tried putting the try catch around the Task.WhenAll(tasks) but it did not catch anything.  In one of my tasks I tried to artificially generate an exception by using Substring on an empty string.  But all that happens is the app crashes and defaults to Application_UnhandledException.</p>

```<code>    private async void RunTasks()
    {

        tasks[0] = HttpExtensions.GetMyData("http://www....");

        tasks[1] = HttpExtensions.GetMyData("http://www.....");

        tasks[2] = GeoLocate.OneShotGeoLocate();

        try
        {
            await Task.WhenAll(tasks);
        }
        catch (AggregateException ae)
        {

            App.ViewModel.ErrorMessage = ae.Message;

        }

 }
</code>```

答:
To get all exceptions thrown from execution of the tasks, use the following:

```<code>Task taskReturned = Task.WhenAll(taskArray);
try
{
    await taskReturned;
}
catch
{
    throw taskReturned.Exception;
}
</code>```

Body:
I tried putting the try catch around the Task.WhenAll(tasks) but it did not catch anything.  In one of my tasks I tried to artificially generate an exception by using Substring on an empty string.  But all that happens is the app crashes and defaults to Application_UnhandledException.

    private async void RunTasks()
    {

        tasks[0] = HttpExtensions.GetMyData("http://www....");

        tasks[1] = HttpExtensions.GetMyData("http://www.....");

        tasks[2] = GeoLocate.OneShotGeoLocate();

        try
        {
            await Task.WhenAll(tasks);
        }
        catch (AggregateException ae)
        {

            App.ViewModel.ErrorMessage = ae.Message;

        }

 }

Body:
To get all exceptions thrown from execution of the tasks, use the following:

Task taskReturned = Task.WhenAll(taskArray);
try
{
    await taskReturned;
}
catch
{
    throw taskReturned.Exception;
}


问:
How can I get result as 0 if IN() condition value not exist in the table
My table is:

```
s_no  user  join_year  knowledge handled_pojects_count
1     john     2017    PHP        5
2     john     2017    SQL        5
3     gokul    2017    JAVA       3
4     gokul    2017    PHP        2
5     hari     2017    ASP        1
6     hari     2017    Azure      9
```

Below one is my query

```<code>SELECT
COALESCE(SUM(handled_pojects_count),0) AS count,
knowledge
FROM team_members WHERE
join_year = '2017' AND
user = 'john' AND
knowledge IN ('PHP','JAVA');
</code>```

I need the result that should have both values for knowledge like below

```
    project count
    PHP     5
    JAVA    0
```

How can I arrive this?

答:
Can you try this?</p>

```<code>SELECT
knowledge,
SUM(CASE WHEN join_year = 2017 AND user = 'john' THEN ISNULL(handled_projects_count,0) ELSE 0 END) as cnt
FROM team_members WHERE
knowledge IN ('PHP','JAVA')
GROUP BY knowledge
</code>```

Body:
My table is:

s_no  user  join_year  knowledge handled_pojects_count
1     john     2017    PHP        5
2     john     2017    SQL        5
3     gokul    2017    JAVA       3
4     gokul    2017    PHP        2
5     hari     2017    ASP        1
6     hari     2017    Azure      9

Below one is my query

SELECT
COALESCE(SUM(handled_pojects_count),0) AS count,
knowledge
FROM team_members WHERE
join_year = '2017' AND
user = 'john' AND
knowledge IN ('PHP','JAVA');

I need the result that should have both values for knowledge like below

    project count
    PHP     5
    JAVA    0

How can I arrive this?

Body:
Can you try this?

SELECT
knowledge,
SUM(CASE WHEN join_year = 2017 AND user = 'john' THEN ISNULL(handled_projects_count,0) ELSE 0 END) as cnt
FROM team_members WHERE
knowledge IN ('PHP','JAVA')
GROUP BY knowledge


问:
"The installed Xamarin.iOS (version 10.3) on the Mac Unnamed Server (...) is not compatible with the local Xamarin.iOS (version 10.4)"
On my Windows box I have VS 2017, and on my Mac I have Xamarin Studio 6.2.

When I try to build an iOS project in Visual Studio on Windows, it complains that "The installed Xamarin.iOS (version 10.3) on the Mac Unnamed Server () is not compatible with the local Xamarin.iOS (version 10.4)".

However, in Help -> About in VS, it reports that the Xamarin.iOS is version 10.4.0.123. On the Mac, Xamarin Studio reports that I have version 10.4.0.128. Presumably, these should be compatible. I have tried to check for updates, as noted in other questions, but there are none available.

Any hints as to what is going on here?

答:
Those versions are not in fact compatible. Xamarin builds for VS 2017 are currently 1 build behind those for the Mac. I recommend downgrading your Mac Xamarin iOS Version to 10..4.0.123, which you can get from the your Xamarin account Downloads page:
https://store.xamarin.com/account/my/subscription/downloads#all-versions

Get the 10.4 version dated Feb 28th (or perhaps Mar 1 depending on your time zone) which is version 10.4.0.123 as installed in your VS 2017.

See this release note for more info:
https://releases.xamarin.com/category/xamarin-for-visual-studio/

and note this line in the above:

Do note that at the moment, Xamarin for Visual Studio 2017 is one build behind the version for Visual Studio 2015.

and thus is one build behind for Xamarin Studio on the Mac as well. So you can either downgrade your Mac to a matching version or go back to VS 2015.


问:
Getting apple-app-site-association, heroku, and Route 53 to play nice
My web app is hosted on heroku (Ruby on Rails). I use Amazon Route 53 for DNS. I have followed the Heroku docs for configuring Automated Certificate Management so my app can serve HTTPS. I have tested this through a web browser and I am able to access the site fine with HTTPS. I'm relatively certain that a) routing to heroku is working 2) https is working.

Here is where the difficult comes in. I am trying to get my app association file to work with my mobile app. I am able to pull up the file by going to my domain: https://www.example.com/apple-app-site-association.

My ruby app serves up the file in the manner suggested by this SO post:https://stackoverflow.com/a/35588346/5357940.

I have validated that the link is working without redirects with redirectcheck.com. This shows the content type is correct and that there are no redirects happening.

https://www.example.com/apple-app-site-association

HTTP/1.1 200 OK

Server: Cowboy

Connection: close

Date: Tue, 28 Mar 2017 23:29:50 GMT

Status: 200 OK

X-Frame-Options: SAMEORIGIN

X-Xss-Protection: 1; mode=block

X-Content-Type-Options: nosniff

Cache-Control: no-cache

Content-Type: application/json; charset=utf-8

X-Request-Id: 21fd0610-2797-4c83-81ec-d54616086036

X-Runtime: 0.184758

Via: 1.1 vegur

When I run the apple validator, all the tests pass except for the "Link To Application" test. The error returned is:

App Name Domain
Link http://www.example.com/testlink

Bundle Id com.example.app

Universal false

Error cannot fetch app site association

I have read through all the other SO question on this topic, but can't find one that addresses the specific problem I am having.

p.s. I have replaced the name of the app with domain.

答: After much futzing, I found that everything was actually working despite apple's validation tool telling me otherwise. Since I did not have my app with the appropriate site applinks registered, I could not test in the app. It appears this is because Apple's validator apparently caches site association files. Even though I was changing my site file, apple kept saying it was not readable when in fact it was. </p>


问:
Need Help in send news letter using PHP mail function
Need your help in over coming the following issues.

i need to send opt-in newsletters to the user. But using "gmail SMTP", i will not be able to send more than 400 mails per day.

Even if i use the mail option given in the shared server, i will not be able to send mails more than 300 mails per day.

Can you please suggest any other way i can handle this issue. Is it possible to use PHP mail functions? are there any limitations in sending the number of mails to the users.

can a server control the mails sent using PHP mail function.

Thanks for reading.

thanks a lot

答: Use an smtp relay service. I've had good experiences with smtp.com in the past (I'm not affiliated with them in any way). You can grab a library to connect to it and get going relatively fast.</p>


问:
Accessing VideoJS Played TimeRanges
I'm building a web app using ReactJS that will allow employees to view various video training sessions and then answer quiz questions about them. I would like to use HTML5 video elements to maximize compatibility across devices, but users can always just scrub through the video to get to the end and trigger the next operation in the app. It is necessary for them to watch the entire video before moving on.

I need a way to tell if the whole video has been played before allowing the user to move on. I was looking at the Video JS Advanced Examples page, and I found exactly what I was looking for. They have a 'played' data field that updates with what time ranges the user has played through. The problem is that I have no idea of how to implement that feature in my app. I can include and get VideoJS up and running just fine, but I don't know how to access the 'played' property of the video player.

If anyone could give me a direction to go in, I would really appreciate it. If this is a stupid question, I'm really sorry. I'm still fairly new to all of this. Thank you so much.

Cheers,

Jaydon

答:
played comes form the html5 media spec. It returns a TimeRanges object.
Video.js provides most of the functionality of the native video element via methods. So, the played property on the video element (as vidEl.played) becomes a method call on the Video.js's player object (as player.played()).

The API to time ranges is a bit weird. But essentially, it has a three properties: length, start, and end.
This is what they do:
* length: how many ranges are there? In the case of played, how many different sections of the video have been played?
* start(): a method that tells you the start time of a given range
* end(): a method that tells you the end time of a given range

It's likely that you will only have one range, but it's possible you'll have more. So, you'll want to loop over the length of the ranges. To know exactly how much the user as played, you'll basically want to loop over each range and calculate it's duration (end(i) - start(i) and then compare it to the duration of the video (player.duration()). If they are close, that means that the user has watched the entire video.

Title: Accessing VideoJS Played TimeRanges


问:
Xamarin form display alert pop up appear 2 times
i have created Xamarin pcl form project and ask confirmation when user press the logout button, its working fine both android and iOS but at the same i run as windows UWP project the pop up appears 2 time, i don't what happen. Please guide me some one how can i fix this issues.

i mentioned my code below what i used in my project.

I have used both option with await and without await keyword but no luck.

```<code>var resp = await DisplayAlert("","Are you sure want to Logout?","Yes", "No");
if (resp)
{
}
</code>```

答:
Maybe the user is pressing the button to fast 2 times, I suggest you add a flag, something like this:

```<code>bool displayFlag = false;
if(!displayFlag)
{
    displayFlag = true;
   var resp = await DisplayAlert("","Are you sure want to Logout?","Yes", "No");
   if(resp)
   {
        //Logout
   }
   displayFlag = false;
}
</code>```

Or Maybe the Alert message is inside another Task (Just imaging) so Maybe this can help:

```<code>Device.BeginInvokeOnMainthread( () => async
{
    await DisplayAlert("","Are you sure want to Logout?","Yes", "No");
});
</code>```

Body:
i have created Xamarin pcl form project and ask confirmation when user press the logout button, its working fine both android and iOS but at the same i run as windows UWP project the pop up appears 2 time, i don't what happen. Please guide me some one how can i fix this issues.

i mentioned my code below what i used in my project.

I have used both option with await and without await keyword but no luck.

var resp = await DisplayAlert("","Are you sure want to Logout?","Yes", "No");
if (resp)
{
}

Body:
Maybe the user is pressing the button to fast 2 times, I suggest you add a flag, something like this:

bool displayFlag = false;
if(!displayFlag)
{
    displayFlag = true;
   var resp = await DisplayAlert("","Are you sure want to Logout?","Yes", "No");
   if(resp)
   {
        //Logout
   }
   displayFlag = false;
}

Or Maybe the Alert message is inside another Task (Just imaging) so Maybe this can help:

Device.BeginInvokeOnMainthread( () => async
{
    await DisplayAlert("","Are you sure want to Logout?","Yes", "No");
});


问:
Why is my search query returning undefined, while my page populates with the term's results? Using business catalyst
I'm trying to get the search term to appear in the URL. What am I doing wrong?  </p>

```<code><form name="catsearchform74255" method="post" onsubmit="processSearch(this)" action="/Default.aspx?SiteSearchID=2248&ID=/search-results&keywords=">
        <div class="input-field search-box">
            <input id="CAT_Search" type="search" name="CAT_Search" placeholder="What are you looking for?" class="white" required="true">
            <label class="label-icon" for="CAT_Search"><i class="material-icons">search</i></label>
            <i class="material-icons">close</i>
        </div>
         <script type="text/javascript">
        function processSearch(form) {
            form.action = form.action + CAT_Search.value;
        }
    </script>
    </form>
</code>```

答:
Change method="post" to method="get".

Update any server-side code referencing post variables to reference get variables. For example, in PHP code, change $_POST["CAT_Search"] to $_GET["CAT_Search"].

Also, the correct format for the required HTML attribute is either required="" or required="required.

Body:
I'm trying to get the search term to appear in the URL. What am I doing wrong?

<form name="catsearchform74255" method="post" onsubmit="processSearch(this)" action="/Default.aspx?SiteSearchID=2248&ID=/search-results&keywords=">

            <input id="CAT_Search" type="search" name="CAT_Search" placeholder="What are you looking for?" class="white" required="true">
            search
            close

    </form>


问:
Grunt - mongoimpot --headerlines?
I am trying to upload a CSV file using the mongoimport plugin for grunt. I am receiving the following error when running grunt:

```<code>Running "mongoimport" task
2017-03-29T18:43:57.463-0700    error validating settings: must specify --fields, --fieldFile or --headerline to import th
is file type
2017-03-29T18:43:57.464-0700    try 'mongoimport --help' for more information
</code>```

The error message is pretty obvious so I adjusted my grunt task to include headerline: true

This doesn't appear to be correct as the error remains the same. After looking at their documentation for any mentioning of the --headerline property, the only thing I see is this:

collection.fields

Specify a comma separated list of field names when importing csv or tsv files that do not have field names in the first (i.e. header) line of the file.
- https://github.com/andrewkeig/grunt-mongoimport

What is the correct way using grunt to import mongodb data from a csv?

gruntfile.ts

```<code>module.exports = (grunt) => {

  grunt.initConfig({

    mongoimport: {
      options: {
        db: 'mynewdatabase',
        collections: [
          {
            name: 'somethings',
            type: 'csv',
            file: 'data/test.csv',
            headerline: true // <----does not work
          }
        ]
      }
    }

  });

  //Load Plugins
  grunt.loadNpmTasks('grunt-mongoimport');

  //Run Tasks
  grunt.registerTask('default', ['mongoimport']);

}
</code>```

The csv file does have headlines and if I run the below mongo command in a terminal, it works fine:

```<code>use mynewdatabase
mongoimport --db mynewdatabase --collection somethings --type csv --headerline --file test.csv
</code>```

Looking at the mongimport source code, they have the following logic:

```<code>if (collection.type === 'csv' || collection.type === 'tsv') {
        if (collection.headerLine) args.push('--headerline');
    }
</code>```

If i'm passing the type of csv then it looks like --hearline should be getting added already so the error message doesn't seem to be aligning with what i'm seeing the code/task...

答:
I was looking over the documentation. In their source code they have the following

```<code>if (collection.type === 'csv' || collection.type === 'tsv') {
        if (collection.headerLine) args.push('--headerline');
}
</code>```

This means if you pass headerLine: true and your type: 'csv' then you mongoimport will include the --headerline

```<code>module.exports = (grunt) => {

  grunt.initConfig({

    mongoimport: {
      options: {
        db: 'mynewdatabase',
        collections: [
          {
            name: 'somethings',
            type: 'csv',
            file: 'data/test.csv',
            headerLine: true // <----works
          }
        ]
      }
    }

  });

  //Load Plugins
  grunt.loadNpmTasks('grunt-mongoimport');

  //Run Tasks
  grunt.registerTask('default', ['mongoimport']);

}
</code>```

Title: Grunt - mongoimpot --headerlines?

Body:
I am trying to upload a CSV file using the mongoimport plugin for grunt. I am receiving the following error when running grunt:

Running "mongoimport" task
2017-03-29T18:43:57.463-0700    error validating settings: must specify --fields, --fieldFile or --headerline to import th
is file type
2017-03-29T18:43:57.464-0700    try 'mongoimport --help' for more information

The error message is pretty obvious so I adjusted my grunt task to include headerline: true

This doesn't appear to be correct as the error remains the same. After looking at their documentation for any mentioning of the --headerline property, the only thing I see is this:

collection.fields

Specify a comma separated list of field names when importing csv or tsv files that do not have field names in the first (i.e. header) line of the file.
- https://github.com/andrewkeig/grunt-mongoimport

What is the correct way using grunt to import mongodb data from a csv?

gruntfile.ts

module.exports = (grunt) => {

  grunt.initConfig({

    mongoimport: {
      options: {
        db: 'mynewdatabase',
        collections: [
          {
            name: 'somethings',
            type: 'csv',
            file: 'data/test.csv',
            headerline: true // <----does not work
          }
        ]
      }
    }

  });

  //Load Plugins
  grunt.loadNpmTasks('grunt-mongoimport');

  //Run Tasks
  grunt.registerTask('default', ['mongoimport']);

}

The csv file does have headlines and if I run the below mongo command in a terminal, it works fine:

use mynewdatabase
mongoimport --db mynewdatabase --collection somethings --type csv --headerline --file test.csv

Looking at the mongimport source code, they have the following logic:

if (collection.type === 'csv' || collection.type === 'tsv') {
        if (collection.headerLine) args.push('--headerline');
    }

If i'm passing the type of csv then it looks like --hearline should be getting added already so the error message doesn't seem to be aligning with what i'm seeing the code/task...

Body:
I was looking over the documentation. In their source code they have the following

if (collection.type === 'csv' || collection.type === 'tsv') {
        if (collection.headerLine) args.push('--headerline');
}

This means if you pass headerLine: true and your type: 'csv' then you mongoimport will include the --headerline

module.exports = (grunt) => {

  grunt.initConfig({

    mongoimport: {
      options: {
        db: 'mynewdatabase',
        collections: [
          {
            name: 'somethings',
            type: 'csv',
            file: 'data/test.csv',
            headerLine: true // <----works
          }
        ]
      }
    }

  });

  //Load Plugins
  grunt.loadNpmTasks('grunt-mongoimport');

  //Run Tasks
  grunt.registerTask('default', ['mongoimport']);

}


问:
Playing Sound in C++
I need to play sound in C++.
It should be compatible across all platforms.

Thanks,

goerdy

答:
My suggestion is to go with OpenAl (3D cross platform Audio API)

It's fairly easy to learn and meant to have a similar flow of programming as OpenGl.  It's free and has different extensions to take advantage of sound cards.  OpenAl has a library akin to OpenGl's Utility Toolkit (GLUT) that's called freealut.  It makes things even simpler.

This might be a good place to get started:
http://www.devmaster.net/articles/openal/

Some of the functions in that code are deprecated but reading the documentation, you'll be able to update it.

The devmaster tutorial also teaches you how to load ogg vorbis (royalty free) files into memory and play them.  You'll need to download and build libvorbis and libogg to do that but there's good documentation and, in case you're using Visual Studio, already made solutions.

The fact that Creative Labs (largest sound card manufacturer) is a major contributor to the project is a great point in it's favor.  Hardware will not be ignored.

Last thing, remember to download the OpenAl SDK and link to the proper libraries and include directories.  There's always a lot of people asking for specific files stored inside it.

Title: Playing Sound in C++


问:
How using with istringstream in c++?
I look for function to split whitespace in c++. i find this code on internet. i want to know what is says.</p>

```<code>  string line;
  istringstream buf(line);
  istream_iterator<string> beg(buf), end;
  vector<string> tokens(beg, end);
  return tokens;
</code>```

答:
See:

```<code>#include <iostream>
#include <sstream>
#include <vector>
#include <iterator>

std::vector<std::string> SplitByWhiteSpace(std::string stringToSplit)
{
    std::istringstream buf(stringToSplit);
    std::istream_iterator<std::string> beg(buf), end;
    return std::vector<std::string>(beg, end);
}

int main() {
    std::vector<std::string> tokens = SplitByWhiteSpace("Hello World!");

    for (std::size_t i = 0; i < tokens.size(); ++i)
    {
        std::cout<<tokens[i]<<"\n";
    }

    return 0;
}
</code>```

That code splits the string by white-space and returns all tokens in a vector. You can then print all the tokens in the vector.

It is almost the same as doing (same result, different technique):

```<code>std::vector<std::string> SplitByWhiteSpace(std::string stringToSplit)
{
    std::string word;
    std::vector<std::string> tokens;
    std::istringstream buf(stringToSplit);

    while (buf >> word)
    {
        tokens.push_back(word);
    }

    return tokens;
}
</code>```

Title: How using with istringstream in c++?

Body:
I look for function to split whitespace in c++. i find this code on internet. i want to know what is says.

  string line;
  istringstream buf(line);
  istream_iterator<string> beg(buf), end;
  vector<string> tokens(beg, end);
  return tokens;

Body:
See:

#include <iostream>
#include <sstream>
#include <vector>
#include <iterator>

std::vector<std::string> SplitByWhiteSpace(std::string stringToSplit)
{
    std::istringstream buf(stringToSplit);
    std::istream_iterator<std::string> beg(buf), end;
    return std::vector<std::string>(beg, end);
}

int main() {
    std::vector<std::string> tokens = SplitByWhiteSpace("Hello World!");

    for (std::size_t i = 0; i < tokens.size(); ++i)
    {
        std::cout<<tokens[i]<<"\n";
    }

    return 0;
}

That code splits the string by white-space and returns all tokens in a vector. You can then print all the tokens in the vector.

It is almost the same as doing (same result, different technique):

std::vector<std::string> SplitByWhiteSpace(std::string stringToSplit)
{
    std::string word;
    std::vector<std::string> tokens;
    std::istringstream buf(stringToSplit);

    while (buf >> word)
    {
        tokens.push_back(word);
    }

    return tokens;
}


问:
VSTS use on premise deployment agent
I ran out of release/build minutes on VSTS, therefore I configured an on premise agent to run my builds. This is working fine, however I cannot select that agent to be used for deploying my releases.

I tried to follow the following tutorial, however it seems like it is a bit old:

http://vsts-deploy-guide.readthedocs.io/en/latest/

Does anyone have experience setting up on premise agents to do the deployment?

答:
Refer to these steps:

Open release definition

Select Environments tab

Click Run on agent

Change Deployment queue in right panel.

Title: VSTS use on premise deployment agent


问:
Bootstrap 3, full width for nav-pills regarding to its container
I have a following trouble.

Let's assume I have a container and its width is 950px. There's a nav-pills element in this container, but it has margins on left and right side, but I need to remove these margins to keep this element's width 100% regarding to original container which width is as I said before 950px. My code looks like this:

```<code><div class="container">
    <ul id="mytabs" class="nav nav-pills nav-justified" role="tablist">
        <li><a href="/link" role="tab" data-toggle="tab">link1</a></li>
        <li class="active"><a href="/link2" role="tab" data-toggle="tab">link2</a></li>
        <li><a href="/link3" role="tab" data-toggle="tab">link3</a></li>
        <li><a href="/link4" role="tab" data-toggle="tab">link4</a></li>
    </ul>
</div>
</code>```

And css for .container:

```<code>.container {
    width: 950px;
}
</code>```

So far I tried many ways to accomplish it, for example giving width: 100% to pills, but still no luck. Here's a jsfiddle to give you a better understanding of my problem.

答:
I think, your mean like this : https://jsfiddle.net/z3d9984p/2/

so I remove padding to get 100% of width

```<code>.container {
  width: 950px !important;
  padding-right:0;
  padding-left:0
}
</code>```

Body:
I have a following trouble.

Let's assume I have a container and its width is 950px. There's a nav-pills element in this container, but it has margins on left and right side, but I need to remove these margins to keep this element's width 100% regarding to original container which width is as I said before 950px. My code looks like this:

link1

link2

link3

link4

And css for .container:

.container {
    width: 950px;
}

So far I tried many ways to accomplish it, for example giving width: 100% to pills, but still no luck. Here's a jsfiddle to give you a better understanding of my problem.

Body:
I think, your mean like this : https://jsfiddle.net/z3d9984p/2/

so I remove padding to get 100% of width

.container {
  width: 950px !important;
  padding-right:0;
  padding-left:0
}


问:
Google Cloud Endpoints - Method does not exist - OpenAPI yaml specification
I'm trying to setup a NodeJS REST API using Google Cloud Endpoints and Google App Engine. I've cloned the offical sample project from GitHub and set up Google Cloud Endpoints using the Quickstart. Out of the box, it works fine,but I tried adding another API endpoint for a GET request at /, but the response I get after I deploy and make the request is as follows:

```<code>{
 "code": 5,
 "message": "Method does not exist.",
 "details": [
  {
   "@type": "type.googleapis.com/google.rpc.DebugInfo",
   "stackEntries": [],
   "detail": "service_control"
  }
 ]
}
</code>```

The APIs which came pre-configured works fine, but only new ones which I add aren't working.

I've configured the new endpoint properly in my NodeJS app (it works fine locally). The corresponding code I've added is:

```<code>app.get('/', function (req, res) {
  res.status(200).json({ message: 'Hello, world!' });
});
</code>```

I've added the following to my openapi.yaml file:

```<code>paths:
  "/":
    get:
      description: "Returns the message \"Hello, World\""
      operationId: "root"
      produces:
      - "application/json"
      responses:
        200:
          description: "Hello"
          schema:
            $ref: "#/definitions/helloMessage"
definitions:
  helloMessage:
    properties:
      message:
        type: "string"
</code>```

After running gcloud service-management deploy openapi.yaml from a terminal to deploy and configure Google Cloud Endpoints, I got the service name and the service configuration ID, which I've replaced in app.yaml, in the format specified by the QuickStart

```<code>endpoints_api_service:
  name: echo-api.endpoints.[YOUR-PROJECT-ID].cloud.goog
  config_id: YOUR-CONFIG-ID
</code>```

(That's the format, I've replaced YOUR-PROJECT-ID and YOUR-CONFIG-ID with the right ones)

I deployed the app to Google App Engine using gcloud app deploy. I can see the app running properly, via the Google App Engine console.

Yet, the GET method on / is not being identified as a valid endpoint and I get the response as stated above.

Am I missing something? I searched a lot about this problem, but didn't come across anything useful/similar!

P.S: By added, I mean, it is the code which I've added to the corresponding GitHub cloned files

EDIT:
I changed the API endpoint from / to /hello and it works fine!! Unable to understand why the same functionality on / is not working on Google Cloud Endpoints (works locally though!)

答: Google Cloud Endpoints does not currently support the root path at "/". This is something that is being looked into.</p>

Body:
I'm trying to setup a NodeJS REST API using Google Cloud Endpoints and Google App Engine. I've cloned the offical sample project from GitHub and set up Google Cloud Endpoints using the Quickstart. Out of the box, it works fine,but I tried adding another API endpoint for a GET request at /, but the response I get after I deploy and make the request is as follows:

{
 "code": 5,
 "message": "Method does not exist.",
 "details": [
  {
   "@type": "type.googleapis.com/google.rpc.DebugInfo",
   "stackEntries": [],
   "detail": "service_control"
  }
 ]
}

The APIs which came pre-configured works fine, but only new ones which I add aren't working.

I've configured the new endpoint properly in my NodeJS app (it works fine locally). The corresponding code I've added is:

app.get('/', function (req, res) {
  res.status(200).json({ message: 'Hello, world!' });
});

I've added the following to my openapi.yaml file:

paths:
  "/":
    get:
      description: "Returns the message \"Hello, World\""
      operationId: "root"
      produces:
      - "application/json"
      responses:
        200:
          description: "Hello"
          schema:
            $ref: "#/definitions/helloMessage"
definitions:
  helloMessage:
    properties:
      message:
        type: "string"

After running gcloud service-management deploy openapi.yaml from a terminal to deploy and configure Google Cloud Endpoints, I got the service name and the service configuration ID, which I've replaced in app.yaml, in the format specified by the QuickStart

endpoints_api_service:
  name: echo-api.endpoints.[YOUR-PROJECT-ID].cloud.goog
  config_id: YOUR-CONFIG-ID

(That's the format, I've replaced YOUR-PROJECT-ID and YOUR-CONFIG-ID with the right ones)

I deployed the app to Google App Engine using gcloud app deploy. I can see the app running properly, via the Google App Engine console.

Yet, the GET method on / is not being identified as a valid endpoint and I get the response as stated above.

Am I missing something? I searched a lot about this problem, but didn't come across anything useful/similar!

P.S: By added, I mean, it is the code which I've added to the corresponding GitHub cloned files

EDIT:
I changed the API endpoint from / to /hello and it works fine!! Unable to understand why the same functionality on / is not working on Google Cloud Endpoints (works locally though!)


问:
How to check if the multipart upload was successful with alamofire image
I am making a network call to upload an image to a backend server. Right now I am using the following to code. This code works perfectly in conditions where the internet is online.

```<code>// MARK: - PUT

    static func PUT(URL: String,
                    data: Data,
                    mimeType: String,
                    headers: [String: String]?) -> Promise<Void>
    {
        return Promise { fulfill, reject in

            let URL = try! URLRequest(url: URL, method: .put, headers: headers)

            Alamofire.upload(
                multipartFormData: { multipartFormData in

                    multipartFormData.append(InputStream.init(data: data), withLength: UInt64(data.count), name: "image", fileName: "file.png", mimeType: mimeType)
            },
            with: URL,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                    case .success(let upload, _, _):
                    upload.responseJSON { response in

                        if response.result.value == nil {
                            fulfill()
                        }else {
                            reject(response.result.error!)
                        }
                    }
                    case .failure( _):
                    break
                }
            })
        }
    }
}
</code>```

In case I put it on offline mode. It'll still execute the function and still fullfills() the promise. Even tho the network is offline. I think this is because it's checking if the encodingResult is succesful or not. NOt for the network call itself.

How am I able to check if the network call was successful or not? It's returning Void.

Import notes:

Server returns nill if we receive 200 code which means that have uploaded the image.

答:
If you're going to use status codes to determine success or failure, you should add validate:

For example:

```<code>static func PUT(URL: String,
                data: Data,
                mimeType: String,
                headers: [String: String]?) -> Promise<Void> {
    return Promise { fulfill, reject in

        let URL = try! URLRequest(url: URL, method: .put, headers: headers)

        Alamofire.upload(
            multipartFormData: { multipartFormData in
                multipartFormData.append(data, withName: "image", fileName: "file.png", mimeType: mimeType)
        }, with: URL) { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload
                    .validate(statusCode: 200 ..< 300)
                    .responseJSON { response in
                        switch response.result {
                        case .success:
                            fulfill()
                        case .failure(let error):
                            reject(error)
                        }
                }
            case .failure(let error):
                reject(error)
            }
        }
    }
}
</code>```

The above assumes that upon successful response, you'll also get JSON response. You might want to do some additional checking of value.

If you're not returning JSON upon success, then just use response, not responseJSON:

```<code>static func PUT(URL: String,
                data: Data,
                mimeType: String,
                headers: [String: String]?) -> Promise<Void> {
    return Promise { fulfill, reject in
        let URL = try! URLRequest(url: URL, method: .put, headers: headers)

        Alamofire.upload(
            multipartFormData: { multipartFormData in
                multipartFormData.append(data, withName: "image", fileName: "file.png", mimeType: mimeType)
        }, with: URL) { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload
                    .validate(statusCode: 200 ..< 300)
                    .response { response in
                        if let error = response.error {
                            reject(error)
                        } else {
                            fulfill()
                        }
                }
            case .failure(let error):
                reject(error)
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am making a network call to upload an image to a backend server. Right now I am using the following to code. This code works perfectly in conditions where the internet is online.

// MARK: - PUT

    static func PUT(URL: String,
                    data: Data,
                    mimeType: String,
                    headers: [String: String]?) -> Promise<Void>
    {
        return Promise { fulfill, reject in

            let URL = try! URLRequest(url: URL, method: .put, headers: headers)

            Alamofire.upload(
                multipartFormData: { multipartFormData in

                    multipartFormData.append(InputStream.init(data: data), withLength: UInt64(data.count), name: "image", fileName: "file.png", mimeType: mimeType)
            },
            with: URL,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                    case .success(let upload, _, _):
                    upload.responseJSON { response in

                        if response.result.value == nil {
                            fulfill()
                        }else {
                            reject(response.result.error!)
                        }
                    }
                    case .failure( _):
                    break
                }
            })
        }
    }
}

In case I put it on offline mode. It'll still execute the function and still fullfills() the promise. Even tho the network is offline. I think this is because it's checking if the encodingResult is succesful or not. NOt for the network call itself.

How am I able to check if the network call was successful or not? It's returning Void.

Import notes:

Server returns nill if we receive 200 code which means that have uploaded the image.

Body:
If you're going to use status codes to determine success or failure, you should add validate:

For example:

static func PUT(URL: String,
                data: Data,
                mimeType: String,
                headers: [String: String]?) -> Promise<Void> {
    return Promise { fulfill, reject in

        let URL = try! URLRequest(url: URL, method: .put, headers: headers)

        Alamofire.upload(
            multipartFormData: { multipartFormData in
                multipartFormData.append(data, withName: "image", fileName: "file.png", mimeType: mimeType)
        }, with: URL) { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload
                    .validate(statusCode: 200 ..< 300)
                    .responseJSON { response in
                        switch response.result {
                        case .success:
                            fulfill()
                        case .failure(let error):
                            reject(error)
                        }
                }
            case .failure(let error):
                reject(error)
            }
        }
    }
}

The above assumes that upon successful response, you'll also get JSON response. You might want to do some additional checking of value.

If you're not returning JSON upon success, then just use response, not responseJSON:

static func PUT(URL: String,
                data: Data,
                mimeType: String,
                headers: [String: String]?) -> Promise<Void> {
    return Promise { fulfill, reject in
        let URL = try! URLRequest(url: URL, method: .put, headers: headers)

        Alamofire.upload(
            multipartFormData: { multipartFormData in
                multipartFormData.append(data, withName: "image", fileName: "file.png", mimeType: mimeType)
        }, with: URL) { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload
                    .validate(statusCode: 200 ..< 300)
                    .response { response in
                        if let error = response.error {
                            reject(error)
                        } else {
                            fulfill()
                        }
                }
            case .failure(let error):
                reject(error)
            }
        }
    }
}


问:
My AutoNumber Code Does Not Work
Can anyone help me here? I am trying to do a user defined autonumber when I click on a button. The code worked fine when the recordset is empty, it give me a 1 on my first record, however, after I click on the button again, it give me 1 again. Here's my code.

```<code>Private Sub BtnNew_Click()
    Dim rsClone As Recordset
    Dim pVal As Integer

    Set rsClone = Me.RecordsetClone

    If Not (rsClone.BOF) Then
        DoCmd.GoToRecord , , acNewRec
        rsClone.MoveLast
        pVal = rsClone.AbsolutePosition + 2
        Me.CatgId.Value = pVal
        Me.CatgId.SetFocus
    Else
        rsClone.AddNew
        Me.CatgId.Value = 1
        Me.CatgId.SetFocus
    End If
End Sub
</code>```

Thanks for the help.

答: I'm guessing that this is for a web page.  If that's the case, every time your page handles any event, you're working with an entirely new instance of the page's type.  That is, you're "Me" reference in that code points to a different object every time the function is called.</p>

Title: My AutoNumber Code Does Not Work

Body:
Can anyone help me here? I am trying to do a user defined autonumber when I click on a button. The code worked fine when the recordset is empty, it give me a 1 on my first record, however, after I click on the button again, it give me 1 again. Here's my code.

Private Sub BtnNew_Click()
    Dim rsClone As Recordset
    Dim pVal As Integer

    Set rsClone = Me.RecordsetClone

    If Not (rsClone.BOF) Then
        DoCmd.GoToRecord , , acNewRec
        rsClone.MoveLast
        pVal = rsClone.AbsolutePosition + 2
        Me.CatgId.Value = pVal
        Me.CatgId.SetFocus
    Else
        rsClone.AddNew
        Me.CatgId.Value = 1
        Me.CatgId.SetFocus
    End If
End Sub

Thanks for the help.


问:
WIndows 10 UWP - How can I determine if a Key press is a letter or number?
Windows 10 UWP: Example: On UWP grid, a button1.content = 1 and a textbox. Using mouse to press button1.content, 1 is shown in the textbox.text.
How to simulate numeric keypad (1) and 1 is shown in the textbox.text?</p>

答:
You can use TextBlock.Text to set the text to TextBlock.

If you want to know the key press, you should add KeyDown in Grid

```<code><Grid KeyDown="Grid_OnKeyDown"></Grid>
</code>```

And add the following code

```<code>private void Grid_OnKeyDown(object sender, KeyEventArgs e)
{
    var str = e.Key.ToString();
    if (char.IsDigit(str[0]))
    {
        //is digit
    }
    // is letter
}
</code>```

You can use TextBlock.Text = xx to set the TextBlock.

Body:
You can use TextBlock.Text to set the text to TextBlock.

If you want to know the key press, you should add KeyDown in Grid

<Grid KeyDown="Grid_OnKeyDown"></Grid>

And add the following code

private void Grid_OnKeyDown(object sender, KeyEventArgs e)
{
    var str = e.Key.ToString();
    if (char.IsDigit(str[0]))
    {
        //is digit
    }
    // is letter
}

You can use TextBlock.Text = xx to set the TextBlock.