问:
Build CNN Model Using Keras
Hello I am new comer in Keras. I choose keras to Implement this paper : http://mmlab.ie.cuhk.edu.hk/projects/TCDCN.html . I just change the input size to 48x48 then for the output I just need the 68 landmark coordinate. Here is my network:

```<code>def mtfl40New(size):
    model = Sequential()
    model.add(Conv2D(16, (5, 5), padding='valid', input_shape=(3, size, size)))
    model.add(Activation('tanh'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(48, (3, 3), padding='valid'))
    model.add(Activation('tanh'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(64, (3, 3), padding='valid'))
    model.add(Activation('tanh'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(64, (2, 2), padding='valid'))
    model.add(Activation('tanh'))

    model.add(Flatten())
    model.summary()
    #model.count_params()
    model.add(Dense(100, kernel_initializer="normal", input_shape=(576,)))
    model.add(Activation('tanh'))
    model.add(Dense(136, kernel_initializer="normal"))
    model.add(Activation('tanh'))

    model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])
    return model
</code>```

However I get this error :

Anyone can help?
-Thank you-

答:
This is again an incompatibility between your input shape and the format how it is interpreted. You have set in your Keras configuration the image ordering to channels first, while the input shape has the channels at the end. To fix it simply replace this line:

```<code>model.add(Conv2D(16, (5, 5), padding='valid', input_shape=(3, size, size)))
</code>```

With:

```<code>model.add(Conv2D(16, (5, 5), padding='valid', input_shape=(size, size, 3)))
</code>```

Title: Build CNN Model Using Keras

Body:
Hello I am new comer in Keras. I choose keras to Implement this paper : http://mmlab.ie.cuhk.edu.hk/projects/TCDCN.html . I just change the input size to 48x48 then for the output I just need the 68 landmark coordinate. Here is my network:

def mtfl40New(size):
    model = Sequential()
    model.add(Conv2D(16, (5, 5), padding='valid', input_shape=(3, size, size)))
    model.add(Activation('tanh'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(48, (3, 3), padding='valid'))
    model.add(Activation('tanh'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(64, (3, 3), padding='valid'))
    model.add(Activation('tanh'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(64, (2, 2), padding='valid'))
    model.add(Activation('tanh'))

    model.add(Flatten())
    model.summary()
    #model.count_params()
    model.add(Dense(100, kernel_initializer="normal", input_shape=(576,)))
    model.add(Activation('tanh'))
    model.add(Dense(136, kernel_initializer="normal"))
    model.add(Activation('tanh'))

    model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])
    return model

However I get this error :

Anyone can help?
-Thank you-

Body:
This is again an incompatibility between your input shape and the format how it is interpreted. You have set in your Keras configuration the image ordering to channels first, while the input shape has the channels at the end. To fix it simply replace this line:

model.add(Conv2D(16, (5, 5), padding='valid', input_shape=(3, size, size)))

With:

model.add(Conv2D(16, (5, 5), padding='valid', input_shape=(size, size, 3)))


来源: stackexchange

问:
how to use xpath to get all the value conform to requirement from a designated web site
there is a website,link:view-source:https://www.zhihu.com/people/weizhi-xiazhi/followers.
and when i use

```<code>import url
from scrapy.selector import Selector
url = 'https://www.zhihu.com/people/weizhi-xiazhi/followers'
content = urllib.request.urlopen(url).read()
content = content.decode('utf-8')
Selector(text=content).xpath('' // div[ @class ="ContentItem-head"] // a[@ class ="UserLink-link" and @ target="_blank"]'').extract()[0]
</code>```

to extract the information,there only have a list of 3 element ,which is supposed to have more than 3 element. i wonder why.thanks in advance!

答:
The website is loading more followers from javascript after the first query, you could look into selenium for rendering javascript, something like this if you are using phatomJS:

```<code>from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get('https://www.zhihu.com/people/weizhi-xiazhi/followers')
driver.implicitly_wait(10) #wait some time to load
elements = driver.find_elements_by_xpath('//*[@class="UserItem-title"]/descendant::a')
for e in elements:
    print(e.get_attribute("href"))
</code>```

Note that I opted for a less "restrictive" expression so that it is less sensible to small website changes.

ContentLicense: CC BY-SA 3.0

Body:
there is a website,link:view-source:https://www.zhihu.com/people/weizhi-xiazhi/followers.
and when i use

import url
from scrapy.selector import Selector
url = 'https://www.zhihu.com/people/weizhi-xiazhi/followers'
content = urllib.request.urlopen(url).read()
content = content.decode('utf-8')
Selector(text=content).xpath('' // div[ @class ="ContentItem-head"] // a[@ class ="UserLink-link" and @ target="_blank"]'').extract()[0]

to extract the information,there only have a list of 3 element ,which is supposed to have more than 3 element. i wonder why.thanks in advance!

Body:
The website is loading more followers from javascript after the first query, you could look into selenium for rendering javascript, something like this if you are using phatomJS:

from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get('https://www.zhihu.com/people/weizhi-xiazhi/followers')
driver.implicitly_wait(10) #wait some time to load
elements = driver.find_elements_by_xpath('//*[@class="UserItem-title"]/descendant::a')
for e in elements:
    print(e.get_attribute("href"))

Note that I opted for a less "restrictive" expression so that it is less sensible to small website changes.


问:
Defining the directory to save outputs in Python for text files
I would like to save my outputs (which are text files) from a Python script to a different directory. Following is my code to define the directory for my  outputs:

```<code>headers = list(uniq)
output_headers = open(save_path, "headers_dash1" + "_" + str(count) + ".raw", "w")
for item in headers:
    output_headers.write("%s\n" % item)
</code>```

How can I generate these outputs to a different fixed directory like:
D:\Test\"The file name"

答:
For instance, you can use the join function from os.path (docs)

```<code>import os
output_dir = "Test"

files = ["file1", "file2", "file3"]
for f in files:
    open(os.path.join(output_dir, f)) #this combines the path into Test/file1, etc.
    #write etc here
</code>```

Body:
I would like to save my outputs (which are text files) from a Python script to a different directory. Following is my code to define the directory for my  outputs:

headers = list(uniq)
output_headers = open(save_path, "headers_dash1" + "_" + str(count) + ".raw", "w")
for item in headers:
    output_headers.write("%s\n" % item)

How can I generate these outputs to a different fixed directory like:
D:\Test\"The file name"

Body:
For instance, you can use the join function from os.path (docs)

import os
output_dir = "Test"

files = ["file1", "file2", "file3"]
for f in files:
    open(os.path.join(output_dir, f)) #this combines the path into Test/file1, etc.
    #write etc here


问:
Why TAB inside VIM moves one space after exactly three-long characters words?
After one-character length word or more than three-length characters word there TAB moves exactly 4 spaces.
My .vimrc configuration file is it as it follows.

```<code>syntax on

" number of spaces moved along by pressing >>, << or ==
set shiftwidth=4

" number of spaces moved along by pressing the <TAB> or <BS> key
set softtabstop=4

set expandtab
</code>```

The tabstop configuration value is set to default, 8.
I was expecting that TAB will move forward 4 spaces no matter what.

答:
When indenting, vim inserts however many spaces it needs to get to the next multiple of shiftwidth.

In your case, shiftwidth=4, so vim inserts spaces until it gets to column 4: only one space.

If you want vim to instead blindly insert four spaces no matter what, try the following in your vimrc:

```<code>inoremap <TAB> <space><space><space><space>
</code>```

That will make vim insert 4 spaces.

Body:
After one-character length word or more than three-length characters word there TAB moves exactly 4 spaces.
My .vimrc configuration file is it as it follows.

syntax on

" number of spaces moved along by pressing >>, << or ==
set shiftwidth=4

" number of spaces moved along by pressing the <TAB> or <BS> key
set softtabstop=4

set expandtab

The tabstop configuration value is set to default, 8.
I was expecting that TAB will move forward 4 spaces no matter what.

Body:
When indenting, vim inserts however many spaces it needs to get to the next multiple of shiftwidth.

In your case, shiftwidth=4, so vim inserts spaces until it gets to column 4: only one space.

If you want vim to instead blindly insert four spaces no matter what, try the following in your vimrc:

inoremap <TAB> <space><space><space><space>

That will make vim insert 4 spaces.


问:
Appending predicted residuals to pandas dataframe - by groups
This question extends this question, but now I want to add the residuals for separate groups.

So, how to append the residuals when you want to run regressions for separate groups?

Here is the data frame:

```<code>df = pd.DataFrame({'gp': [1,1,1,1,1,2,2,2,2,2],
               'x1': [3.17, 4.76, 4.17, 8.70, 11.45, 3.17, 4.76, 4.17, 8.70, 11.45],
               'x2': [23, 26, 73, 72, 16, 26, 73, 72, 16, 25],
               'y': [880.37, 716.20, 974.79, 322.80, 1054.25, 980.37, 816.20, 1074.79, 522.80, 1254.25]},
               index=np.arange(10, 30, 2))
</code>```

Now, I want to run separate regression for the two groups (gp), and append the residuals in a separate column.

I tried this code, but it only fills the residuals of the last regression group (gp=2):

```<code>import numpy as np
import pandas as pd
import statsmodels.formula.api as sm

def groupreg(df, regmodel):
    groups = df.groupby('gp')
    for item, group in groups:
        df['residual'] = sm.ols(formula=regmodel, data=group).fit().resid
    return (df)

regmodel = 'y ~ x1 + x2'

df = groupreg(df,regmodel)
</code>```

I found one way to crack this problem, but the code is long en looks inefficient:

```<code>def groupreg2(df, regmodel):
    groups = df.groupby('gp')
    i = 0
    resname='residual'
    for item, group in groups:
        data = group.copy()
        data[resname] = sm.ols(formula=regmodel, data=data).fit().resid
        if i == 0:
            i = 1
            dout = data[resname].copy()
        else:
            dout = dout.append(data[resname].copy())

    df = pd.concat([df,dout],axis=1)
    return (df)

    df = groupreg2(df,regmodel)
</code>```

Any suggestions to improve?

答:
I found the issue with your first solution, it's that you assign the result to original dataframe (df), instead you should assign it to the group, like that:

```<code>def groupreg(df, regmodel):
    groups = df.groupby('gp')
    for item, group in groups:
        group['residual'] = sm.ols(formula=regmodel, data=group).fit().resid
    return (df)
</code>```

Just a slight change but it works as expected now.

Body:
This question extends this question, but now I want to add the residuals for separate groups.

So, how to append the residuals when you want to run regressions for separate groups?

Here is the data frame:

df = pd.DataFrame({'gp': [1,1,1,1,1,2,2,2,2,2],
               'x1': [3.17, 4.76, 4.17, 8.70, 11.45, 3.17, 4.76, 4.17, 8.70, 11.45],
               'x2': [23, 26, 73, 72, 16, 26, 73, 72, 16, 25],
               'y': [880.37, 716.20, 974.79, 322.80, 1054.25, 980.37, 816.20, 1074.79, 522.80, 1254.25]},
               index=np.arange(10, 30, 2))

Now, I want to run separate regression for the two groups (gp), and append the residuals in a separate column.

I tried this code, but it only fills the residuals of the last regression group (gp=2):

import numpy as np
import pandas as pd
import statsmodels.formula.api as sm

def groupreg(df, regmodel):
    groups = df.groupby('gp')
    for item, group in groups:
        df['residual'] = sm.ols(formula=regmodel, data=group).fit().resid
    return (df)

regmodel = 'y ~ x1 + x2'

df = groupreg(df,regmodel)

I found one way to crack this problem, but the code is long en looks inefficient:

def groupreg2(df, regmodel):
    groups = df.groupby('gp')
    i = 0
    resname='residual'
    for item, group in groups:
        data = group.copy()
        data[resname] = sm.ols(formula=regmodel, data=data).fit().resid
        if i == 0:
            i = 1
            dout = data[resname].copy()
        else:
            dout = dout.append(data[resname].copy())

    df = pd.concat([df,dout],axis=1)
    return (df)

    df = groupreg2(df,regmodel)

Any suggestions to improve?

Body:
I found the issue with your first solution, it's that you assign the result to original dataframe (df), instead you should assign it to the group, like that:

def groupreg(df, regmodel):
    groups = df.groupby('gp')
    for item, group in groups:
        group['residual'] = sm.ols(formula=regmodel, data=group).fit().resid
    return (df)

Just a slight change but it works as expected now.


问:
RadMenu Performance Issues
I have a page that has a RadMenu and a RadGrid used together. The RadGrid is used in client-side mode. This means that the loading, saving, editing and creation of new records is done via ajax. The grid seems to work fine but after sometime it appears that The menu dropdowns tend to be slower and after more use the entire page freezes. I am not sure whether it is this combo that causes this effect or either of the controls since a lot of js is being used to automate the menu dropdown and the ajax calls to the. This is the order in which the error is reproduced.

The menu control is located up above in a separate iframe and the grid is below in a separate iframe. This makes the scenario more peculiar since different js files are loaded in two iframes and there is no interaction between the two.

What could be the cause of the sudden freezing, a memory leak perhaps? Better still could it be a general problem when a lot of ajax interactions occur and other events are fired before the callbacks return?

On the video once can see that when the grid page loads everything seems fine, but after firing some events and performing some actions, the menu starts taking a lot of time to load. It reaches a point that it takes such a long time for the drop downs to display and eventually the entire browser tab freezes.

I have uploaded a video of the effects and here is the link:
http://megaswf.com/simple_serve/87153/

答:
"Better still could it be a general problem when a lot of ajax interactions occur and other events are fired before the callbacks return?"
- that's most of your problem. Telerik's JavaScript is thrown together, just view source and check out how many scripts are on the page, as well as the inlineJS. Contacting Telerik couldn't hurt, but I doubt it'll help. If you have a float based layout, when you go into edit Telerik, the tools don't work because they're relying on absolute positioning. I had to find my own solution. Good luck. </p>

ContentLicense: CC BY-SA 4.0

Title: RadMenu Performance Issues

ContentLicense: CC BY-SA 2.5


问:
Properly log out a user from android app
I'm developing a small android app, and basically so far it just has login and logout functionality. I'm using Firebase to store user data and also for authentication.

So I have login working and it authenticates users as it should and I have logging out working in the sense that it unauthenticates users. But is there anything I have to do from within the app to kill the session?

```<code>if (id == R.id.action_log_out) {
    ref.unauth(); //End user session
    startActivity(new Intent(MainActivity.this, LoginActivity.class)); //Go back to home page
    finish();
}
</code>```

Will this work as I think it should?  Obviously if someone logs out they shouldn't be able to hit th back button and magically go back to the last page without re-logging in.

答:
I see 2 options for the issue we have with the back-Button after Logout:

In your LoginActivity, wich should be you launcher activity, Override onBackPressed Method and leave it empty:

```<code>    @Override
public void onBackPressed() {
// empty so nothing happens
}
</code>```

Or/and you can add the LoginActivityIntent in your LogoutActivty if user == null.
This way, whenever a not authenticated user lands on the activity, it will redirect to the LoginActivity instantly, although this looks kinda weird.

```<code>        mAuth = FirebaseAuth.getInstance();
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG,"onAuthStateChanged:signed_out");
                startActivity(new Intent(LogoutActivity.this, LoginActivity.class));
            }
            // ...
        }
    };
</code>```

First Option is easier, but I guess if you apply both your on the save side ^^ Im coding for 2 weeks now so correct me if im wrong.

Body:
I'm developing a small android app, and basically so far it just has login and logout functionality. I'm using Firebase to store user data and also for authentication.

So I have login working and it authenticates users as it should and I have logging out working in the sense that it unauthenticates users. But is there anything I have to do from within the app to kill the session?

if (id == R.id.action_log_out) {
    ref.unauth(); //End user session
    startActivity(new Intent(MainActivity.this, LoginActivity.class)); //Go back to home page
    finish();
}

Will this work as I think it should?  Obviously if someone logs out they shouldn't be able to hit th back button and magically go back to the last page without re-logging in.

Body:
I see 2 options for the issue we have with the back-Button after Logout:

In your LoginActivity, wich should be you launcher activity, Override onBackPressed Method and leave it empty:

    @Override
public void onBackPressed() {
// empty so nothing happens
}

Or/and you can add the LoginActivityIntent in your LogoutActivty if user == null.
This way, whenever a not authenticated user lands on the activity, it will redirect to the LoginActivity instantly, although this looks kinda weird.

        mAuth = FirebaseAuth.getInstance();
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG,"onAuthStateChanged:signed_out");
                startActivity(new Intent(LogoutActivity.this, LoginActivity.class));
            }
            // ...
        }
    };

First Option is easier, but I guess if you apply both your on the save side ^^ Im coding for 2 weeks now so correct me if im wrong.


问:
How to downcast in Typescript?
How do I downcast in typescript?

```<code>const x: {a: number, b: number} = {a: 1, b: 2};

const y: {b: number}            = x;   //   upcast
const z: {a: number, b: number} = ???; // downcast
</code>```

I can upcast x to y, but what needs to go in ??? to downcast y to z?

For comparison, C# would look like

```<code>AandB x = ...
A y = x;
B z = y as B;
</code>```

答:
Try something like:</p>

```<code>type AandB = { a: number, b: number };

const x: AandB = { a: 1, b: 2 };
const y: {b: number} = x; // upcast
const z: { a: number, b: number } = y as AandB; // downcast
</code>```

Title: How to downcast in Typescript?

Body:
How do I downcast in typescript?

const x: {a: number, b: number} = {a: 1, b: 2};

const y: {b: number}            = x;   //   upcast
const z: {a: number, b: number} = ???; // downcast

I can upcast x to y, but what needs to go in ??? to downcast y to z?

For comparison, C# would look like

AandB x = ...
A y = x;
B z = y as B;

Body:
Try something like:

type AandB = { a: number, b: number };

const x: AandB = { a: 1, b: 2 };
const y: {b: number} = x; // upcast
const z: { a: number, b: number } = y as AandB; // downcast


问:
Star rating using Font Awesome doesn't work properly on Edge and IE
The star rating using Font Awesome defined by width provided below is working fine on Chrome and Firefox, but on Edge and IE doesn't. Anyone know what could it be?

JSFiddle

Chrome and Firefox

Edge and IE

.star-rating {
  display: inline-block;
  position: relative;
  line-height: 1;
}
.star-rating:before,
.star-rating:after {
  content: "\f005\f005\f005\f005\f005";
  display: block;
  font-family: "FontAwesome";
  font-size: 25px;
  color: #ccc;
}
.star-rating:after {
  color: gold;
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
}

.star-rating.s0:after {
  width: 0%;
}
.star-rating.s1:after {
  width: 10%;
}
.star-rating.s2:after {
  width: 20%;
}
.star-rating.s3:after {
  width: 30%;
}
.star-rating.s4:after {
  width: 40%;
}
.star-rating.s5:after {
  width: 50%;
}
.star-rating.s6:after {
  width: 60%;
}
.star-rating.s7:after {
  width: 70%;
}
.star-rating.s8:after {
  width: 80%;
}
.star-rating.s9:after {
  width: 90%;
}
.star-rating.s10:after {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<span class="star-rating s7"></span></code>```

答:
Add white-space:nowrap to the .star-rating::before, .star-rating::after rule.

.star-rating {
  display: inline-block;
  position: relative;
  line-height: 1;
}
.star-rating:before,
.star-rating:after {
  content: "\f005\f005\f005\f005\f005";
  display: block;
  font-family: "FontAwesome";
  font-size: 25px;
  color: #ccc;
  white-space:nowrap;
}
.star-rating:after {
  color: gold;
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
}

.star-rating.s0:after {
  width: 0%;
}
.star-rating.s1:after {
  width: 10%;
}
.star-rating.s2:after {
  width: 20%;
}
.star-rating.s3:after {
  width: 30%;
}
.star-rating.s4:after {
  width: 40%;
}
.star-rating.s5:after {
  width: 50%;
}
.star-rating.s6:after {
  width: 60%;
}
.star-rating.s7:after {
  width: 70%;
}
.star-rating.s8:after {
  width: 80%;
}
.star-rating.s9:after {
  width: 90%;
}
.star-rating.s10:after {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<span class="star-rating s7"></span></code>```

Body:
The star rating using Font Awesome defined by width provided below is working fine on Chrome and Firefox, but on Edge and IE doesn't. Anyone know what could it be?

JSFiddle

Chrome and Firefox

Edge and IE

.star-rating {
  display: inline-block;
  position: relative;
  line-height: 1;
}
.star-rating:before,
.star-rating:after {
  content: "\f005\f005\f005\f005\f005";
  display: block;
  font-family: "FontAwesome";
  font-size: 25px;
  color: #ccc;
}
.star-rating:after {
  color: gold;
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
}

.star-rating.s0:after {
  width: 0%;
}
.star-rating.s1:after {
  width: 10%;
}
.star-rating.s2:after {
  width: 20%;
}
.star-rating.s3:after {
  width: 30%;
}
.star-rating.s4:after {
  width: 40%;
}
.star-rating.s5:after {
  width: 50%;
}
.star-rating.s6:after {
  width: 60%;
}
.star-rating.s7:after {
  width: 70%;
}
.star-rating.s8:after {
  width: 80%;
}
.star-rating.s9:after {
  width: 90%;
}
.star-rating.s10:after {
  width: 100%;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

Body:
Add white-space:nowrap to the .star-rating::before, .star-rating::after rule.

.star-rating {
  display: inline-block;
  position: relative;
  line-height: 1;
}
.star-rating:before,
.star-rating:after {
  content: "\f005\f005\f005\f005\f005";
  display: block;
  font-family: "FontAwesome";
  font-size: 25px;
  color: #ccc;
  white-space:nowrap;
}
.star-rating:after {
  color: gold;
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
}

.star-rating.s0:after {
  width: 0%;
}
.star-rating.s1:after {
  width: 10%;
}
.star-rating.s2:after {
  width: 20%;
}
.star-rating.s3:after {
  width: 30%;
}
.star-rating.s4:after {
  width: 40%;
}
.star-rating.s5:after {
  width: 50%;
}
.star-rating.s6:after {
  width: 60%;
}
.star-rating.s7:after {
  width: 70%;
}
.star-rating.s8:after {
  width: 80%;
}
.star-rating.s9:after {
  width: 90%;
}
.star-rating.s10:after {
  width: 100%;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<span class="star-rating s7"></span>


问:
Pandas/Google BigQuery: Schema mismatch makes the upload fail
The schema in my google table looks like this:

```<code>price_datetime : DATETIME,
symbol         : STRING,
bid_open       : FLOAT,
bid_high       : FLOAT,
bid_low        : FLOAT,
bid_close      : FLOAT,
ask_open       : FLOAT,
ask_high       : FLOAT,
ask_low        : FLOAT,
ask_close      : FLOAT
</code>```

After I do a pandas.read_gbq I get a dataframe with column dtypes like this:

```<code>price_datetime     object
symbol             object
bid_open          float64
bid_high          float64
bid_low           float64
bid_close         float64
ask_open          float64
ask_high          float64
ask_low           float64
ask_close         float64
dtype: object
</code>```

Now I want to use to_gbq so I convert my local dataframe (which I just made) from these dtypes:

```<code>price_datetime    datetime64[ns]
symbol                    object
bid_open                 float64
bid_high                 float64
bid_low                  float64
bid_close                float64
ask_open                 float64
ask_high                 float64
ask_low                  float64
ask_close                float64
dtype: object
</code>```

to these dtypes:

```<code>price_datetime     object
symbol             object
bid_open          float64
bid_high          float64
bid_low           float64
bid_close         float64
ask_open          float64
ask_high          float64
ask_low           float64
ask_close         float64
dtype: object
</code>```

by doing:

```<code>df['price_datetime'] = df['price_datetime'].astype(object)
</code>```

Now I (think) I am read to use to_gbq so I do:

```<code>import pandas
pandas.io.gbq.to_gbq(df, <table_name>, <project_name>, if_exists='append')
</code>```

but I get the error:

```<code>---------------------------------------------------------------------------
InvalidSchema                             Traceback (most recent call last)
<ipython-input-15-d5a3f86ad382> in <module>()
      1 a = time.time()
----> 2 pandas.io.gbq.to_gbq(df, <table_name>, <project_name>, if_exists='append')
      3 b = time.time()
      4
      5 print(b-a)

C:\Users\me\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\gbq.py in to_gbq(dataframe, destination_table, project_id, chunksize, verbose, reauth, if_exists, private_key)
    825         elif if_exists == 'append':
    826             if not connector.verify_schema(dataset_id, table_id, table_schema):
--> 827                 raise InvalidSchema("Please verify that the structure and "
    828                                     "data types in the DataFrame match the "
    829                                     "schema of the destination table.")

InvalidSchema: Please verify that the structure and data types in the DataFrame match the schema of the destination table.
</code>```

答:
This is probably an issue related to pandas. If you check the code for to_gbq, you'll see that it runs this code:

```<code>table_schema = _generate_bq_schema(dataframe)
</code>```

Where _generate_bq_schema is given by:

```<code>def _generate_bq_schema(df, default_type='STRING'):
    """ Given a passed df, generate the associated Google BigQuery schema.
    Parameters
    ----------
    df : DataFrame
    default_type : string
        The default big query type in case the type of the column
        does not exist in the schema.
    """

    type_mapping = {
        'i': 'INTEGER',
        'b': 'BOOLEAN',
        'f': 'FLOAT',
        'O': 'STRING',
        'S': 'STRING',
        'U': 'STRING',
        'M': 'TIMESTAMP'
    }

    fields = []
    for column_name, dtype in df.dtypes.iteritems():
        fields.append({'name': column_name,
                       'type': type_mapping.get(dtype.kind, default_type)})

    return {'fields': fields}
</code>```

As you can see, there's no type mapping to DATETIME. This inevitably gets mapped to type STRING (since its dtype.kind is "O") and then conflict occurs.

The only work around for now that I'm aware of would be to change your table schema from DATETIME to either TIMESTAMP or STRING.

It probably would be a good idea to start a new issue on pandas-bq repository asking to update this code to accept DATETIME as well.

[EDIT]:

I've opened this issue in their repository.

Body:
The schema in my google table looks like this:

price_datetime : DATETIME,
symbol         : STRING,
bid_open       : FLOAT,
bid_high       : FLOAT,
bid_low        : FLOAT,
bid_close      : FLOAT,
ask_open       : FLOAT,
ask_high       : FLOAT,
ask_low        : FLOAT,
ask_close      : FLOAT

After I do a pandas.read_gbq I get a dataframe with column dtypes like this:

price_datetime     object
symbol             object
bid_open          float64
bid_high          float64
bid_low           float64
bid_close         float64
ask_open          float64
ask_high          float64
ask_low           float64
ask_close         float64
dtype: object

Now I want to use to_gbq so I convert my local dataframe (which I just made) from these dtypes:

price_datetime    datetime64[ns]
symbol                    object
bid_open                 float64
bid_high                 float64
bid_low                  float64
bid_close                float64
ask_open                 float64
ask_high                 float64
ask_low                  float64
ask_close                float64
dtype: object

to these dtypes:

price_datetime     object
symbol             object
bid_open          float64
bid_high          float64
bid_low           float64
bid_close         float64
ask_open          float64
ask_high          float64
ask_low           float64
ask_close         float64
dtype: object

by doing:

df['price_datetime'] = df['price_datetime'].astype(object)

Now I (think) I am read to use to_gbq so I do:

import pandas
pandas.io.gbq.to_gbq(df, <table_name>, <project_name>, if_exists='append')

but I get the error:

---------------------------------------------------------------------------
InvalidSchema                             Traceback (most recent call last)
<ipython-input-15-d5a3f86ad382> in <module>()
      1 a = time.time()
----> 2 pandas.io.gbq.to_gbq(df, <table_name>, <project_name>, if_exists='append')
      3 b = time.time()
      4
      5 print(b-a)

C:\Users\me\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\gbq.py in to_gbq(dataframe, destination_table, project_id, chunksize, verbose, reauth, if_exists, private_key)
    825         elif if_exists == 'append':
    826             if not connector.verify_schema(dataset_id, table_id, table_schema):
--> 827                 raise InvalidSchema("Please verify that the structure and "
    828                                     "data types in the DataFrame match the "
    829                                     "schema of the destination table.")

InvalidSchema: Please verify that the structure and data types in the DataFrame match the schema of the destination table.

Body:
This is probably an issue related to pandas. If you check the code for to_gbq, you'll see that it runs this code:

table_schema = _generate_bq_schema(dataframe)

Where _generate_bq_schema is given by:

def _generate_bq_schema(df, default_type='STRING'):
    """ Given a passed df, generate the associated Google BigQuery schema.
    Parameters
    ----------
    df : DataFrame
    default_type : string
        The default big query type in case the type of the column
        does not exist in the schema.
    """

    type_mapping = {
        'i': 'INTEGER',
        'b': 'BOOLEAN',
        'f': 'FLOAT',
        'O': 'STRING',
        'S': 'STRING',
        'U': 'STRING',
        'M': 'TIMESTAMP'
    }

    fields = []
    for column_name, dtype in df.dtypes.iteritems():
        fields.append({'name': column_name,
                       'type': type_mapping.get(dtype.kind, default_type)})

    return {'fields': fields}

As you can see, there's no type mapping to DATETIME. This inevitably gets mapped to type STRING (since its dtype.kind is "O") and then conflict occurs.

The only work around for now that I'm aware of would be to change your table schema from DATETIME to either TIMESTAMP or STRING.

It probably would be a good idea to start a new issue on pandas-bq repository asking to update this code to accept DATETIME as well.

[EDIT]:

I've opened this issue in their repository.


问:
Edit .dtsx file without the SSIS project
We got a SSIS maintenance plan package in our client's server which does the database backups (Back Up Database Task). We need to export this package to a new database server and need to change the backup locations and sql serer server configurations in the package.

The problem is we do not have the actual SSIS project but the .dtsx file.It's possible to do the changes just by using .dtsx file design by opening it on SQL Server Data Tools but does it require to do a build and then import the file in to stored packages?

答: As per my experience, take a backup of the file, open the file in notepad or notepad++ and edit the locations. it is that simple. And should test first in UAT or PreProd :)</p>


问:
How to format many values in a database?
I have a database (in SQLite) in which some entries (or possibly all) are strings whose first character is a space.

The database may be small enough for me to export it as a CSV file and do a regular-expression search-and-replace which will delete the leading space. Is there an SQL statement which can achieve the same result?

(The database has over 60 columns---listing each one might get tedious.)

答:
Take a look at thr trim family of functions, e.g. ltrim.

ltrim(X), ltrim(X,Y)

The ltrim(X,Y) function returns a string formed by removing any and all characters that appear in Y from the left side of X. If the Y argument is omitted, ltrim(X) removes spaces from the left side of X.

More: http://www.sqlite.org/lang_corefunc.html


问:
Pass parameter in the select of a query
I am building a query but I need to pass the parameters that I am sending to the model to be used in the query, the problem is that I can not make the query accept the parameters within the select, this is my query:

```<code>  def self.reporte_inventario_total(params)
    query = select("(SELECT Ruta FROM Rutas WHERE IdRutas = :rutaId or :rutaId = '') AS Ruta,
      ISNULL((SELECT S.Stock/PP.PzaXCja AS INT FROM stockhistorico S LEFT JOIN ProductosXPzas PP ON S.Articulo=PP.Producto WHERE S.Articulo=Productos.Clave AND S.RutaId = :rutaId or :rutaId = '' AND fecha = :fechaDiaO or :fechaDiaO = ''),0) AS  StockCajas,
      ISNULL((SELECT S.Stock%PP.PzaXCja AS INT FROM stockhistorico S LEFT JOIN ProductosXPzas PP ON S.Articulo=PP.Producto WHERE S.Articulo=Productos.Clave AND S.RutaId = :rutaId or :rutaId = '' AND fecha = :fechaDiaO or :fechaDiaO = ''),0) AS StockPiezas,
      Productos.Clave, Productos.Producto, Productos.CodBarras,Productos.Sector", ({rutaId: params[:search],fechaDiaO: params[:fechaDiaO]}))

  end
</code>```

and this is the error that I get

```<code>unsupported: Hash
</code>```

答:
Your problem is that the select method unlike the where method expects a plain string as its argument, it doesn't allow ? and :variable placeholders.

To use expressions like :rutaId you need to wrap the select query with a call to sanitize_sql_array.

Assuming that reporte_inventario_total is a method on some ActiveRecord::Base subclass:

```<code>query_string = "SELECT Ruta FROM Rutas WHERE IdRutas = :rutaId or :rutaId ..."
query = select(sanitize_sql_array([query_string, rutaId: params[:search], fechaDiaO: params[:fechaDiaO]))
</code>```

If reporte_inventario_total is a written outside of some ActiveRecord::Base subclass then you need to replace sanitize_sql_array(...) with something like ActiveRecord::Base.send(:sanitize_sql_array, ...), because that method is private and is intended to be used in models only.

Title: Pass parameter in the select of a query

Body:
I am building a query but I need to pass the parameters that I am sending to the model to be used in the query, the problem is that I can not make the query accept the parameters within the select, this is my query:

  def self.reporte_inventario_total(params)
    query = select("(SELECT Ruta FROM Rutas WHERE IdRutas = :rutaId or :rutaId = '') AS Ruta,
      ISNULL((SELECT S.Stock/PP.PzaXCja AS INT FROM stockhistorico S LEFT JOIN ProductosXPzas PP ON S.Articulo=PP.Producto WHERE S.Articulo=Productos.Clave AND S.RutaId = :rutaId or :rutaId = '' AND fecha = :fechaDiaO or :fechaDiaO = ''),0) AS  StockCajas,
      ISNULL((SELECT S.Stock%PP.PzaXCja AS INT FROM stockhistorico S LEFT JOIN ProductosXPzas PP ON S.Articulo=PP.Producto WHERE S.Articulo=Productos.Clave AND S.RutaId = :rutaId or :rutaId = '' AND fecha = :fechaDiaO or :fechaDiaO = ''),0) AS StockPiezas,
      Productos.Clave, Productos.Producto, Productos.CodBarras,Productos.Sector", ({rutaId: params[:search],fechaDiaO: params[:fechaDiaO]}))

  end

and this is the error that I get

unsupported: Hash

Body:
Your problem is that the select method unlike the where method expects a plain string as its argument, it doesn't allow ? and :variable placeholders.

To use expressions like :rutaId you need to wrap the select query with a call to sanitize_sql_array.

Assuming that reporte_inventario_total is a method on some ActiveRecord::Base subclass:

query_string = "SELECT Ruta FROM Rutas WHERE IdRutas = :rutaId or :rutaId ..."
query = select(sanitize_sql_array([query_string, rutaId: params[:search], fechaDiaO: params[:fechaDiaO]))

If reporte_inventario_total is a written outside of some ActiveRecord::Base subclass then you need to replace sanitize_sql_array(...) with something like ActiveRecord::Base.send(:sanitize_sql_array, ...), because that method is private and is intended to be used in models only.


问:
Asterisk abandoned calls
I have some realtime tables, those named cdr and queue_log. I can get reports from that tables. These are "Cdr details" and "Abandoned calls". But i have a problem. I can see who abandoned the queue and do voicemail.

But what about other stuffs. If somebody close call before reaching queue or voicemail message. How can I detect them? That's important, because some customers doesn't want to create voicemail message. I don't want to lose them.

答:
There are NO WAY say who abandoned queue.

Reason is simple: let say you have queue with 100 agents and nobody answered. Who abandoned?

You have 2 options

1) on incoming call save cid to some table, compare with queue_log in 10 minutes.

2) check cdr and see if you have calls that have be reported. optionally mark such calls by CDR(userfield).

Title: Asterisk abandoned calls


问:
Grails 2.5.5 controller unit test cannot cast object error
I've been trying to set up a unit test for a controller. However, any attempt to access the controller property causes the following error:

```<code>org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'class au.org.ala.collectory.ContactController' with class 'java.lang.Class' to class 'au.org.ala.collectory.ContactController'
</code>```

Here's the code that I've been using:

```<code>package au.org.ala.collectory

import grails.test.mixin.Mock
import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(ContactController)
@Mock([Contact, CollectoryAuthService])
class ContactControllerTests extends Specification {
    def contact

    def setup() {
        contact = new Contact(
            title: "Dr",
            firstName: "Lemmy",
            lastName: "Caution",
            phone: "0262465909",
            mobile: "0419468551",
            email: "lemmy.caution@csiro.au",
            notes: "to be treated with exaggerated respect",
            publish: true,
            userLastModified: 'test')
     }

    def testList() {
        when:
        contact.save(flush:true, failOnError: true)
        request.contentType = JSON_CONTENT_TYPE
        controller.list()
        then:
        model.contactInstanceList.size() == 1
        model.contactInstanceList[0].title == 'Dr'
    }
}
</code>```

I've tried various combinations of code placement and mocking, all to no avail. Any explanation as to why I would be getting this error would be most appreciated.

答: The problem is caused by a def name = { closure in the controller. This seems to interfere with the AST transformation taking place. Changing the closure to a method, ie def name() { allows the tests to run.

Body:
I've been trying to set up a unit test for a controller. However, any attempt to access the controller property causes the following error:

org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'class au.org.ala.collectory.ContactController' with class 'java.lang.Class' to class 'au.org.ala.collectory.ContactController'

Here's the code that I've been using:

package au.org.ala.collectory

import grails.test.mixin.Mock
import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(ContactController)
@Mock([Contact, CollectoryAuthService])
class ContactControllerTests extends Specification {
    def contact

    def setup() {
        contact = new Contact(
            title: "Dr",
            firstName: "Lemmy",
            lastName: "Caution",
            phone: "0262465909",
            mobile: "0419468551",
            email: "lemmy.caution@csiro.au",
            notes: "to be treated with exaggerated respect",
            publish: true,
            userLastModified: 'test')
     }

    def testList() {
        when:
        contact.save(flush:true, failOnError: true)
        request.contentType = JSON_CONTENT_TYPE
        controller.list()
        then:
        model.contactInstanceList.size() == 1
        model.contactInstanceList[0].title == 'Dr'
    }
}

I've tried various combinations of code placement and mocking, all to no avail. Any explanation as to why I would be getting this error would be most appreciated.


问:
Performance issues with Redshift Spectrum
I am using Redhshift spectrum. I created an external table and uploaded a csv data file on S3 with around 5.5 million records. If fire a query on this external table, it is taking ~15 seconds whereas If I run same query on Amazon redshift, I was getting same result in ~2 seconds. What could be the reason for this performance lag where AWS claim it to be be very high performance platform. Please suggest solution for same performance using spectrum.</p>

答:
These results are to be expected. The whole reason for using Amazon Redshift is that it stores data in a highly-optimized manner to provide fast queries. Data stored outside of Redshift will not run anywhere near as fast.

The intention of Amazon Redshift Spectrum is to provide access to data stored in Amazon S3 without having to load it into Redshift (similar to Amazon Athena), but it makes no performance guarantees.


问:
Making an executable GEM from a script
I started developing ruby lately and I really like it, But I feel somehow lost. I developed a script that does "whatever" and that scripts requires many gems like nokogiri and colorize. I now want to deploy the script, so after reading a while I found many people saying that deploying as a gem is the best approach. So my question is simple? Is there any tool that I can use to create a gem of my script file and include all the gem dependencies(nokogiri) in the new gem?

I am using ubuntu!

Thanks alot

答:
The best way to make a gem is to use the bundler program to build a skeleton:

```<code># bundler gem (gem_name)
bundler gem geil_gem
</code>```

This will create a template gemspec file and give you the basic structure needed for your gem to have a setup command, a console and be ready to build into a working gem (both found in the bin folder of your skeleton project). From here you can add a command binary or build out the gem as a library using the lib directory or start with tests by adding rspec to the gemspec and creating a test folder.

Title: Making an executable GEM from a script

Body:
The best way to make a gem is to use the bundler program to build a skeleton:

# bundler gem (gem_name)
bundler gem geil_gem

This will create a template gemspec file and give you the basic structure needed for your gem to have a setup command, a console and be ready to build into a working gem (both found in the bin folder of your skeleton project). From here you can add a command binary or build out the gem as a library using the lib directory or start with tests by adding rspec to the gemspec and creating a test folder.


问:
PHP: Maintain session data with a class object
I am a PHP OOP newbie and I am currently learning sessions. I have created a session class which is supposed to check if session variable $_SESSION['userID'] is set, and set the login status to true; as well as set the user id.There is also a function, setVars() to set other object properties when called:
session.php

```<code><?php
class Session
{
public  $log_in_status=false;
public  $userID;
public  $fname;
public  $class_id;
public  $email;

public function __construct()
{
session_start();

if ($_SESSION['userID'])
{
    $this->log_in_status = true;
    $this->userID = $_SESSION['userID'];
}
else
{
    $this->log_in_status = false;
    unset($_SESSION['userID']);
}
}

public function setVars($classID, $email, $fname)
{
$this->class_id = $classID;
$this->email    = $email;
$this->fname    = $fname;
}
}

$session = new Session();
</code>```

The above class is in a require_once statement in init.php file:

```<code><?php
 #init.php
 require_once("session.php");
</code>```

Page1.php sets some properties in the $session instance by calling the setVars method, and after echo them to the screen. However, page2.php is not able to echo these same values from the object properties:

```<code><?php
# page1.php

  require_once("init.php");

  $class_id = 1;
  $email    = "test@test.com";
  $fname    = "Toto The Dog";

  $session->setVars($class_id, $email, $fname);

?>

<!DOCTYPE html>
<html>
    <head>
        <title>Testing sessions</title>
    </head>
    <body>
    <?php
        echo "Page 1 <br> <br>";
        echo "objectClassID: "   .$session->class_id . "<br>";
        echo "objectEmail  : "   . $session->email . "<br>";
        echo "objectFname  : "   . $session->fname . "<br> <br>";

        echo "<a href='page2.php'>Go to Page 2</a>";
    ?>
    </body>
</html>
</code>```

//--------------------------------------------

```<code><?php
# page2.php

 require_once("init.php");
?>

<!DOCTYPE html>
<html>
    <head>
        <title>Testing sessions</title>
    </head>
    <body>
        <?php
            echo "Page 2 <br> <br>";
            echo "objectClassID: "   . $session->class_id . "<br>";
            echo "objectEmail  : "   . $session->email . "<br>";
            echo "objectFname  : "   . $session->fname . "<br> <br>";

            echo "<a href='page1.php'>Go to Page 1</a>";
        ?>
    </body>
</html>
</code>```

How can I get page2.php to be able to display the $session object properties?

答:
If you want to persist the vars across pages, you need to store them in the $_SESSION array. For example

```<code><?php
class Session {
  public $log_in_status = false;
  public $userID;
  public $fname;
  public $class_id;
  public $email;

  public function __construct() {
    session_start();

    if (isset($_SESSION['userID'])) {
        $this->log_in_status = true;
        $this->userID = $_SESSION['userID'];
    }

    $this->class_id = isset($_SESSION['class_id']) ? $_SESSION['class_id'] : null;
    $this->email = isset($_SESSION['email']) ? $_SESSION['email'] : null;
    $this->fname = isset($_SESSION['fname']) ? $_SESSION['fname'] : null;
  }

  public function setVars($classID, $email, $fname) {
    $this->class_id = $_SESSION['class_id'] = $classID;
    $this->email = $_SESSION['email'] = $email;
    $this->fname = $_SESSION['fname'] = $fname;
  }
}

$session = new Session();
</code>```

Body:
I am a PHP OOP newbie and I am currently learning sessions. I have created a session class which is supposed to check if session variable $_SESSION['userID'] is set, and set the login status to true; as well as set the user id.There is also a function, setVars() to set other object properties when called:
session.php

<?php
class Session
{
public  $log_in_status=false;
public  $userID;
public  $fname;
public  $class_id;
public  $email;

public function __construct()
{
session_start();

if ($_SESSION['userID'])
{
    $this->log_in_status = true;
    $this->userID = $_SESSION['userID'];
}
else
{
    $this->log_in_status = false;
    unset($_SESSION['userID']);
}
}

public function setVars($classID, $email, $fname)
{
$this->class_id = $classID;
$this->email    = $email;
$this->fname    = $fname;
}
}

$session = new Session();

The above class is in a require_once statement in init.php file:

<?php
 #init.php
 require_once("session.php");

Page1.php sets some properties in the $session instance by calling the setVars method, and after echo them to the screen. However, page2.php is not able to echo these same values from the object properties:

<?php
# page1.php

  require_once("init.php");

  $class_id = 1;
  $email    = "test@test.com";
  $fname    = "Toto The Dog";

  $session->setVars($class_id, $email, $fname);

?>

<!DOCTYPE html>

        <title>Testing sessions</title>

    <?php
        echo "Page 1

";
        echo "objectClassID: "   .$session->class_id . "
";
        echo "objectEmail  : "   . $session->email . "
";
        echo "objectFname  : "   . $session->fname . "

";

        echo "Go to Page 2";
    ?>

//--------------------------------------------

<?php
# page2.php

 require_once("init.php");
?>

<!DOCTYPE html>

        <title>Testing sessions</title>

        <?php
            echo "Page 2

";
            echo "objectClassID: "   . $session->class_id . "
";
            echo "objectEmail  : "   . $session->email . "
";
            echo "objectFname  : "   . $session->fname . "

";

            echo "Go to Page 1";
        ?>

How can I get page2.php to be able to display the $session object properties?

Body:
If you want to persist the vars across pages, you need to store them in the $_SESSION array. For example

<?php
class Session {
  public $log_in_status = false;
  public $userID;
  public $fname;
  public $class_id;
  public $email;

  public function __construct() {
    session_start();

    if (isset($_SESSION['userID'])) {
        $this->log_in_status = true;
        $this->userID = $_SESSION['userID'];
    }

    $this->class_id = isset($_SESSION['class_id']) ? $_SESSION['class_id'] : null;
    $this->email = isset($_SESSION['email']) ? $_SESSION['email'] : null;
    $this->fname = isset($_SESSION['fname']) ? $_SESSION['fname'] : null;
  }

  public function setVars($classID, $email, $fname) {
    $this->class_id = $_SESSION['class_id'] = $classID;
    $this->email = $_SESSION['email'] = $email;
    $this->fname = $_SESSION['fname'] = $fname;
  }
}

$session = new Session();


问:
PHP 7: Whats bad about passing a non-variable by reference and why a NOTICE if function passed, but an FATAL error if array is passed?
I have the following code:

```<code>$family = cis_resempty(wp_get_post_terms($post->ID,'family'),0);
</code>```

I get the following error:

Notice: Only variables should be passed by reference in
  C:\xampp.....xxx.php on line 18

If I do the following:

```<code>$family = cis_resempty(array('a'),0);
</code>```

I even get

Fatal error: Only variables can be passed by reference in
  C:\xampp...xxx.php on line 16

The function cis_resempty is like this (but its from a library):

```<code>function cis_resempty(&$var,$key) { ... }
</code>```

Found out that if I remove the & reference sign within the parameter list of cis_resempty there are no errors.

If I do this:

```<code>$family = @cis_resempty(wp_get_post_terms($post->ID,'family'),0);
</code>```

There is no notice and everything works - but Netbeans says:

Misuse of the error control operator

But if I do this:

```<code>$family = @cis_resempty(array('a'),0);
</code>```

The fatal error continues to exist.

Why can I pass a function by reference and suppress the notice with the error control operator but if I pass an array I get a fatal error?

Why is it bad to pass a non variable by reference?

答:
NOTE: never use '@' for suppressing.

Why can I pass a function by reference and suppress the notice with
  the error control operator but if I pass an array I get a fatal error?

Read here Passing by Reference first note:

There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.

PHP doesn't "support" it since 5.4.0 => you get E_FATAL in any case. With @ or without @. For function - you get E_STRICT. All right. Then, read about @ work more here Error Control Operators. Again, first note:

Note: The @-operator works only on expressions. A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.

Try this code ( it will shed light) :

```<code> error_reporting(E_ALL);

 $arr = [1,2,3,4,5,];

 $a_closure = function(){
     return [1,2,3,4,5];
 };

 function a(){
    return [1,2,3,4,5];
 }

 function ref_func(&$input){
    foreach($input as &$in){
        $in++;
    }
 }

 ref_func($a);          // @ref_func($a);
 ref_func(a());         // @ref_func($a());
 ref_func($a_closure);  // @ref_func($a_closure);
 // Fatals in both
 ref_func([1,2,3,4,5]); // @ref_func([1,2,3,4,5]);
</code>```

Body:
I have the following code:

$family = cis_resempty(wp_get_post_terms($post->ID,'family'),0);

I get the following error:

Notice: Only variables should be passed by reference in
  C:\xampp.....xxx.php on line 18

If I do the following:

$family = cis_resempty(array('a'),0);

I even get

Fatal error: Only variables can be passed by reference in
  C:\xampp...xxx.php on line 16

The function cis_resempty is like this (but its from a library):

function cis_resempty(&$var,$key) { ... }

Found out that if I remove the & reference sign within the parameter list of cis_resempty there are no errors.

If I do this:

$family = @cis_resempty(wp_get_post_terms($post->ID,'family'),0);

There is no notice and everything works - but Netbeans says:

Misuse of the error control operator

But if I do this:

$family = @cis_resempty(array('a'),0);

The fatal error continues to exist.

Why can I pass a function by reference and suppress the notice with the error control operator but if I pass an array I get a fatal error?

Why is it bad to pass a non variable by reference?

Body:
NOTE: never use '@' for suppressing.

Why can I pass a function by reference and suppress the notice with
  the error control operator but if I pass an array I get a fatal error?

Read here Passing by Reference first note:

There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.

PHP doesn't "support" it since 5.4.0 => you get E_FATAL in any case. With @ or without @. For function - you get E_STRICT. All right. Then, read about @ work more here Error Control Operators. Again, first note:

Note: The @-operator works only on expressions. A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.

Try this code ( it will shed light) :

 error_reporting(E_ALL);

 $arr = [1,2,3,4,5,];

 $a_closure = function(){
     return [1,2,3,4,5];
 };

 function a(){
    return [1,2,3,4,5];
 }

 function ref_func(&$input){
    foreach($input as &$in){
        $in++;
    }
 }

 ref_func($a);          // @ref_func($a);
 ref_func(a());         // @ref_func($a());
 ref_func($a_closure);  // @ref_func($a_closure);
 // Fatals in both
 ref_func([1,2,3,4,5]); // @ref_func([1,2,3,4,5]);


问:
Django Model self referencing M2M field
I'm trying to get a Django model to automatically construct a typical __str__(self) value for itself (in the model definition), but based on 3 ManyToMany Fields. Unlike when using basic field types (as in the first two models), this doesn't appear to work for M2M fields (see the third model).
The model migrates fine, but causes errors when being referenced in the admin.

Any help much appreciated, thanks!

```<code>class Party(models.Model):
    name=models.CharField("Party", max_length=150)
    def __str__(self):              # __unicode__ on Python 2
        return self.name

    class Meta:
         ordering = ('name',)

class ValCharBehav(models.Model):
    name=models.CharField("Value / Character / Behaviour", max_length=150, unique=True)

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class ValCharBehavWithPeople(models.Model):
    vcb=models.ManyToManyField(ValCharBehav, verbose_name="Value / Character / Behvaiour")
    bywhom=models.ManyToManyField(Party, verbose_name="By Whom", blank=True, related_name="valCharByWhomReverseAccessor")
    towhom=models.ManyToManyField(Party, verbose_name="To Whom", blank=True, related_name="valCharToWhomReverseAccessor")

    def __str__(self):              # __unicode__ on Python 2
         return self.vcb.name+": by: "+self.bywhom.name+", to: "+self.towhom.name
</code>```

答:
```<code>def get_vcb_name(self):
    return ' | '.join(self.vcb.filter(
        name__isnull=False
    ).values_list('name', flat=True))

def get_bywhom_name(self):
    return ' | '.join(self.bywhom.filter(
        name__isnull=False
    ).values_list('name', flat=True))

def get_towhom_name(self):
    return ' | '.join(self.towhom.filter(
        name__isnull=False
    ).values_list('name', flat=True))

def __str__(self):
     return self.get_vcb_name()+": by: "+self.get_bywhom_name()+", to: "+self.get_towhom_name()
</code>```

Title: Django Model self referencing M2M field

Body:
I'm trying to get a Django model to automatically construct a typical __str__(self) value for itself (in the model definition), but based on 3 ManyToMany Fields. Unlike when using basic field types (as in the first two models), this doesn't appear to work for M2M fields (see the third model).
The model migrates fine, but causes errors when being referenced in the admin.

Any help much appreciated, thanks!

class Party(models.Model):
    name=models.CharField("Party", max_length=150)
    def __str__(self):              # __unicode__ on Python 2
        return self.name

    class Meta:
         ordering = ('name',)

class ValCharBehav(models.Model):
    name=models.CharField("Value / Character / Behaviour", max_length=150, unique=True)

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class ValCharBehavWithPeople(models.Model):
    vcb=models.ManyToManyField(ValCharBehav, verbose_name="Value / Character / Behvaiour")
    bywhom=models.ManyToManyField(Party, verbose_name="By Whom", blank=True, related_name="valCharByWhomReverseAccessor")
    towhom=models.ManyToManyField(Party, verbose_name="To Whom", blank=True, related_name="valCharToWhomReverseAccessor")

    def __str__(self):              # __unicode__ on Python 2
         return self.vcb.name+": by: "+self.bywhom.name+", to: "+self.towhom.name


问:
very strange behaviour in Asterisk: Callee is Caller when agent from a queue responds
I saw something strange in asterisk take a loot at the following extensions

```<code>[from-internal]
exten => 7000,1,Answer
same => n,queue(queuename,,,,60,,test)
same => n,Set(GLOBAL(APPELANT)=${CALLERID(num)})

[macro-test]
exten => s,1,Set(GLOBAL(APPELE)=${CALLERID(num)})
</code>```

you will notice that APPELANT and APPELE don't have the same value
APPELANT will contain the caller when APPELE will contain the
callee how is it possible? is it a bug?

I got this from FreePbx 13 (asterisk 11 and above)

答:
No, it is not bug.

You queue members setuped via Local channel.

Can recommend you do following

1) NOT USE GLOBAL VARIABLES for channel staff

2) do Dumpchan at start of your macro and see in which variable you now have caller.

Body:
I saw something strange in asterisk take a loot at the following extensions

[from-internal]
exten => 7000,1,Answer
same => n,queue(queuename,,,,60,,test)
same => n,Set(GLOBAL(APPELANT)=${CALLERID(num)})

[macro-test]
exten => s,1,Set(GLOBAL(APPELE)=${CALLERID(num)})

you will notice that APPELANT and APPELE don't have the same value
APPELANT will contain the caller when APPELE will contain the
callee how is it possible? is it a bug?

I got this from FreePbx 13 (asterisk 11 and above)


问:
How to prevent state change in AngularJS 1.6 with ui-router 1.0?
How can we use $transitions to cancel a state change to prompt the user for saving? Previous ui-router versions used to have an event in the callback, and could be stopped with event.preventDefault(), but this event seems to have disappeared.

I'm using this code in my controller:

```<code>var onTransitionStartOff = $transitions.onStart({}, function($transitions)
{
    if ($scope.itemTracker.hasChanged()) {
        $scope.itemTracker.askExitConfirm().then(function () {
            onTransitionStartOff();
            var toState = $transitions.$to();
            $state.go(toState);
        }, function () {});
        return $q.reject(null);
    }
    onTransitionStartOff();
});
</code>```

It works great, but it leaves an error message in the console due to the rejected promise.

I took a look in stateService.ts, but I didn't see some interesting things...

答:
The solution is to resolve the promise with false if you want to stay in the current state or true if you want to navigate to the new state.</p>

```<code>return $q.resolve(false);
</code>```

Body:
How can we use $transitions to cancel a state change to prompt the user for saving? Previous ui-router versions used to have an event in the callback, and could be stopped with event.preventDefault(), but this event seems to have disappeared.

I'm using this code in my controller:

var onTransitionStartOff = $transitions.onStart({}, function($transitions)
{
    if ($scope.itemTracker.hasChanged()) {
        $scope.itemTracker.askExitConfirm().then(function () {
            onTransitionStartOff();
            var toState = $transitions.$to();
            $state.go(toState);
        }, function () {});
        return $q.reject(null);
    }
    onTransitionStartOff();
});

It works great, but it leaves an error message in the console due to the rejected promise.

I took a look in stateService.ts, but I didn't see some interesting things...

Body:
The solution is to resolve the promise with false if you want to stay in the current state or true if you want to navigate to the new state.

return $q.resolve(false);


问:
pip compiling vs binaries
Sometimes pip install launches a lengthy compilation process. Sometimes it does not. This was most notable with numpy, because it takes significant time to compile but is negligible time when installing binaries. I have an Ubuntu 14 machine where it always compiles numpy, and an Ubuntu 16 machine where it never compiles.

I assumed that Ubuntu 14 packages were no longer available or something. But then I launched a brand new VM with this same older OS, and pip install numpy, went super fast (no compiling). So clearly it is not simply the OS version impacting me. What is going on here?

答:
It's probably a difference in the version of pip you're using. Both binary and source wheels exist in pypi so the question is which will pip choose. I found that on the same machine, pip 1.5.4 would choose the source wheel but pip 9.0.1 would choose the binary one.

Newer versions of pip (ex. 9.0.1) have options for controlling this behaviour: https://pip.pypa.io/en/stable/reference/pip_install/#cmdoption-no-binary

I'm guessing maybe older versions of pip don't even support binary wheels.

So try upgrading pip and then it should install without compiling.

Title: pip compiling vs binaries


问:
Which constructor should I use for the StringBuilder class?
I'm building a large string from a list of items.  Each item will generate a string which is approximately 200 characters long (plus or minus 100%).

Will I get a (noticeable) performance benefit from using

```<code>Dim sb = New StringBuilder(averageCharacterCount * items.Count)
</code>```

instead of

```<code>Dim sb = New StringBuilder()
</code>```

even if the specified capacity is just a guess?

答: If you have a list of strings then you'll get better performance from using String.Concat instead of StringBuilder.

Body:
I'm building a large string from a list of items.  Each item will generate a string which is approximately 200 characters long (plus or minus 100%).

Will I get a (noticeable) performance benefit from using

Dim sb = New StringBuilder(averageCharacterCount * items.Count)

instead of

Dim sb = New StringBuilder()

even if the specified capacity is just a guess?


问:
Using string variables within a command in VBA
I was trying to get a string to work with a code where I automate multiple tabs to be filtered by the same criteria, for a sheet that gets the subtotal out of other sheets.

So, I did some If and Elses to check for some criteria and try to make the filtering after this analysis, instead of having to do multiple AutoFilters withing multiple Ifs.

So, the part bellow works just fine, it is making the string (subStr) accordingly

```<code>If subBacia = "TODOS" Then
    subStr = """<>"""
Else
    subStr = """=" & subBacia & QUOTE & " , Operator:=xlOr, Criteria2:=" & QUOTE & "=TOTAIS" & QUOTE & ""
End If
</code>```

But this part, that I am avoiding to do multiple ifs for, is not working:

```<code>ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=4, Criteria1:=subStr
</code>```

My idea was that it would end up as the construction bellow, for example, with multiple criteria:

```<code>ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=4, Criteria1:="=AN6b" _
    , Operator:=xlOr, Criteria2:="=TOTAIS"`
</code>```

So, what am I doing wrong, or what should I do that I am not aware of?
Edit: Here goes the full code

```<code>Sub Filter()
    Dim subBacia, encarregado As String
    Dim bm As String
    Dim subStr, encStr, bmStr As String

    'Application.Calculation = xlCalculationManual
    'Application.ScreenUpdating = False

    Sheets("Resumo").Select
    encarregado = Range("T3")
    subBacia = Range("T5")
    bm = Range("T4")
    Const QUOTE = """"
    On Error Resume Next

    If encarregado = "TODOS" And bm = "TODOS" And subBacia = "TODOS" Then
        Sheets("Dem. Rede").Select
        ActiveSheet.ShowAllData
        Sheets("Dem. Interceptor").Select
        ActiveSheet.ShowAllData
        Sheets("Dem.Ramal").Select
        ActiveSheet.ShowAllData
    Else
        If encarregado = "TODOS" Then
            encStr = """<>"""
        Else
            encStr = """=" & encarregado & QUOTE & " , Operator:=xlOr, Criteria2:=" & QUOTE & "=TOTAIS" & QUOTE & ""
        End If
        If bm = "TODOS" Then
            bmStr = """<>"""
        Else
            bmStr = """=" & bm & QUOTE & " , Operator:=xlOr, Criteria2:=" & QUOTE & "=TOTAIS" & QUOTE & ""
        End If
        If subBacia = "TODOS" Then
            subStr = """<>"""
        Else
            subStr = """=" & subBacia & QUOTE & " , Operator:=xlOr, Criteria2:=" & QUOTE & "=TOTAIS" & QUOTE & ""
        End If
        Debug.Print encStr
        Debug.Print bmStr
        Debug.Print subStr
        Sheets("Dem. Rede").Select
            ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=2, Criteria1:=bmStr
            ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=3, Criteria1:=encStr
            ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=4, Criteria1:=subStr
        Sheets("Dem. Interceptor").Select
            ActiveSheet.Range("$A$12:$EM$137").AutoFilter Field:=2, Criteria1:=bmStr
            ActiveSheet.Range("$A$12:$EM$137").AutoFilter Field:=4, Criteria1:=encStr
            ActiveSheet.Range("$A$12:$EM$137").AutoFilter Field:=3, Criteria1:=subStr
        Sheets("Dem.Ramal").Select
            ActiveSheet.Range("$B$11:$Z$1214").AutoFilter Field:=3, Criteria1:=bmStr
            ActiveSheet.Range("$B$11:$Z$1214").AutoFilter Field:=2, Criteria1:=encStr
            ActiveSheet.Range("$B$11:$Z$1214").AutoFilter Field:=1, Criteria1:=subStr
        Sheets("Cadastro Ramal").Select
            ActiveSheet.Range("$A$9:$K$841").AutoFilter Field:=2, Criteria1:=bmStr
    End If

    'Application.Calculation = xlCalculationAutomatic
    'Application.ScreenUpdating = True

End Sub
</code>```

Edit: BTW the Debug.Print is returning for example: "=9" , Operator:=xlOr, Criteria2:="=TOTAIS"

or simply "<>"

And it is exactly the way it should, but, it seems I can't concatenate the string in the code the way I hoped for.

答: Unless you can show otherwise, I don't think you can make VBA interpret your string as a parameter list. I haven't understood what you're trying to save by this method.</p>

Body:
I was trying to get a string to work with a code where I automate multiple tabs to be filtered by the same criteria, for a sheet that gets the subtotal out of other sheets.

So, I did some If and Elses to check for some criteria and try to make the filtering after this analysis, instead of having to do multiple AutoFilters withing multiple Ifs.

So, the part bellow works just fine, it is making the string (subStr) accordingly

If subBacia = "TODOS" Then
    subStr = """<>"""
Else
    subStr = """=" & subBacia & QUOTE & " , Operator:=xlOr, Criteria2:=" & QUOTE & "=TOTAIS" & QUOTE & ""
End If

But this part, that I am avoiding to do multiple ifs for, is not working:

ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=4, Criteria1:=subStr

My idea was that it would end up as the construction bellow, for example, with multiple criteria:

ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=4, Criteria1:="=AN6b" _
    , Operator:=xlOr, Criteria2:="=TOTAIS"`

So, what am I doing wrong, or what should I do that I am not aware of?
Edit: Here goes the full code

Sub Filter()
    Dim subBacia, encarregado As String
    Dim bm As String
    Dim subStr, encStr, bmStr As String

    'Application.Calculation = xlCalculationManual
    'Application.ScreenUpdating = False

    Sheets("Resumo").Select
    encarregado = Range("T3")
    subBacia = Range("T5")
    bm = Range("T4")
    Const QUOTE = """"
    On Error Resume Next

    If encarregado = "TODOS" And bm = "TODOS" And subBacia = "TODOS" Then
        Sheets("Dem. Rede").Select
        ActiveSheet.ShowAllData
        Sheets("Dem. Interceptor").Select
        ActiveSheet.ShowAllData
        Sheets("Dem.Ramal").Select
        ActiveSheet.ShowAllData
    Else
        If encarregado = "TODOS" Then
            encStr = """<>"""
        Else
            encStr = """=" & encarregado & QUOTE & " , Operator:=xlOr, Criteria2:=" & QUOTE & "=TOTAIS" & QUOTE & ""
        End If
        If bm = "TODOS" Then
            bmStr = """<>"""
        Else
            bmStr = """=" & bm & QUOTE & " , Operator:=xlOr, Criteria2:=" & QUOTE & "=TOTAIS" & QUOTE & ""
        End If
        If subBacia = "TODOS" Then
            subStr = """<>"""
        Else
            subStr = """=" & subBacia & QUOTE & " , Operator:=xlOr, Criteria2:=" & QUOTE & "=TOTAIS" & QUOTE & ""
        End If
        Debug.Print encStr
        Debug.Print bmStr
        Debug.Print subStr
        Sheets("Dem. Rede").Select
            ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=2, Criteria1:=bmStr
            ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=3, Criteria1:=encStr
            ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=4, Criteria1:=subStr
        Sheets("Dem. Interceptor").Select
            ActiveSheet.Range("$A$12:$EM$137").AutoFilter Field:=2, Criteria1:=bmStr
            ActiveSheet.Range("$A$12:$EM$137").AutoFilter Field:=4, Criteria1:=encStr
            ActiveSheet.Range("$A$12:$EM$137").AutoFilter Field:=3, Criteria1:=subStr
        Sheets("Dem.Ramal").Select
            ActiveSheet.Range("$B$11:$Z$1214").AutoFilter Field:=3, Criteria1:=bmStr
            ActiveSheet.Range("$B$11:$Z$1214").AutoFilter Field:=2, Criteria1:=encStr
            ActiveSheet.Range("$B$11:$Z$1214").AutoFilter Field:=1, Criteria1:=subStr
        Sheets("Cadastro Ramal").Select
            ActiveSheet.Range("$A$9:$K$841").AutoFilter Field:=2, Criteria1:=bmStr
    End If

    'Application.Calculation = xlCalculationAutomatic
    'Application.ScreenUpdating = True

End Sub

Edit: BTW the Debug.Print is returning for example: "=9" , Operator:=xlOr, Criteria2:="=TOTAIS"

or simply "<>"

And it is exactly the way it should, but, it seems I can't concatenate the string in the code the way I hoped for.


问:
AngularJS possible unhandled rejection when using ui-router
After I have changed from ngRoute to angular-ui-router the console shows always 4 errors stating: Possibly unhandled rejection: {}

I did not noticed any "problem" in the behavior of the application I am building, but I would like to get rid of it.

Any idea what does it mean and how to solve it?

Here an screenshot:

答: Resolve the promise with false if you are trying to abort a transition.</p>


问:
CloudWatch custom metrics not working as expected
I had already created 7 other metrics based on some log files I send to CloudWatch with no problems.

Some time ago we had a problem with MongoDB connection, and I identified that through logs, so I'd like to create a Metric, so that I can create an Alarm based on it. I did create the Metric, but (of course) there are no data being fed into that Metic, because no more "MongoError" messages exists.

But does that also mean that I can't even access the Metric to create the Alarm? Because this is what is happening right now. The Metric cannot be seen anywhere, only in the "Filters" section of the Logs, which won't allow me to create Alarms or create graphics or anything.

I have already posted this on AWS forums but that usually doesn't help.

答:
An Amazon CloudWatch custom metric is only created when data is stored against the custom metric. Therefore, you'll need to push a data value to make appear and then you will be able to create an alarm.

You can push some data to CloudWatch with the AWS Command-Line Interface (CLI), eg:

```<code>aws cloudwatch put-metric-data --namespace MongoDB --metric-name errors --value 0
</code>```

Body:
An Amazon CloudWatch custom metric is only created when data is stored against the custom metric. Therefore, you'll need to push a data value to make appear and then you will be able to create an alarm.

You can push some data to CloudWatch with the AWS Command-Line Interface (CLI), eg:

aws cloudwatch put-metric-data --namespace MongoDB --metric-name errors --value 0


问:
Git commit to common submodule (master branch)
I've two or more projects (let's call them ProjectFoo and ProjectBar) having some common code that I put in a submodule.

My understanding is that if I commit changes to a submodule from within ProjectFoo it'll be in a detached head that only all ProjectFoo clones can see:

```<code>(master) $ cd ProjectFooBarCommoneSubmodule/
(master) $ git commit -am "Common code fix."
(56f21fb0...) $ git push
Everything up-to-date
</code>```

That's probably because the master branch hasn't changed. I could probably do something like git checkout master && git merge Everything up-to-date but that seem pretty ugly. May be a git reset --hard master would do the same but it seems even uglier.

How to have a common code shared by project, updated from within those projects using it? In other words, committing to that submodule should update all various repositories (repositories, not just clones) that use this same submodule.

---- EDIT ----

Visibly my checked-out repository was messed up and broken. It should have worked right from the start like that (on ProjectFoo in this example):

```<code>(master) $ cd ProjectFooBarCommoneSubmodule/
(master) $ git commit -am "Common code fix."
(master) $ git push
....
   fbfdd71..0acce63  master -> master
(master) $ cd ..
(master) $ git add ProjectFooBarCommoneSubmodule
(master) $ git commit -m "Submodule update."
</code>```

Then to get that change from on other projects, like ProjectBar:

```<code>(master) $ cd ProjectFooBarCommoneSubmodule/
(master) $ git pull
</code>```

Would update to the latest common code. A git checkout master may be required if it's on a detached head.

答:
I just do:

git submodule foreach git push -u origin master

Body:
I've two or more projects (let's call them ProjectFoo and ProjectBar) having some common code that I put in a submodule.

My understanding is that if I commit changes to a submodule from within ProjectFoo it'll be in a detached head that only all ProjectFoo clones can see:

(master) $ cd ProjectFooBarCommoneSubmodule/
(master) $ git commit -am "Common code fix."
(56f21fb0...) $ git push
Everything up-to-date

That's probably because the master branch hasn't changed. I could probably do something like git checkout master && git merge Everything up-to-date but that seem pretty ugly. May be a git reset --hard master would do the same but it seems even uglier.

How to have a common code shared by project, updated from within those projects using it? In other words, committing to that submodule should update all various repositories (repositories, not just clones) that use this same submodule.

---- EDIT ----

Visibly my checked-out repository was messed up and broken. It should have worked right from the start like that (on ProjectFoo in this example):

(master) $ cd ProjectFooBarCommoneSubmodule/
(master) $ git commit -am "Common code fix."
(master) $ git push
....
   fbfdd71..0acce63  master -> master
(master) $ cd ..
(master) $ git add ProjectFooBarCommoneSubmodule
(master) $ git commit -m "Submodule update."

Then to get that change from on other projects, like ProjectBar:

(master) $ cd ProjectFooBarCommoneSubmodule/
(master) $ git pull

Would update to the latest common code. A git checkout master may be required if it's on a detached head.


问:
jqgrid hidden columns contribute to row height calculation
I have create a jqgrid and a few of the columns are hidden. The css attribute

```<code>.ui-jqgrid tr.jqgrow td {
white-space: normal !important;
}
</code>```

is used to take care for overflowing texts. Row height is set to 'auto'. The columns are hidden using hidden:"true" attribute.

Now, one of the hidden column contains large text which making the row height larger. How can I make sure that the row height is computed only based on the displayed column contents?

Looking forward for your help. Thanks in advance.

Now, if I reduce the text length in the hidden column, it reduces the height of the row as shown below.

How can I achieve the height as in second screenshot so that the hidden column contents does not affect row height?

答:
I used the hidden property in colModel as:

```<code>hidden:"true"
</code>```

When I changed it to:

```<code>hidden:true
</code>```

It works! Because, the data rows for hidden columns now have the style="display:none;".

Thanks!

Body:
I have create a jqgrid and a few of the columns are hidden. The css attribute

.ui-jqgrid tr.jqgrow td {
white-space: normal !important;
}

is used to take care for overflowing texts. Row height is set to 'auto'. The columns are hidden using hidden:"true" attribute.

Now, one of the hidden column contains large text which making the row height larger. How can I make sure that the row height is computed only based on the displayed column contents?

Looking forward for your help. Thanks in advance.

Now, if I reduce the text length in the hidden column, it reduces the height of the row as shown below.

How can I achieve the height as in second screenshot so that the hidden column contents does not affect row height?

Body:
I used the hidden property in colModel as:

hidden:"true"

When I changed it to:

hidden:true

It works! Because, the data rows for hidden columns now have the style="display:none;".

Thanks!


问:
Conditional where statement in T-SQL
I've got a table that returns the history of a value, as well as the current one, each with a date.

The oldest date is the main record.  If the value is changed, a new record is created, with the old value, and the main record is updated with the new value.  If this happens again, a third record is created, which contains the now old value.

So if the value starts at 4, changes to 2, then again changes to 1.  The records will go

```<code>1
4
2
</code>```

I'm currently creating an inner join on the table to itself as follows, which gets the max date of the 3 above records, which would be 2.. The actual value I need is the 4.  The easiest way to tell if a record is a historical one is that the TriageEndDateTime is NULL.

```<code>INNER JOIN (SELECT EmergencyAttendanceId,MIN(SourceCreateDateTime) as Max_Date
                FROM FactEmergencyAttendanceTriageDetail
                GROUP BY EmergencyAttendanceId) AS EAiD
                ON EAiD.EmergencyAttendanceId = FactEmergencyAttendanceTriageDetail.EmergencyAttendanceId
                AND EAiD.Max_Date = FactEmergencyAttendanceTriageDetail.SourceCreateDateTime
</code>```

What I need to do is select the second record, but only if it exists.  So something along the lines of this.

```<code> SELECT EmergencyAttendanceId,MIN(SourceCreateDateTime) as Max_Date
    FROM FactEmergencyAttendanceTriageDetail
    WHERE IF COUNT(EmergencyAttendanceId) > 1 THEN TriageEndDateTime Is NULL ELSE NOT NULL
    GROUP BY EmergencyAttendanceId
    inside the INNER JOIN.
</code>```

Can anyone help me with this?

Sample data

In the above case, record 2 is the one I'm after.

答:
Use CASE in place of your pseudo-code:

```<code>WHERE TriageEndDateTime =
    CASE WHEN EmergencyAttendanceId > 1 THEN NULL ELSE NOT NULL END
</code>```

Title: Conditional where statement in T-SQL

Body:
I've got a table that returns the history of a value, as well as the current one, each with a date.

The oldest date is the main record.  If the value is changed, a new record is created, with the old value, and the main record is updated with the new value.  If this happens again, a third record is created, which contains the now old value.

So if the value starts at 4, changes to 2, then again changes to 1.  The records will go

1
4
2

I'm currently creating an inner join on the table to itself as follows, which gets the max date of the 3 above records, which would be 2.. The actual value I need is the 4.  The easiest way to tell if a record is a historical one is that the TriageEndDateTime is NULL.

INNER JOIN (SELECT EmergencyAttendanceId,MIN(SourceCreateDateTime) as Max_Date
                FROM FactEmergencyAttendanceTriageDetail
                GROUP BY EmergencyAttendanceId) AS EAiD
                ON EAiD.EmergencyAttendanceId = FactEmergencyAttendanceTriageDetail.EmergencyAttendanceId
                AND EAiD.Max_Date = FactEmergencyAttendanceTriageDetail.SourceCreateDateTime

What I need to do is select the second record, but only if it exists.  So something along the lines of this.

 SELECT EmergencyAttendanceId,MIN(SourceCreateDateTime) as Max_Date
    FROM FactEmergencyAttendanceTriageDetail
    WHERE IF COUNT(EmergencyAttendanceId) > 1 THEN TriageEndDateTime Is NULL ELSE NOT NULL
    GROUP BY EmergencyAttendanceId
    inside the INNER JOIN.

Can anyone help me with this?

Sample data

In the above case, record 2 is the one I'm after.

Body:
Use CASE in place of your pseudo-code:

WHERE TriageEndDateTime =
    CASE WHEN EmergencyAttendanceId > 1 THEN NULL ELSE NOT NULL END


问:
How to detect that a scroll bar knob is being dragged by the user
I have (old...) code that updates the scrollbar position and min-max values in the background with SetScrollRange() but this code should not run while the user is dragging the scrollbar knob as it makes the knob visually jump back to the original position and then jumps back to the user's selected position when he drags or releases the mouse.

Is there some easy way to detect that the dragging is going on?

答:
When the user is dragging around the scrollbar's thumb, the scrollbar's owner window receives WM_VSCROLL (vertical) or WM_HSCROLL (horizontal) messages (depending on the orientation of the scrollbar), where the lo-word of the wParam value is set to SB_THUMBTRACK and the hi-word is set to the new position.

When the user releases the thumb, the owner window receives two final WM_(V|H)SCROLL messages:

the first message has the lo-word of the wParam value set to SB_THUMBPOSITION and the hi-word set to the new position.

the second message has the lo-word of the wParam set to TB_ENDTRACK.

You can subclass the UI control that owns the scrollbar to intercept those messages.  When you see any WM_(V|H)SCROLL messages, don't make updates to the scrollbar until you see a TB_ENDTRACK notification.


问:
Find the section or page of a VBA controls object
How can I identify if a controls object (such as acTextBox) is member of a pages collection in VBA?

When a control object has the focus, a function is called to move the focus to the next control.tabindex based on the type of key which is used. I managed to do this with Sendkeys "{TAB}", but I want to change this since this method constantly disables NUMLOCK on the keyboard.

So far the function below works, but the procedure considers all controls in a form. It should only consider the controls within the same section or page where the function is called from. To accomplish this I need to know if the active control is located within a page and/or section and if it is, the name or index of this page/section. I cannot find the code to do this.

```<code>Public Function GotoNextTab()
    Dim ctlNext, ctlCurrent As Control
    Dim frmCurrent As Form
    Dim lngNextTab As Long
    Set frmCurrent = Screen.Activeform
    Set ctlCurrent = Forms(frmCurrent.Name).ActiveControl

    lngNextTab = Val(ctlCurrent.TabIndex) + 1

    Do Until lngNextTab = frmCurrent.Controls.Count
        For Each ctlNext In frmCurrent.Controls
            Select Case ctlNext.ControlType
                Case acCheckBox, _
                     acComboBox, _
                     acCommandButton, _
                     acListBox, _
                     acOptionButton, _
                     acSubform, _
                     acTabCtl, _
                     acTextBox, _
                     acToggleButton
                        If ctlNext.TabIndex = lngNextTab Then
                            If ctlNext.TabStop = True Then
                                'Make sure that the focus can be set here!
                                If ctlNext.Visible = True And ctlNext.Enabled = True Then
                                    ctlNext.SetFocus
                                    Exit Function
                                Else
                                    'Focus could not be moved, so increase lngNextTab
                                    lngNextTab = lngNextTab + 1
                                End If
                            Else
                                'This was the last tab, so exit
                                Exit Function
                            End If
                        End If
            End Select
        Next ctlNext
    Loop
End Function
</code>```

答:
Thank you for your answer, this helped me in the right direction. I discovered that the parent property always refers to the control up one level (which is in this case the Page object). I still have to insert a feature to return to the first available control within the parent controls collection when the last control is reached. So far it gave not the result I wanted, so I will stick with the procedure as it is now.</p>

```<code>Private Sub Form_Load()
    KeyPreview = True
End Sub

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    Dim ctl As Control
    If KeyCode = vbKeyReturn Then
        'Disregard textboxes with multiple lines
        Set ctl = Me.ActiveControl
        If ctl.ControlType = acTextBox Then
            If ctl.EnterKeyBehavior Then
                Exit Sub
            End If
        End If
        GotoNextTab
    End If
End Sub

Public Function GotoNextTab()
' This function will move the focus to the next control if
' a) This control is a specified type
' b) The control is visible and enabled
' c) The control has a tabstop set to true
'
' If the controls are within a page (TabControl), the focus is cycled within the controls on that page.
' The function disregards sections as it is assumed that there is no need to cycle controls on a form header or footer
' The focus does not cycle within subforms.

On Error Resume Next

    Dim ctlNext as Control
    Dim ctlCurrent As Control
    Dim frmCurrent As Form
    Dim lngNextTab As Long
    Set frmCurrent = Screen.Activeform
    Set ctlCurrent = Forms(frmCurrent.Name).ActiveControl
    If ctlCurrent.Parent.ControlType = acOptionGroup Then
        Set ctlCurrent = ctlCurrent.Parent
    End If
    lngNextTab = ctlCurrent.TabIndex

    Do Until lngNextTab > ctlCurrent.Parent.Controls.Count
        lngNextTab = lngNextTab + 1
        For Each ctlNext In ctlCurrent.Parent.Controls
            Select Case ctlNext.ControlType
                Case acCheckBox, _
                    acComboBox, _
                    acCommandButton, _
                    acListBox, _
                    acSubform, _
                    acTabCtl, _
                    acTextBox, _
                    acToggleButton, _
                    acOptionGroup
                        If ctlNext.TabIndex = lngNextTab Then
                            'Make sure that the focus can be set here!
                            If ctlNext.TabStop = True And ctlNext.Visible = True And ctlNext.Enabled = True Then
                                ctlNext.SetFocus
                                Exit Function
                            Else
                                Exit For 'restart for/next and search the next value
                            End If
                        End If
            End Select
        Next ctlNext
    Loop
End Function
</code>```

Body:
How can I identify if a controls object (such as acTextBox) is member of a pages collection in VBA?

When a control object has the focus, a function is called to move the focus to the next control.tabindex based on the type of key which is used. I managed to do this with Sendkeys "{TAB}", but I want to change this since this method constantly disables NUMLOCK on the keyboard.

So far the function below works, but the procedure considers all controls in a form. It should only consider the controls within the same section or page where the function is called from. To accomplish this I need to know if the active control is located within a page and/or section and if it is, the name or index of this page/section. I cannot find the code to do this.

Public Function GotoNextTab()
    Dim ctlNext, ctlCurrent As Control
    Dim frmCurrent As Form
    Dim lngNextTab As Long
    Set frmCurrent = Screen.Activeform
    Set ctlCurrent = Forms(frmCurrent.Name).ActiveControl

    lngNextTab = Val(ctlCurrent.TabIndex) + 1

    Do Until lngNextTab = frmCurrent.Controls.Count
        For Each ctlNext In frmCurrent.Controls
            Select Case ctlNext.ControlType
                Case acCheckBox, _
                     acComboBox, _
                     acCommandButton, _
                     acListBox, _
                     acOptionButton, _
                     acSubform, _
                     acTabCtl, _
                     acTextBox, _
                     acToggleButton
                        If ctlNext.TabIndex = lngNextTab Then
                            If ctlNext.TabStop = True Then
                                'Make sure that the focus can be set here!
                                If ctlNext.Visible = True And ctlNext.Enabled = True Then
                                    ctlNext.SetFocus
                                    Exit Function
                                Else
                                    'Focus could not be moved, so increase lngNextTab
                                    lngNextTab = lngNextTab + 1
                                End If
                            Else
                                'This was the last tab, so exit
                                Exit Function
                            End If
                        End If
            End Select
        Next ctlNext
    Loop
End Function

Body:
Thank you for your answer, this helped me in the right direction. I discovered that the parent property always refers to the control up one level (which is in this case the Page object). I still have to insert a feature to return to the first available control within the parent controls collection when the last control is reached. So far it gave not the result I wanted, so I will stick with the procedure as it is now.

Private Sub Form_Load()
    KeyPreview = True
End Sub

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    Dim ctl As Control
    If KeyCode = vbKeyReturn Then
        'Disregard textboxes with multiple lines
        Set ctl = Me.ActiveControl
        If ctl.ControlType = acTextBox Then
            If ctl.EnterKeyBehavior Then
                Exit Sub
            End If
        End If
        GotoNextTab
    End If
End Sub

Public Function GotoNextTab()
' This function will move the focus to the next control if
' a) This control is a specified type
' b) The control is visible and enabled
' c) The control has a tabstop set to true
'
' If the controls are within a page (TabControl), the focus is cycled within the controls on that page.
' The function disregards sections as it is assumed that there is no need to cycle controls on a form header or footer
' The focus does not cycle within subforms.

On Error Resume Next

    Dim ctlNext as Control
    Dim ctlCurrent As Control
    Dim frmCurrent As Form
    Dim lngNextTab As Long
    Set frmCurrent = Screen.Activeform
    Set ctlCurrent = Forms(frmCurrent.Name).ActiveControl
    If ctlCurrent.Parent.ControlType = acOptionGroup Then
        Set ctlCurrent = ctlCurrent.Parent
    End If
    lngNextTab = ctlCurrent.TabIndex

    Do Until lngNextTab > ctlCurrent.Parent.Controls.Count
        lngNextTab = lngNextTab + 1
        For Each ctlNext In ctlCurrent.Parent.Controls
            Select Case ctlNext.ControlType
                Case acCheckBox, _
                    acComboBox, _
                    acCommandButton, _
                    acListBox, _
                    acSubform, _
                    acTabCtl, _
                    acTextBox, _
                    acToggleButton, _
                    acOptionGroup
                        If ctlNext.TabIndex = lngNextTab Then
                            'Make sure that the focus can be set here!
                            If ctlNext.TabStop = True And ctlNext.Visible = True And ctlNext.Enabled = True Then
                                ctlNext.SetFocus
                                Exit Function
                            Else
                                Exit For 'restart for/next and search the next value
                            End If
                        End If
            End Select
        Next ctlNext
    Loop
End Function