答:
Is there a reason you cannot use the split function and then map the function to the column?

As per the first example, this will work:

```<code>def word_scrape(whole_string):
    outside_v = whole_string.split(" v ")
    first_word = outside_v[0].split(" ")[0]
    last_word = outside_v[1].split(" ")[1]
    return first_word + " v " + last_word

for i,text in enumerate(df.ix[:,'text']):
    df.ix[i,'text'] = word_scrape(text)
</code>```

for fault tolerance for single word entries, use:

```<code>def word_scrape(whole_string):
    try:
        outside_v = whole_string.split(" v ")
        first_word = outside_v[0].split(" ")[0]
        last_word = outside_v[1].split(" ")[1]
        return first_word + " v " + last_word
    except:
        outside_v = whole_string.split(" v ")
        first_word = outside_v[0].split(" ")[0]
        last_word = outside_v[1].split(" ")[0]
        return first_word + " v " + last_word

for i,text in enumerate(df.ix[:,'text']):
    df.ix[i,'text'] = word_scrape(text)
</code>```

As per the second example, this will work:

```<code>def word_scrape(whole_string):
    outside_v = whole_string.split(" v ")
    first_word = outside_v[0].split(" ")[0]
    last_word = outside_v[1].split(" ")[0]
    return first_word + " v " + last_word

for i,text in enumerate(df.ix[:,'text']):
    df.ix[i,'text'] = word_scrape(text)
</code>```

Title: How to get very first word before and after 'text'

Body:
Is there a reason you cannot use the split function and then map the function to the column?

As per the first example, this will work:

def word_scrape(whole_string):
    outside_v = whole_string.split(" v ")
    first_word = outside_v[0].split(" ")[0]
    last_word = outside_v[1].split(" ")[1]
    return first_word + " v " + last_word

for i,text in enumerate(df.ix[:,'text']):
    df.ix[i,'text'] = word_scrape(text)

for fault tolerance for single word entries, use:

def word_scrape(whole_string):
    try:
        outside_v = whole_string.split(" v ")
        first_word = outside_v[0].split(" ")[0]
        last_word = outside_v[1].split(" ")[1]
        return first_word + " v " + last_word
    except:
        outside_v = whole_string.split(" v ")
        first_word = outside_v[0].split(" ")[0]
        last_word = outside_v[1].split(" ")[0]
        return first_word + " v " + last_word

for i,text in enumerate(df.ix[:,'text']):
    df.ix[i,'text'] = word_scrape(text)

As per the second example, this will work:

def word_scrape(whole_string):
    outside_v = whole_string.split(" v ")
    first_word = outside_v[0].split(" ")[0]
    last_word = outside_v[1].split(" ")[0]
    return first_word + " v " + last_word

for i,text in enumerate(df.ix[:,'text']):
    df.ix[i,'text'] = word_scrape(text)


来源: stackexchange

问:
Not able to receive an attachment from Skype in BotFramework
On BotFramework (NodeJS), I was trying to replicate the demo available at https://learn.microsoft.com/en-us/bot-framework/nodejs/bot-builder-nodejs-send-receive-attachments . It actually works well.

Code in case ms article change:

```<code>// Create your bot with a function to receive messages from the user
var bot = new builder.UniversalBot(connector, function (session) {
    var msg = session.message;
    if (msg.attachments && msg.attachments.length > 0) {
     // Echo back attachment
     var attachment = msg.attachments[0];
        session.send({
            text: "You sent:",
            attachments: [
                {
                    contentType: attachment.contentType,
                    contentUrl: attachment.contentUrl,
                    name: attachment.name
                }
            ]
        });
    } else {
        // Echo back users text
        session.send("You said: %s", session.message.text);
    }
});
</code>```

However, the problem I am facing is that when I do a call from Skype (Normal), I receive an error message:

```<code>2017-12-07T02:16:15.815Z Error: POST to 'https://smba.trafficmanager.net/apis/v3/conversations/<My Conversation>/activities' failed: [400] Bad Request
    at Request._callback (/app/node_modules/botbuilder/lib/bots/ChatConnector.js:545:46)
    at Request.self.callback (/app/node_modules/request/request.js:186:22)
    at emitTwo (events.js:126:13)
    at Request.emit (events.js:214:7)
    at Request.<anonymous> (/app/node_modules/request/request.js:1163:10)
    at emitOne (events.js:116:13)
    at Request.emit (events.js:211:7)
    at IncomingMessage.<anonymous> (/app/node_modules/request/request.js:1085:12)
    at Object.onceWrapper (events.js:313:30)
    at emitNone (events.js:111:20)
</code>```

Any ideas?

[Update: It happens only when I create the attachment response. So I expect that's where I have an issue]

答:
Actually the code on the MS Website is not up-to-date (in a way).

If I follow the code visible at : https://github.com/Microsoft/BotBuilder-Samples/tree/master/Node/core-ReceiveAttachment

By example, I can receive the attachment and save it somewhere on a public folder. Once completed, then I can send back the "public" URL as attachment and then it works.

ContentLicense: CC BY-SA 3.0

Body:
On BotFramework (NodeJS), I was trying to replicate the demo available at https://learn.microsoft.com/en-us/bot-framework/nodejs/bot-builder-nodejs-send-receive-attachments . It actually works well.

Code in case ms article change:

// Create your bot with a function to receive messages from the user
var bot = new builder.UniversalBot(connector, function (session) {
    var msg = session.message;
    if (msg.attachments && msg.attachments.length > 0) {
     // Echo back attachment
     var attachment = msg.attachments[0];
        session.send({
            text: "You sent:",
            attachments: [
                {
                    contentType: attachment.contentType,
                    contentUrl: attachment.contentUrl,
                    name: attachment.name
                }
            ]
        });
    } else {
        // Echo back users text
        session.send("You said: %s", session.message.text);
    }
});

However, the problem I am facing is that when I do a call from Skype (Normal), I receive an error message:

2017-12-07T02:16:15.815Z Error: POST to 'https://smba.trafficmanager.net/apis/v3/conversations/<My Conversation>/activities' failed: [400] Bad Request
    at Request._callback (/app/node_modules/botbuilder/lib/bots/ChatConnector.js:545:46)
    at Request.self.callback (/app/node_modules/request/request.js:186:22)
    at emitTwo (events.js:126:13)
    at Request.emit (events.js:214:7)
    at Request.<anonymous> (/app/node_modules/request/request.js:1163:10)
    at emitOne (events.js:116:13)
    at Request.emit (events.js:211:7)
    at IncomingMessage.<anonymous> (/app/node_modules/request/request.js:1085:12)
    at Object.onceWrapper (events.js:313:30)
    at emitNone (events.js:111:20)

Any ideas?

[Update: It happens only when I create the attachment response. So I expect that's where I have an issue]


问:
Gulp not compiling but getting error ReferenceError: runSequence is not defined

Question

What should I modify in my code to get these two tasks to build in sequence?

Background

I have never had this problem before with gulp, but now that I want to run two tasks in sequence, it is not working properly. I have two tasks previously set up.

```<code>gulp.task('copyAllFiles', function() {
    //PHP files
    gulp.src('src/*.php')
    .pipe(gulp.dest('dist'));
    //childtheme screenshot
    gulp.src('src/screenshot.png')
    .pipe(gulp.dest('dist'));
});

gulp.task('sass2css', function() {
    return gulp.src('src/sass/**/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('dist'))
});
</code>```

I then added a "build" task to run both

gulpfile.js

```<code>gulp.task('build', function(callback) {
    runSequence(['copyAllFiles', 'sass2css'], callback);
});
</code>```

But now getting this error

```<code>ReferenceError: runSequence is not defined
</code>```

答:
To use runSequence, you'll need to install that dependency and require it into your gulp file:

Install

```<code>npm install --save-dev run-sequence
</code>```

Gulp file

```<code>const runSequence = require('run-sequence');
</code>```

Body:
Question

What should I modify in my code to get these two tasks to build in sequence?

Background

I have never had this problem before with gulp, but now that I want to run two tasks in sequence, it is not working properly. I have two tasks previously set up.

gulp.task('copyAllFiles', function() {
    //PHP files
    gulp.src('src/*.php')
    .pipe(gulp.dest('dist'));
    //childtheme screenshot
    gulp.src('src/screenshot.png')
    .pipe(gulp.dest('dist'));
});

gulp.task('sass2css', function() {
    return gulp.src('src/sass/**/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('dist'))
});

I then added a "build" task to run both

gulpfile.js

gulp.task('build', function(callback) {
    runSequence(['copyAllFiles', 'sass2css'], callback);
});

But now getting this error

ReferenceError: runSequence is not defined

Body:
To use runSequence, you'll need to install that dependency and require it into your gulp file:

Install

npm install --save-dev run-sequence

Gulp file

const runSequence = require('run-sequence');


问:
How can I sort dataframe with str+number
I got a dataframe now and try to sort it by 'No.'
dataframe is like:

```<code>         No.              value1                  value2
 0     NODE11              1654                     14
 1     NODE10              1710                    817
 2      NODE9              1162                     23
 3      NODE8              1883                    198
 4   no match              2303                      0
 5      NODE1              1098                     67
 6      NODE3              1488                     78
 7      NODE2              2426                     49
 8      NODE5              1974                     90
 9      NODE4              1767                     11
 10     NODE7              1708                     26
 11     NODE6              2418                    248
</code>```

I tried:

```<code>df.to_csv('count.csv',index = False)
df = pd.read_csv('count.csv', thousands=',', parse_dates=['No.'])
df = df.sort_values(by=['No.', 'only can on this node'], ascending=[True, False])
df.to_csv('count.csv',index = False)
</code>```

Its work but:

```<code>         No.              value1                 value2
 5      NODE1              1098                     67
 1     NODE10              1710                    817  -------error
 0     NODE11              1654                     14   -------error
 7      NODE2              2426                     49
 6      NODE3              1488                     78
 9      NODE4              1767                     11
 8      NODE5              1974                     90
 11     NODE6              2418                    248
 10     NODE7              1708                     26
 3      NODE8              1883                    198
 2      NODE9              1162                     23
 4   no match              2303                      0
</code>```

I dont know how to sort this dataframe because this sort key is str+number. any ideas? Thanks!

答:
Its sorting it alphabetically like a string
You will want to rename
NODE1 -->  NODE01
NODE2 -->  NODE02
...
NODE9 -->  NODE09
NODE10 --> NODE10

Because NODE1 NODE12 NODE13 NODE1123123 NODE2 NODE3 is sorted alphabetically.

Body:
I got a dataframe now and try to sort it by 'No.'
dataframe is like:

         No.              value1                  value2
 0     NODE11              1654                     14
 1     NODE10              1710                    817
 2      NODE9              1162                     23
 3      NODE8              1883                    198
 4   no match              2303                      0
 5      NODE1              1098                     67
 6      NODE3              1488                     78
 7      NODE2              2426                     49
 8      NODE5              1974                     90
 9      NODE4              1767                     11
 10     NODE7              1708                     26
 11     NODE6              2418                    248

I tried:

df.to_csv('count.csv',index = False)
df = pd.read_csv('count.csv', thousands=',', parse_dates=['No.'])
df = df.sort_values(by=['No.', 'only can on this node'], ascending=[True, False])
df.to_csv('count.csv',index = False)

Its work but:

         No.              value1                 value2
 5      NODE1              1098                     67
 1     NODE10              1710                    817  -------error
 0     NODE11              1654                     14   -------error
 7      NODE2              2426                     49
 6      NODE3              1488                     78
 9      NODE4              1767                     11
 8      NODE5              1974                     90
 11     NODE6              2418                    248
 10     NODE7              1708                     26
 3      NODE8              1883                    198
 2      NODE9              1162                     23
 4   no match              2303                      0

I dont know how to sort this dataframe because this sort key is str+number. any ideas? Thanks!


问:
Why does Rust not recognize that I re-assign to the moved variable inside a closure?
I am having trouble understanding why a particular pattern is not compiling.

Rust recognizes when I move a variable and then reassign to it outside of a closure and I think properly allows the code to compile, but when I try to do the same in a closure that will be run more than once it will not.

```<code>fn main() {
    let mut v = vec![1, 2, 3, 4];
    v.into_iter().fold(0, |a, b| a + b);
    v = vec![1, 2, 3, 4];
    vec![1, 2, 3].into_iter().for_each(|x| {
        v.into_iter().fold(x, |a, b| a + b);
        v = vec![1, 2, 3, 4];
    });
}
</code>```

error[E0507]: cannot move out of captured outer variable in an `FnMut` closure
 --> src/main.rs:6:9
  |
2 |     let mut v = vec![1, 2, 3, 4];
  |         ----- captured outer variable
...
6 |         v.into_iter().fold(x, |a, b| a + b);
  |         ^ cannot move out of captured outer variable in an `FnMut` closure
```

It seems to me that the reassignment to v should satisfy the borrow checker that no variable will be accessed after being moved. Am I missing something?

答:
the reassignment to v should satisfy the borrow checker that no variable will be accessed after being moved

Pay attention to the error message details — there isn't a move to start with:

cannot move out of captured outer variable in an `FnMut` closure
```
</blockquote>

<p>Since there was no move out, it doesn't make sense to move something back in.</p>

<p>Instead, you can replace the value through the mutable reference and consume the old value: </p>

```fn main() {
    let mut v = vec![1, 2, 3, 4];

    vec![1, 2, 3].into_iter().for_each(move |x| {
        let v_old = std::mem::replace(&mut v, vec![1, 2, 3, 4]);
        v_old.into_iter().fold(x, |a, b| a + b);
    });
}
```

Body:
I am having trouble understanding why a particular pattern is not compiling.

Rust recognizes when I move a variable and then reassign to it outside of a closure and I think properly allows the code to compile, but when I try to do the same in a closure that will be run more than once it will not.

fn main() {
    let mut v = vec![1, 2, 3, 4];
    v.into_iter().fold(0, |a, b| a + b);
    v = vec![1, 2, 3, 4];
    vec![1, 2, 3].into_iter().for_each(|x| {
        v.into_iter().fold(x, |a, b| a + b);
        v = vec![1, 2, 3, 4];
    });
}

error[E0507]: cannot move out of captured outer variable in an `FnMut` closure
 --> src/main.rs:6:9
  |
2 |     let mut v = vec![1, 2, 3, 4];
  |         ----- captured outer variable
...
6 |         v.into_iter().fold(x, |a, b| a + b);
  |         ^ cannot move out of captured outer variable in an `FnMut` closure

It seems to me that the reassignment to v should satisfy the borrow checker that no variable will be accessed after being moved. Am I missing something?

Body:
the reassignment to v should satisfy the borrow checker that no variable will be accessed after being moved

Pay attention to the error message details — there isn't a move to start with:

cannot move out of captured outer variable in an `FnMut` closure

Since there was no move out, it doesn't make sense to move something back in.

Instead, you can replace the value through the mutable reference and consume the old value:

fn main() {
    let mut v = vec![1, 2, 3, 4];

    vec![1, 2, 3].into_iter().for_each(move |x| {
        let v_old = std::mem::replace(&mut v, vec![1, 2, 3, 4]);
        v_old.into_iter().fold(x, |a, b| a + b);
    });
}


问:
Django's sitemap framework giving error when using aggregate max function on lastmod
I'm trying to use Django's sitemap framework feature. I've implemented the code and it works with current article objects post_date. However I'm trying to get a more accurate last modification date using the following code and it gives me error. Traceback of error http://dpaste.com/3Z04VH8

Regards.
Thanks for any help

```<code>from django.contrib.sitemaps import Sitemap
from django.db.models import Max
from article.models import Article

class ArticleSitemap(Sitemap):
    changefreq = 'hourly'
    priority = 0.5

    def items(self):
        return Article.objects.all()

    def lastmod(self, obj):
        from post.models import Post
        return Post.objects.filter(article=obj).aggregate(Max('post_date'))
        #return obj.post_date
</code>```

答:
The lastmod method in the Sitemap class needs to return a datetime object. Instead you are returning a dictionary (which is what aggregate will produce) - which is invalid.

You need to fetch the data from inside that dictionary and return that:

```<code>result = Post.objects.filter(article=obj).aggregate(Max('post_date'))
# result will look something like {'post_date__max': Datetime('2017-12-06')}
return result['post_date__max']
</code>```

Body:
I'm trying to use Django's sitemap framework feature. I've implemented the code and it works with current article objects post_date. However I'm trying to get a more accurate last modification date using the following code and it gives me error. Traceback of error http://dpaste.com/3Z04VH8

Regards.
Thanks for any help

from django.contrib.sitemaps import Sitemap
from django.db.models import Max
from article.models import Article

class ArticleSitemap(Sitemap):
    changefreq = 'hourly'
    priority = 0.5

    def items(self):
        return Article.objects.all()

    def lastmod(self, obj):
        from post.models import Post
        return Post.objects.filter(article=obj).aggregate(Max('post_date'))
        #return obj.post_date

Body:
The lastmod method in the Sitemap class needs to return a datetime object. Instead you are returning a dictionary (which is what aggregate will produce) - which is invalid.

You need to fetch the data from inside that dictionary and return that:

result = Post.objects.filter(article=obj).aggregate(Max('post_date'))
# result will look something like {'post_date__max': Datetime('2017-12-06')}
return result['post_date__max']


问:
Remove command-prompt in D?
I'm writing an SDL app in D (therefore I'd like to maintain a high amount of platform-independence), and I'm looking for a way to stop the command prompt opening up release builds. How does one do this?</p>

答:
Call DMD with the option -L-Subsystem:Windows.

Just make sure that your main gets changed to WinMain, with the appropriate arguments.

ContentLicense: CC BY-SA 2.5

Title: Remove command-prompt in D?


问:
MySQL Select Matching Rows With Same Value From 2 Different Items
I have a table with 3 columns (primary key, Col1, Col2). Col1 has an index on it. The table is over 100 million rows so I want to query using the index for speed.

Im trying to search 2 items from Col1 that have having matching values in Col2 but excluding any results that only match 1 of the items.

```<code>Col1  | Col2
------------
item1 | 123
item2 | 492
item3 | 123
item4 | 392
item5 | 588
item1 | 456
item2 | 492
item3 | 039
item4 | 938
item5 | 209
item1 | 456
</code>```

So for example this query:

```<code>SELECT * FROM `table` WHERE `Col1` = 'item1' OR `Col1` = 'item3' group
by Col2
having count(*) > 1
</code>```

Returns:

```<code>item1 | 123
item1 | 456
</code>```

item1 | 123 is correct since it matches both item1 and item3 like I want but I don't want it to return item1 | 456 since it doesn't match both item1 and item3. It's only returning because there are 2 item1's that match it. Any help would be much appreciated.

答:
Use count(distinct):

```<code>SELECT Col2
FROM `table`
WHERE Col1 IN ('item1', 'item3')
GROUP BY Col2
HAVING COUNT(DISTINCT Col1) > 1;
</code>```

Body:
I have a table with 3 columns (primary key, Col1, Col2). Col1 has an index on it. The table is over 100 million rows so I want to query using the index for speed.

Im trying to search 2 items from Col1 that have having matching values in Col2 but excluding any results that only match 1 of the items.

Col1  | Col2
------------
item1 | 123
item2 | 492
item3 | 123
item4 | 392
item5 | 588
item1 | 456
item2 | 492
item3 | 039
item4 | 938
item5 | 209
item1 | 456

So for example this query:

SELECT * FROM `table` WHERE `Col1` = 'item1' OR `Col1` = 'item3' group
by Col2
having count(*) > 1

Returns:

item1 | 123
item1 | 456

item1 | 123 is correct since it matches both item1 and item3 like I want but I don't want it to return item1 | 456 since it doesn't match both item1 and item3. It's only returning because there are 2 item1's that match it. Any help would be much appreciated.

Body:
Use count(distinct):

SELECT Col2
FROM `table`
WHERE Col1 IN ('item1', 'item3')
GROUP BY Col2
HAVING COUNT(DISTINCT Col1) > 1;


问:
How can you create a widget inside an android application? (Use App Widget Host class?)
I need to create an application that contains multiple widgets.  These are not desktop widgets.  I need to be able to interact with these widgets as if they were desktop widgets, but they need to be encased inside a larger application.  (Each widget has it's own functionality and behavior when clicked.)

Is this possible in android?  Or do I need to create an application and create each object that I'd like to behave like a widget actually as a view?

Ex. The parent app is for a car.  Example of "in app" widgets are: oil change history (list of last three oil change dates visible, clicking on a date will open a scan of the receipt, etc.), tire pressure monitor, lap speed history (shows last four laps, pinching and expanding will show more than four), etc.

Can I make each of these objects widgets?  Or do they have to be views inside the app?

Edit: The Android developer's App Widget Host page mentions: "The AppWidgetHost provides the interaction with the AppWidget service for apps, like the home screen, that want to embed app widgets in their UI."

Has anyone created their own App Widget Host or worked directly with this class?

答:
If you want to embed a specific widget in your app, and know the package name and class name:</p>

```<code>public boolean createWidget(View view, String packageName, String className) {
    // Get the list of installed widgets
    AppWidgetProviderInfo newAppWidgetProviderInfo = null;
    List<AppWidgetProviderInfo> appWidgetInfos;
    appWidgetInfos = mAppWidgetManager.getInstalledProviders();
    boolean widgetIsFound = false;
    for(int j = 0; j < appWidgetInfos.size(); j++)
    {
        if (appWidgetInfos.get(j).provider.getPackageName().equals(packageName) && appWidgetInfos.get(j).provider.getClassName().equals(className))
        {
            // Get the full info of the required widget
            newAppWidgetProviderInfo = appWidgetInfos.get(j);
            widgetIsFound = true;
            break;
        }
    }

    if (!widgetIsFound) {
        return false;
    } else {
        // Create Widget
        int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
        AppWidgetHostView hostView = mAppWidgetHost.createView(getApplicationContext(), appWidgetId, newAppWidgetProviderInfo);
        hostView.setAppWidget(appWidgetId, newAppWidgetProviderInfo);

        // Add it to your layout
        LinearLayout widgetLayout = view.findViewById(R.id.widget_view);
        widgetLayout.addView(hostView);

        // And bind widget IDs to make them actually work
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            boolean allowed = mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, newAppWidgetProviderInfo.provider);

            if (!allowed) {
                // Request permission - https://stackoverflow.com/a/44351320/1816603
                Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, newAppWidgetProviderInfo.provider);
                final int REQUEST_BIND_WIDGET = 1987;
                startActivityForResult(intent, REQUEST_BIND_WIDGET);
            }
        }

        return true;
    }
}
</code>```

Body:
If you want to embed a specific widget in your app, and know the package name and class name:

public boolean createWidget(View view, String packageName, String className) {
    // Get the list of installed widgets
    AppWidgetProviderInfo newAppWidgetProviderInfo = null;
    List<AppWidgetProviderInfo> appWidgetInfos;
    appWidgetInfos = mAppWidgetManager.getInstalledProviders();
    boolean widgetIsFound = false;
    for(int j = 0; j < appWidgetInfos.size(); j++)
    {
        if (appWidgetInfos.get(j).provider.getPackageName().equals(packageName) && appWidgetInfos.get(j).provider.getClassName().equals(className))
        {
            // Get the full info of the required widget
            newAppWidgetProviderInfo = appWidgetInfos.get(j);
            widgetIsFound = true;
            break;
        }
    }

    if (!widgetIsFound) {
        return false;
    } else {
        // Create Widget
        int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
        AppWidgetHostView hostView = mAppWidgetHost.createView(getApplicationContext(), appWidgetId, newAppWidgetProviderInfo);
        hostView.setAppWidget(appWidgetId, newAppWidgetProviderInfo);

        // Add it to your layout
        LinearLayout widgetLayout = view.findViewById(R.id.widget_view);
        widgetLayout.addView(hostView);

        // And bind widget IDs to make them actually work
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            boolean allowed = mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, newAppWidgetProviderInfo.provider);

            if (!allowed) {
                // Request permission - https://stackoverflow.com/a/44351320/1816603
                Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, newAppWidgetProviderInfo.provider);
                final int REQUEST_BIND_WIDGET = 1987;
                startActivityForResult(intent, REQUEST_BIND_WIDGET);
            }
        }

        return true;
    }
}


问:
I can't figure out why I'm getting a Cannot add foreign key constraint error
I'm working on a schema for a project and I'm trying to import it to my local host so I can work on writing some queries that will pull info from the database onto a webpage. I'm getting a #1215 - Cannot add foreign key constraint error, and it pertains to the use of cities(city_id) as a foreign key. I'm not sure what the problem is, they're both the same data type (INT) and city_id is the primary key of the cities table. I'm stumped here guys and I'm hoping somebody on here can lend a hand.

EDITED: So I got this working, but that's without the order table which I'll paste below the working schema.

```<code>DROP TABLE IF EXISTS cities;
-- Table for storing cities
create table cities (
    city_id INT(100) NOT NULL AUTO_INCREMENT,
    city_name VARCHAR(32),
    PRIMARY KEY(city_id)
)ENGINE=InnoDB;

DROP TABLE IF EXISTS drivers;
-- table for Drivers registered in lyft database
create table drivers (
    driver_id INT(100) NOT NULL AUTO_INCREMENT,
    fname VARCHAR(32),
    lname VARCHAR(32),
    address VARCHAR(32),
    contactnumber VARCHAR(32),
    driver_city INT(100),
    PRIMARY KEY(driver_id),
    FOREIGN KEY (driver_city) REFERENCES cities(city_id)
)ENGINE=InnoDB;

DROP TABLE IF EXISTS cars;
-- Table for storing cars information in lyft
create table cars (
    car_id INT(100) NOT NULL AUTO_INCREMENT,
    car_name VARCHAR(32),
    car_type VARCHAR(32),
    car_model VARCHAR(32),
    car_licencenumber VARCHAR(32),
    PRIMARY KEY(car_id)
)ENGINE=InnoDB;

DROP TABLE IF EXISTS customers;
-- Table for storing customers using lyft
create table customers (
    c_id INT(100) NOT NULL AUTO_INCREMENT,
    c_fname VARCHAR(32),
    c_lname VARCHAR(32),
    c_city INT(100),
    PRIMARY KEY (c_id),
    FOREIGN KEY (c_city) REFERENCES cities(city_id)
)ENGINE=InnoDB;

DROP TABLE IF EXISTS owns;
--  Table stores which drivers are having which cars
create table owns (
    driver INT(100),
    car INT(100),
    PRIMARY KEY (driver,car),
    FOREIGN KEY (driver) REFERENCES drivers(driver_id) ON DELETE CASCADE,
    FOREIGN KEY (car) REFERENCES cars(car_id) ON DELETE CASCADE
)ENGINE=InnoDB;
</code>```

Table that I cannot add to database is below:

```<code>DROP TABLE IF EXISTS order;
-- Table stores which drivers are driving a customer
create table order (
    driver INT(100),
    customer INT(100),
    city INT(100),
    PRIMARY KEY (driver, customer, city),
    FOREIGN KEY (driver) REFERENCES drivers(driver_id),
    FOREIGN KEY (customer) REFERENCES customers(c_id),
    FOREIGN KEY (city) REFERENCES cities(city_id)
)ENGINE=InnoDB;
</code>```

When trying to add it via phpmyadmin I get the following error:

```<code>Static analysis:

2 errors were found during analysis.

    An expression was expected. (near "ORDER" at position 21)
    Unrecognized keyword. (near "ORDER" at position 21)

SQL query:

DROP TABLE IF EXISTS ORDER

MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER' at line 1
</code>```

FINAL EDIT: I finally figured it out, my problem was that order is a reserved/key word in mysql so that was throwing an error. I changed it to orders and all is well. I'll post the final schema below incase anybody runs into the same trouble as I did.

```<code>DROP TABLE IF EXISTS cities;
-- Table for storing cities
create table cities (
    city_id INT(100) NOT NULL AUTO_INCREMENT,
    city_name VARCHAR(32),
    PRIMARY KEY(city_id)
)ENGINE=InnoDB;

DROP TABLE IF EXISTS drivers;
-- table for Drivers registered in lyft database
create table drivers (
    driver_id INT(100) NOT NULL AUTO_INCREMENT,
    fname VARCHAR(32),
    lname VARCHAR(32),
    address VARCHAR(32),
    contactnumber VARCHAR(32),
    driver_city INT(100),
    PRIMARY KEY(driver_id),
    FOREIGN KEY (driver_city) REFERENCES cities(city_id)
)ENGINE=InnoDB;

DROP TABLE IF EXISTS cars;
-- Table for storing cars information in lyft
create table cars (
    car_id INT(100) NOT NULL AUTO_INCREMENT,
    car_name VARCHAR(32),
    car_type VARCHAR(32),
    car_model VARCHAR(32),
    car_licencenumber VARCHAR(32),
    PRIMARY KEY(car_id)
)ENGINE=InnoDB;

DROP TABLE IF EXISTS customers;
-- Table for storing customers using lyft
create table customers (
    c_id INT(100) NOT NULL AUTO_INCREMENT,
    c_fname VARCHAR(32),
    c_lname VARCHAR(32),
    c_city INT(100),
    PRIMARY KEY (c_id),
    FOREIGN KEY (c_city) REFERENCES cities(city_id)
)ENGINE=InnoDB;

DROP TABLE IF EXISTS owns;
--  Table stores which drivers are having which cars
create table owns (
    driver INT(100),
    car INT(100),
    PRIMARY KEY (driver,car),
    FOREIGN KEY (driver) REFERENCES drivers(driver_id) ON DELETE CASCADE,
    FOREIGN KEY (car) REFERENCES cars(car_id) ON DELETE CASCADE
)ENGINE=InnoDB;

DROP TABLE IF EXISTS orders;
-- Table stores which drivers are driving a customer
create table orders (
    driver INT(100),
    customer INT(100),
    city INT(100),
    PRIMARY KEY (driver, customer, city),
    FOREIGN KEY (driver) REFERENCES drivers(driver_id),
    FOREIGN KEY (customer) REFERENCES customers(c_id),
    FOREIGN KEY (city) REFERENCES cities(city_id)
)ENGINE=InnoDB;
</code>```

答: From the error Cannot resolve table name, I guess you are trying to create table drivers before you create table cities, that means you are referring a table which doesn't exist. So the solution is to create table cities first

Body:
I'm working on a schema for a project and I'm trying to import it to my local host so I can work on writing some queries that will pull info from the database onto a webpage. I'm getting a #1215 - Cannot add foreign key constraint error, and it pertains to the use of cities(city_id) as a foreign key. I'm not sure what the problem is, they're both the same data type (INT) and city_id is the primary key of the cities table. I'm stumped here guys and I'm hoping somebody on here can lend a hand.

EDITED: So I got this working, but that's without the order table which I'll paste below the working schema.

DROP TABLE IF EXISTS cities;
-- Table for storing cities
create table cities (
    city_id INT(100) NOT NULL AUTO_INCREMENT,
    city_name VARCHAR(32),
    PRIMARY KEY(city_id)
)ENGINE=InnoDB;

DROP TABLE IF EXISTS drivers;
-- table for Drivers registered in lyft database
create table drivers (
    driver_id INT(100) NOT NULL AUTO_INCREMENT,
    fname VARCHAR(32),
    lname VARCHAR(32),
    address VARCHAR(32),
    contactnumber VARCHAR(32),
    driver_city INT(100),
    PRIMARY KEY(driver_id),
    FOREIGN KEY (driver_city) REFERENCES cities(city_id)
)ENGINE=InnoDB;

DROP TABLE IF EXISTS cars;
-- Table for storing cars information in lyft
create table cars (
    car_id INT(100) NOT NULL AUTO_INCREMENT,
    car_name VARCHAR(32),
    car_type VARCHAR(32),
    car_model VARCHAR(32),
    car_licencenumber VARCHAR(32),
    PRIMARY KEY(car_id)
)ENGINE=InnoDB;

DROP TABLE IF EXISTS customers;
-- Table for storing customers using lyft
create table customers (
    c_id INT(100) NOT NULL AUTO_INCREMENT,
    c_fname VARCHAR(32),
    c_lname VARCHAR(32),
    c_city INT(100),
    PRIMARY KEY (c_id),
    FOREIGN KEY (c_city) REFERENCES cities(city_id)
)ENGINE=InnoDB;

DROP TABLE IF EXISTS owns;
--  Table stores which drivers are having which cars
create table owns (
    driver INT(100),
    car INT(100),
    PRIMARY KEY (driver,car),
    FOREIGN KEY (driver) REFERENCES drivers(driver_id) ON DELETE CASCADE,
    FOREIGN KEY (car) REFERENCES cars(car_id) ON DELETE CASCADE
)ENGINE=InnoDB;

Table that I cannot add to database is below:

DROP TABLE IF EXISTS order;
-- Table stores which drivers are driving a customer
create table order (
    driver INT(100),
    customer INT(100),
    city INT(100),
    PRIMARY KEY (driver, customer, city),
    FOREIGN KEY (driver) REFERENCES drivers(driver_id),
    FOREIGN KEY (customer) REFERENCES customers(c_id),
    FOREIGN KEY (city) REFERENCES cities(city_id)
)ENGINE=InnoDB;

When trying to add it via phpmyadmin I get the following error:

Static analysis:

2 errors were found during analysis.

    An expression was expected. (near "ORDER" at position 21)
    Unrecognized keyword. (near "ORDER" at position 21)

SQL query:

DROP TABLE IF EXISTS ORDER

MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER' at line 1

FINAL EDIT: I finally figured it out, my problem was that order is a reserved/key word in mysql so that was throwing an error. I changed it to orders and all is well. I'll post the final schema below incase anybody runs into the same trouble as I did.

DROP TABLE IF EXISTS cities;
-- Table for storing cities
create table cities (
    city_id INT(100) NOT NULL AUTO_INCREMENT,
    city_name VARCHAR(32),
    PRIMARY KEY(city_id)
)ENGINE=InnoDB;

DROP TABLE IF EXISTS drivers;
-- table for Drivers registered in lyft database
create table drivers (
    driver_id INT(100) NOT NULL AUTO_INCREMENT,
    fname VARCHAR(32),
    lname VARCHAR(32),
    address VARCHAR(32),
    contactnumber VARCHAR(32),
    driver_city INT(100),
    PRIMARY KEY(driver_id),
    FOREIGN KEY (driver_city) REFERENCES cities(city_id)
)ENGINE=InnoDB;

DROP TABLE IF EXISTS cars;
-- Table for storing cars information in lyft
create table cars (
    car_id INT(100) NOT NULL AUTO_INCREMENT,
    car_name VARCHAR(32),
    car_type VARCHAR(32),
    car_model VARCHAR(32),
    car_licencenumber VARCHAR(32),
    PRIMARY KEY(car_id)
)ENGINE=InnoDB;

DROP TABLE IF EXISTS customers;
-- Table for storing customers using lyft
create table customers (
    c_id INT(100) NOT NULL AUTO_INCREMENT,
    c_fname VARCHAR(32),
    c_lname VARCHAR(32),
    c_city INT(100),
    PRIMARY KEY (c_id),
    FOREIGN KEY (c_city) REFERENCES cities(city_id)
)ENGINE=InnoDB;

DROP TABLE IF EXISTS owns;
--  Table stores which drivers are having which cars
create table owns (
    driver INT(100),
    car INT(100),
    PRIMARY KEY (driver,car),
    FOREIGN KEY (driver) REFERENCES drivers(driver_id) ON DELETE CASCADE,
    FOREIGN KEY (car) REFERENCES cars(car_id) ON DELETE CASCADE
)ENGINE=InnoDB;

DROP TABLE IF EXISTS orders;
-- Table stores which drivers are driving a customer
create table orders (
    driver INT(100),
    customer INT(100),
    city INT(100),
    PRIMARY KEY (driver, customer, city),
    FOREIGN KEY (driver) REFERENCES drivers(driver_id),
    FOREIGN KEY (customer) REFERENCES customers(c_id),
    FOREIGN KEY (city) REFERENCES cities(city_id)
)ENGINE=InnoDB;


问:
calling a getter method from multiple methods in a different class than the getter
I'm in the process of learning Java and trying to use OOP style programming. The problem I'm having is that when I attempt to call a getter method in one class, for another class, it only works within the method that I create an object in and I'm calling from. My question is: Is it possible to call a getter from multiple methods in a different class than the getter method class? If so, how do I go about it?

Thanks!

答:
The class with getter method:

```<code>public class A {
    public void getter(){
       ....
    }
}
</code>```

The class that calls the getter method:

```<code>public class B {

    A a = new A();

    private void callMethod(){
        a.getter();
    }
}
</code>```

If the class that calls the getter method includes the main method, than make the create a with the static keyword: static A a = new A();.

Body:
The class with getter method:

public class A {
    public void getter(){
       ....
    }
}

The class that calls the getter method:

public class B {

    A a = new A();

    private void callMethod(){
        a.getter();
    }
}

If the class that calls the getter method includes the main method, than make the create a with the static keyword: static A a = new A();.


问:
Faster modulus in C/C#?
Is there a trick for creating a faster integer modulus than the standard % operator for particular bases?

For my program, I'd be looking for around 1000-4000 (e.g. n%2048). Is there a quicker way to perform n modulus 2048 than simply: n%2048?

答:
Branchless non-power-of-two modulus is possible by precomputing magic constants at run-time, to implement division using a multiply-add-shift.

This is roughly 2x faster than the built-in modulo operator % on my Intel Core i5.

I'm surprised it's not more dramatic, as x86 CPU div instructions can have latencies as high as 80-90 cycles for 64-bit division on some CPUs, compared to mul at 3 cycles and bitwise ops at 1 cycle each.

Proof of concept and timings shown below. series_len refers to the number of modulus ops performed in series on a single var. That's to prevent the CPU from hiding latencies through parallelization.

```<code>#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>

typedef int32_t s32;
typedef uint32_t u32;
typedef uint64_t u64;

#define NUM_NUMS 1024
#define NUM_RUNS 500
#define MAX_NUM UINT32_MAX
#define MAX_DEN 1024

struct fastdiv {
    u32 mul;
    u32 add;
    s32 shift;
    u32 _odiv;  /* save original divisor for modulo calc */
};

static u32 num[NUM_NUMS];
static u32 den[NUM_NUMS];
static struct fastdiv fd[NUM_NUMS];

/* hash of results to prevent gcc from optimizing out our ops */
static u32 cookie = 0;

/* required for magic constant generation */
u32 ulog2(u32 v) {
    u32 r, shift;
    r =     (v > 0xFFFF) << 4; v >>= r;
    shift = (v > 0xFF  ) << 3; v >>= shift; r |= shift;
    shift = (v > 0xF   ) << 2; v >>= shift; r |= shift;
    shift = (v > 0x3   ) << 1; v >>= shift; r |= shift;
                                            r |= (v >> 1);
    return r;
}

/* generate constants for implementing a division with multiply-add-shift */
void fastdiv_make(struct fastdiv *d, u32 divisor) {
    u32 l, r, e;
    u64 m;

    d->_odiv = divisor;
    l = ulog2(divisor);
    if (divisor & (divisor - 1)) {
        m = 1ULL << (l + 32);
        d->mul = (u32)(m / divisor);
        r = (u32)m - d->mul * divisor;
        e = divisor - r;
        if (e < (1UL << l)) {
            ++d->mul;
            d->add = 0;
        } else {
            d->add = d->mul;
        }
        d->shift = l;
    } else {
        if (divisor == 1) {
            d->mul = 0xffffffff;
            d->add = 0xffffffff;
            d->shift = 0;
        } else {
            d->mul = 0x80000000;
            d->add = 0;
            d->shift = l-1;
        }
    }
}

/* 0: use function that checks for a power-of-2 modulus (speedup for POTs)
 * 1: use inline macro */
#define FASTMOD_BRANCHLESS 0

#define fastdiv(v,d) ((u32)(((u64)(v)*(d)->mul + (d)->add) >> 32) >> (d)->shift)
#define _fastmod(v,d) ((v) - fastdiv((v),(d)) * (d)->_odiv)

#if FASTMOD_BRANCHLESS
#define fastmod(v,d) _fastmod((v),(d))
#else
u32 fastmod(u32 v, struct fastdiv *d) {
    if (d->mul == 0x80000000) {
        return (v & ((1 << d->shift) - 1));
    }
    return _fastmod(v,d);
}
#endif

u32 random32(u32 upper_bound) {
    return arc4random_uniform(upper_bound);
}

u32 random32_range(u32 lower_bound, u32 upper_bound) {
    return random32(upper_bound - lower_bound) + lower_bound;
}

void fill_arrays() {
    int i;
    for (i = 0; i < NUM_NUMS; ++i) {
        num[i] = random32_range(MAX_DEN, MAX_NUM);
        den[i] = random32_range(1, MAX_DEN);
        fastdiv_make(&fd[i], den[i]);
    }
}

void fill_arrays_pot() {
    u32 log_bound, rand_log;
    int i;

    log_bound = ulog2(MAX_DEN);
    for (i = 0; i < NUM_NUMS; ++i) {
        num[i] = random32_range(MAX_DEN, MAX_NUM);
        rand_log = random32(log_bound) + 1;
        den[i] = 1 << rand_log;
        fastdiv_make(&fd[i], den[i]);
    }
}

u64 clock_ns() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec*1000000000 + tv.tv_usec*1000;
}

void use_value(u32 v) {
    cookie += v;
}

int main(int argc, char **arg) {
    u64 builtin_npot_ns;
    u64 builtin_pot_ns;
    u64 branching_npot_ns;
    u64 branching_pot_ns;
    u64 branchless_npot_ns;
    u64 branchless_pot_ns;
    u64 t0, t1;
    u32 v;
    int s, r, i, j;
    int series_len;

    builtin_npot_ns = builtin_pot_ns = 0;
    branching_npot_ns = branching_pot_ns = 0;
    branchless_npot_ns = branchless_pot_ns = 0;

    for (s = 5; s >= 0; --s) {
        series_len = 1 << s;
        for (r = 0; r < NUM_RUNS; ++r) {
            /* built-in NPOT */
            fill_arrays();
            t0 = clock_ns();
            for (i = 0; i < NUM_NUMS; ++i) {
                v = num[i];
                for (j = 0; j < series_len; ++j) {
                    v /= den[i];
                }
                use_value(v);
            }
            t1 = clock_ns();
            builtin_npot_ns += (t1 - t0) / NUM_NUMS;

            /* built-in POT */
            fill_arrays_pot();
            t0 = clock_ns();
            for (i = 0; i < NUM_NUMS; ++i) {
                v = num[i];
                for (j = 0; j < series_len; ++j) {
                    v /= den[i];
                }
                use_value(v);
            }
            t1 = clock_ns();
            builtin_pot_ns += (t1 - t0) / NUM_NUMS;

            /* branching NPOT */
            fill_arrays();
            t0 = clock_ns();
            for (i = 0; i < NUM_NUMS; ++i) {
                v = num[i];
                for (j = 0; j < series_len; ++j) {
                    v = fastmod(v, fd+i);
                }
                use_value(v);
            }
            t1 = clock_ns();
            branching_npot_ns += (t1 - t0) / NUM_NUMS;

            /* branching POT */
            fill_arrays_pot();
            t0 = clock_ns();
            for (i = 0; i < NUM_NUMS; ++i) {
                v = num[i];
                for (j = 0; j < series_len; ++j) {
                    v = fastmod(v, fd+i);
                }
                use_value(v);
            }
            t1 = clock_ns();
            branching_pot_ns += (t1 - t0) / NUM_NUMS;

            /* branchless NPOT */
            fill_arrays();
            t0 = clock_ns();
            for (i = 0; i < NUM_NUMS; ++i) {
                v = num[i];
                for (j = 0; j < series_len; ++j) {
                    v = _fastmod(v, fd+i);
                }
                use_value(v);
            }
            t1 = clock_ns();
            branchless_npot_ns += (t1 - t0) / NUM_NUMS;

            /* branchless POT */
            fill_arrays_pot();
            t0 = clock_ns();
            for (i = 0; i < NUM_NUMS; ++i) {
                v = num[i];
                for (j = 0; j < series_len; ++j) {
                    v = _fastmod(v, fd+i);
                }
                use_value(v);
            }
            t1 = clock_ns();
            branchless_pot_ns += (t1 - t0) / NUM_NUMS;
        }

        builtin_npot_ns /= NUM_RUNS;
        builtin_pot_ns /= NUM_RUNS;
        branching_npot_ns /= NUM_RUNS;
        branching_pot_ns /= NUM_RUNS;
        branchless_npot_ns /= NUM_RUNS;
        branchless_pot_ns /= NUM_RUNS;

        printf("series_len = %d\n", series_len);
        printf("----------------------------\n");
        printf("builtin_npot_ns    : %llu ns\n", builtin_npot_ns);
        printf("builtin_pot_ns     : %llu ns\n", builtin_pot_ns);
        printf("branching_npot_ns  : %llu ns\n", branching_npot_ns);
        printf("branching_pot_ns   : %llu ns\n", branching_pot_ns);
        printf("branchless_npot_ns : %llu ns\n", branchless_npot_ns);
        printf("branchless_pot_ns  : %llu ns\n\n", branchless_pot_ns);
    }
    printf("cookie=%u\n", cookie);
}
</code>```

Results

Intel Core i5 (MacBookAir7,2), macOS 10.11.6, clang 8.0.0

```<code>series_len = 32
----------------------------
builtin_npot_ns    : 218 ns
builtin_pot_ns     : 225 ns
branching_npot_ns  : 115 ns
branching_pot_ns   : 42 ns
branchless_npot_ns : 110 ns
branchless_pot_ns  : 110 ns

series_len = 16
----------------------------
builtin_npot_ns    : 87 ns
builtin_pot_ns     : 89 ns
branching_npot_ns  : 47 ns
branching_pot_ns   : 19 ns
branchless_npot_ns : 45 ns
branchless_pot_ns  : 45 ns

series_len = 8
----------------------------
builtin_npot_ns    : 32 ns
builtin_pot_ns     : 34 ns
branching_npot_ns  : 18 ns
branching_pot_ns   : 10 ns
branchless_npot_ns : 17 ns
branchless_pot_ns  : 17 ns

series_len = 4
----------------------------
builtin_npot_ns    : 15 ns
builtin_pot_ns     : 16 ns
branching_npot_ns  : 8 ns
branching_pot_ns   : 3 ns
branchless_npot_ns : 7 ns
branchless_pot_ns  : 7 ns

series_len = 2
----------------------------
builtin_npot_ns    : 8 ns
builtin_pot_ns     : 7 ns
branching_npot_ns  : 4 ns
branching_pot_ns   : 2 ns
branchless_npot_ns : 2 ns
branchless_pot_ns  : 2 ns
</code>```

Title: Faster modulus in C/C#?

Body:
Branchless non-power-of-two modulus is possible by precomputing magic constants at run-time, to implement division using a multiply-add-shift.

This is roughly 2x faster than the built-in modulo operator % on my Intel Core i5.

I'm surprised it's not more dramatic, as x86 CPU div instructions can have latencies as high as 80-90 cycles for 64-bit division on some CPUs, compared to mul at 3 cycles and bitwise ops at 1 cycle each.

Proof of concept and timings shown below. series_len refers to the number of modulus ops performed in series on a single var. That's to prevent the CPU from hiding latencies through parallelization.

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>

typedef int32_t s32;
typedef uint32_t u32;
typedef uint64_t u64;

#define NUM_NUMS 1024
#define NUM_RUNS 500
#define MAX_NUM UINT32_MAX
#define MAX_DEN 1024

struct fastdiv {
    u32 mul;
    u32 add;
    s32 shift;
    u32 _odiv;  /* save original divisor for modulo calc */
};

static u32 num[NUM_NUMS];
static u32 den[NUM_NUMS];
static struct fastdiv fd[NUM_NUMS];

/* hash of results to prevent gcc from optimizing out our ops */
static u32 cookie = 0;

/* required for magic constant generation */
u32 ulog2(u32 v) {
    u32 r, shift;
    r =     (v > 0xFFFF) << 4; v >>= r;
    shift = (v > 0xFF  ) << 3; v >>= shift; r |= shift;
    shift = (v > 0xF   ) << 2; v >>= shift; r |= shift;
    shift = (v > 0x3   ) << 1; v >>= shift; r |= shift;
                                            r |= (v >> 1);
    return r;
}

/* generate constants for implementing a division with multiply-add-shift */
void fastdiv_make(struct fastdiv *d, u32 divisor) {
    u32 l, r, e;
    u64 m;

    d->_odiv = divisor;
    l = ulog2(divisor);
    if (divisor & (divisor - 1)) {
        m = 1ULL << (l + 32);
        d->mul = (u32)(m / divisor);
        r = (u32)m - d->mul * divisor;
        e = divisor - r;
        if (e < (1UL << l)) {
            ++d->mul;
            d->add = 0;
        } else {
            d->add = d->mul;
        }
        d->shift = l;
    } else {
        if (divisor == 1) {
            d->mul = 0xffffffff;
            d->add = 0xffffffff;
            d->shift = 0;
        } else {
            d->mul = 0x80000000;
            d->add = 0;
            d->shift = l-1;
        }
    }
}

/* 0: use function that checks for a power-of-2 modulus (speedup for POTs)
 * 1: use inline macro */
#define FASTMOD_BRANCHLESS 0

#define fastdiv(v,d) ((u32)(((u64)(v)*(d)->mul + (d)->add) >> 32) >> (d)->shift)
#define _fastmod(v,d) ((v) - fastdiv((v),(d)) * (d)->_odiv)

#if FASTMOD_BRANCHLESS
#define fastmod(v,d) _fastmod((v),(d))
#else
u32 fastmod(u32 v, struct fastdiv *d) {
    if (d->mul == 0x80000000) {
        return (v & ((1 << d->shift) - 1));
    }
    return _fastmod(v,d);
}
#endif

u32 random32(u32 upper_bound) {
    return arc4random_uniform(upper_bound);
}

u32 random32_range(u32 lower_bound, u32 upper_bound) {
    return random32(upper_bound - lower_bound) + lower_bound;
}

void fill_arrays() {
    int i;
    for (i = 0; i < NUM_NUMS; ++i) {
        num[i] = random32_range(MAX_DEN, MAX_NUM);
        den[i] = random32_range(1, MAX_DEN);
        fastdiv_make(&fd[i], den[i]);
    }
}

void fill_arrays_pot() {
    u32 log_bound, rand_log;
    int i;

    log_bound = ulog2(MAX_DEN);
    for (i = 0; i < NUM_NUMS; ++i) {
        num[i] = random32_range(MAX_DEN, MAX_NUM);
        rand_log = random32(log_bound) + 1;
        den[i] = 1 << rand_log;
        fastdiv_make(&fd[i], den[i]);
    }
}

u64 clock_ns() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec*1000000000 + tv.tv_usec*1000;
}

void use_value(u32 v) {
    cookie += v;
}

int main(int argc, char **arg) {
    u64 builtin_npot_ns;
    u64 builtin_pot_ns;
    u64 branching_npot_ns;
    u64 branching_pot_ns;
    u64 branchless_npot_ns;
    u64 branchless_pot_ns;
    u64 t0, t1;
    u32 v;
    int s, r, i, j;
    int series_len;

    builtin_npot_ns = builtin_pot_ns = 0;
    branching_npot_ns = branching_pot_ns = 0;
    branchless_npot_ns = branchless_pot_ns = 0;

    for (s = 5; s >= 0; --s) {
        series_len = 1 << s;
        for (r = 0; r < NUM_RUNS; ++r) {
            /* built-in NPOT */
            fill_arrays();
            t0 = clock_ns();
            for (i = 0; i < NUM_NUMS; ++i) {
                v = num[i];
                for (j = 0; j < series_len; ++j) {
                    v /= den[i];
                }
                use_value(v);
            }
            t1 = clock_ns();
            builtin_npot_ns += (t1 - t0) / NUM_NUMS;

            /* built-in POT */
            fill_arrays_pot();
            t0 = clock_ns();
            for (i = 0; i < NUM_NUMS; ++i) {
                v = num[i];
                for (j = 0; j < series_len; ++j) {
                    v /= den[i];
                }
                use_value(v);
            }
            t1 = clock_ns();
            builtin_pot_ns += (t1 - t0) / NUM_NUMS;

            /* branching NPOT */
            fill_arrays();
            t0 = clock_ns();
            for (i = 0; i < NUM_NUMS; ++i) {
                v = num[i];
                for (j = 0; j < series_len; ++j) {
                    v = fastmod(v, fd+i);
                }
                use_value(v);
            }
            t1 = clock_ns();
            branching_npot_ns += (t1 - t0) / NUM_NUMS;

            /* branching POT */
            fill_arrays_pot();
            t0 = clock_ns();
            for (i = 0; i < NUM_NUMS; ++i) {
                v = num[i];
                for (j = 0; j < series_len; ++j) {
                    v = fastmod(v, fd+i);
                }
                use_value(v);
            }
            t1 = clock_ns();
            branching_pot_ns += (t1 - t0) / NUM_NUMS;

            /* branchless NPOT */
            fill_arrays();
            t0 = clock_ns();
            for (i = 0; i < NUM_NUMS; ++i) {
                v = num[i];
                for (j = 0; j < series_len; ++j) {
                    v = _fastmod(v, fd+i);
                }
                use_value(v);
            }
            t1 = clock_ns();
            branchless_npot_ns += (t1 - t0) / NUM_NUMS;

            /* branchless POT */
            fill_arrays_pot();
            t0 = clock_ns();
            for (i = 0; i < NUM_NUMS; ++i) {
                v = num[i];
                for (j = 0; j < series_len; ++j) {
                    v = _fastmod(v, fd+i);
                }
                use_value(v);
            }
            t1 = clock_ns();
            branchless_pot_ns += (t1 - t0) / NUM_NUMS;
        }

        builtin_npot_ns /= NUM_RUNS;
        builtin_pot_ns /= NUM_RUNS;
        branching_npot_ns /= NUM_RUNS;
        branching_pot_ns /= NUM_RUNS;
        branchless_npot_ns /= NUM_RUNS;
        branchless_pot_ns /= NUM_RUNS;

        printf("series_len = %d\n", series_len);
        printf("----------------------------\n");
        printf("builtin_npot_ns    : %llu ns\n", builtin_npot_ns);
        printf("builtin_pot_ns     : %llu ns\n", builtin_pot_ns);
        printf("branching_npot_ns  : %llu ns\n", branching_npot_ns);
        printf("branching_pot_ns   : %llu ns\n", branching_pot_ns);
        printf("branchless_npot_ns : %llu ns\n", branchless_npot_ns);
        printf("branchless_pot_ns  : %llu ns\n\n", branchless_pot_ns);
    }
    printf("cookie=%u\n", cookie);
}

Results

Intel Core i5 (MacBookAir7,2), macOS 10.11.6, clang 8.0.0

series_len = 32
----------------------------
builtin_npot_ns    : 218 ns
builtin_pot_ns     : 225 ns
branching_npot_ns  : 115 ns
branching_pot_ns   : 42 ns
branchless_npot_ns : 110 ns
branchless_pot_ns  : 110 ns

series_len = 16
----------------------------
builtin_npot_ns    : 87 ns
builtin_pot_ns     : 89 ns
branching_npot_ns  : 47 ns
branching_pot_ns   : 19 ns
branchless_npot_ns : 45 ns
branchless_pot_ns  : 45 ns

series_len = 8
----------------------------
builtin_npot_ns    : 32 ns
builtin_pot_ns     : 34 ns
branching_npot_ns  : 18 ns
branching_pot_ns   : 10 ns
branchless_npot_ns : 17 ns
branchless_pot_ns  : 17 ns

series_len = 4
----------------------------
builtin_npot_ns    : 15 ns
builtin_pot_ns     : 16 ns
branching_npot_ns  : 8 ns
branching_pot_ns   : 3 ns
branchless_npot_ns : 7 ns
branchless_pot_ns  : 7 ns

series_len = 2
----------------------------
builtin_npot_ns    : 8 ns
builtin_pot_ns     : 7 ns
branching_npot_ns  : 4 ns
branching_pot_ns   : 2 ns
branchless_npot_ns : 2 ns
branchless_pot_ns  : 2 ns


问:
Local Cache Library C# (persistent and encrypted)
I'm looking to add caching to a Windows desktop application written in C# 4.

My requirements are for a persistent key-value store that saves to an encrypted file.  I am trying to cache remote calls to a server that are potentially slow—and may cache a considerable amount of data, i.e. 50+ MB.  I would like to be able to set a max-file-size value with some form of LRU expiration.

I had thought of serialising a dictionary, but this is likely to be a little slow to initialise, and will have too large a memory footprint.

I'm thinking an encrypted SQLCE 4 database might be the best solution, but this seems heavyweight when I really just want a single hash table.  It also doesn't natively offer the caching type features of expiration etc..

Can anyone suggest anything else worth considering, or some suggestion around optimising the serialisation/deserialisation.

答:
A combination of protobuf-net and File encryption in .NET may be useful.

You can use protobuf-net to serialize/deserialze quickly. (See the getting started guide for an example of persisting a 'Person' object to a binary file). protobuf also has methods that return a byte[] so you could pass this to the crypto to avoid reading the byte stream back in.


问:
-bash: monkeyrunner: command not found
I am trying to see how monkeyrunnerworks. I have python script that I want to test it on my android virtual device. I tried running below command through terminal:

monkeyrunner script.py

I am at: /Users/myusername/Library/Android/sdk/tools/bin/monkeyrunner, python file is also in the same directory.

but it returns that: -bash: monkeyrunner: command not found

So I tried another way, and I opened monkeyrunner exec file, then tried to run script.py through it, but still giving this error

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'script' is not defined
</code>```

I also tried monkeyrunner script.py inside monkeyrunner exec file but gives this error:

```<code>File "<stdin>", line 1
    monkeyrunner script.py
                ^
SyntaxError: mismatched input 'script' expecting NEWLINE
</code>```

Can anyone help, how to run a python script using androidstudio's monkeyrunner in MacOS and let me know what I am doing wrong.

答:
Since I am new to macOS I wasn't sure that terminal kind of work the same as cmd on Windows, but after trying ./monkeyrunner script.py, finally my python script successfully run on monkeyrunner.

Also I noticed another point that if someone else get stuck into this issue and doesn't like to put ./ every time he/she executes a command, he/she can just put the monkeyrunner path in his/her environment path variables.

For macOS the paths file is here:
/etc/paths

Title: -bash: monkeyrunner: command not found

Body:
I am trying to see how monkeyrunnerworks. I have python script that I want to test it on my android virtual device. I tried running below command through terminal:

monkeyrunner script.py

I am at: /Users/myusername/Library/Android/sdk/tools/bin/monkeyrunner, python file is also in the same directory.

but it returns that: -bash: monkeyrunner: command not found

So I tried another way, and I opened monkeyrunner exec file, then tried to run script.py through it, but still giving this error

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'script' is not defined

I also tried monkeyrunner script.py inside monkeyrunner exec file but gives this error:

File "<stdin>", line 1
    monkeyrunner script.py
                ^
SyntaxError: mismatched input 'script' expecting NEWLINE

Can anyone help, how to run a python script using androidstudio's monkeyrunner in MacOS and let me know what I am doing wrong.


问:
What makes Everything's file search and index so efficient?
Everything is a file searching program. As its author hasn't released the source code, I am wondering how it works.

How could it index files so efficiently?

What data structures does it use for file searching?

How can its file searching be so fast?

To quote its FAQ,

"Everything" only indexes file and folder names and generally takes a
  few seconds to build its database. A fresh install of Windows 10
  (about 120,000 files) will take about 1 second to index. 1,000,000
  files will take about 1 minute.

If it takes only one second to index the whole Windows 10, and takes only 1 minute to index one million files, does this mean it can index 120,000 files per second?

To make the search fast, there must be a special data structure. Searching by file name doesn't only search from the start, but also from the middle in most cases. This makes it some widely used indexing structures such as Trie and Red–black tree ineffective.

The FAQ clarifies further.

Does "Everything" hog my system resources?

No, "Everything" uses very little system resources. A fresh install of
  Windows 10 (about 120,000 files) will use about 14 MB of ram and less
  than 9 MB of disk space. 1,000,000 files will use about 75 MB of ram
  and 45 MB of disk space.

答:
How could it index files so efficiently?

First, it indexes only file/directory names, not contents.

I don't know if it's efficient enough for your needs, but the ordinary way is with FindFirstFile function. Write a simple C program to list folders/files recursively, and see if it's fast enough for you. The second step through optimization would be running threads in parallel, but maybe disk access would be the bottleneck, if so multiple threads would add little benefit.

If this is not enough, finally you could try to dig into the even lower Native API functions; I have no experience with these, so I can't give you further advice. You'd be pretty close to the metal, and maybe the Linux NTFS project has some concepts you need to learn.

What data structures does it use for file searching?

How can its file searching be so fast?

Well, you know there are many different data structures designed for fast searching... probably the author ran a lot of benchmarks.


问:
Can't install wordcloud in python (Anaconda)
I am trying to install wordcloud in my python program. I am doing the following steps. Please tell me where i am doing wrong-

I downloaded the wordcloud package from here https://github.com/amueller/word_cloud

Copy and paste it in the Anaconda3 folder.

Open Anaconda command prompt and give the following command "pip install wordcloud".

The following error is showing -

Please let me know what to do.

答:
I have python 3.6.3 installed on my windows system. I installed wordcloud package in python but faced the "wordcloud No Module Found" error on Anaconda Jupyter Notebook.

I tried most of the solutions posted here but nothing worked for me.

Finally I installed wordcloud package in the Scripts directory under Anacond3 directory in the command prompt using:

```<code>pip install wordcloud
</code>```

This worked and I am able to import wordcloud on Jupyter now.

Body:
I have python 3.6.3 installed on my windows system. I installed wordcloud package in python but faced the "wordcloud No Module Found" error on Anaconda Jupyter Notebook.

I tried most of the solutions posted here but nothing worked for me.

Finally I installed wordcloud package in the Scripts directory under Anacond3 directory in the command prompt using:

pip install wordcloud

This worked and I am able to import wordcloud on Jupyter now.


问:
Android Universal Music Player unable to advance to next or other song while playing to Chromecast Audio
I'm trying to learn this Universal Music Player sample for my own app development. I was never expecting this so haven't even tried it out so far, but the sample from the GitHub behaves oddly when streaming to Chromecast Audio. I haven't found any related info anywhere, so have been posting this question wherever I can, hoping to get some hints from those of you with some experience with UAMP.

When I'm playing a song on the json list (from the default Google server) to Chromecast Audio and select another song on the list or try to skip to the next song, an error is thrown (see log below) about 5 times and it doesn't progress to the next or selected song. Instead it just moves on to a random song on the list, or keeps playing the same song. This is with the GitHub code directly complied and run on a tablet, without any modification. This does not happen when Chromecast is not being used (i.e., playing directly on the tablet). Sorry about the messy log message. Hope someone has some experience / knowledge on this and can give me a hint!

```<code>11-15 03:08:49.792 18204-18204/com.example.android.uamp
E/MediaNotificationServiceImpl: Unregistering trampoline BroadcastReceiver failed
java.lang.IllegalArgumentException: Receiver not registered: yy@8f7a15d
at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:789)
at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1200)
at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:576)
at yx.b(:com.google.android.gms.DynamiteModulesC@11746440:105)
at yp.onTransact(:com.google.android.gms.DynamiteModulesC@11746440:22)
at android.os.Binder.transact(Binder.java:392)
at com.google.android.gms.internal.zzed.zzb(Unknown Source)
at com.google.android.gms.cast.framework.media.zze.onDestroy(Unknown Source)
at com.google.android.gms.cast.framework.media.MediaNotificationService.onDestroy(Unknown Source)
at android.app.ActivityThread.handleStopService(ActivityThread.java:3244)
at android.app.ActivityThread.-wrap21(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1591)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749)
</code>```

答:
I initially reported this on GitHub, and while waiting found a workaround, described here:

https://github.com/googlesamples/android-UniversalMusicPlayer/issues/182

It's basically tweaking CastPlayback.java a bit so that the playback method doesn't get called multiple times with changing media info.

Body:
I'm trying to learn this Universal Music Player sample for my own app development. I was never expecting this so haven't even tried it out so far, but the sample from the GitHub behaves oddly when streaming to Chromecast Audio. I haven't found any related info anywhere, so have been posting this question wherever I can, hoping to get some hints from those of you with some experience with UAMP.

When I'm playing a song on the json list (from the default Google server) to Chromecast Audio and select another song on the list or try to skip to the next song, an error is thrown (see log below) about 5 times and it doesn't progress to the next or selected song. Instead it just moves on to a random song on the list, or keeps playing the same song. This is with the GitHub code directly complied and run on a tablet, without any modification. This does not happen when Chromecast is not being used (i.e., playing directly on the tablet). Sorry about the messy log message. Hope someone has some experience / knowledge on this and can give me a hint!

11-15 03:08:49.792 18204-18204/com.example.android.uamp
E/MediaNotificationServiceImpl: Unregistering trampoline BroadcastReceiver failed
java.lang.IllegalArgumentException: Receiver not registered: yy@8f7a15d
at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:789)
at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1200)
at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:576)
at yx.b(:com.google.android.gms.DynamiteModulesC@11746440:105)
at yp.onTransact(:com.google.android.gms.DynamiteModulesC@11746440:22)
at android.os.Binder.transact(Binder.java:392)
at com.google.android.gms.internal.zzed.zzb(Unknown Source)
at com.google.android.gms.cast.framework.media.zze.onDestroy(Unknown Source)
at com.google.android.gms.cast.framework.media.MediaNotificationService.onDestroy(Unknown Source)
at android.app.ActivityThread.handleStopService(ActivityThread.java:3244)
at android.app.ActivityThread.-wrap21(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1591)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749)


答:
Use COUNT(DISTINCT) instead:

```<code>SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT Col2
    FROM yourTable
    GROUP BY Col2
    -- WHERE Col1 IN ('item1', 'item3')
    HAVING COUNT(DISTINCT Col1) = 2
) t2
    ON t1.Col2 = t2.Col2;
</code>```

Note that you need to join your original query back to the main table if you want to return the full matching records.  I also do not make assumptions about which matches you want, but rather return all matching pairs.

Demo

Title: MySQL Select Matching Rows With Same Value From 2 Different Items

Body:
Use COUNT(DISTINCT) instead:

SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT Col2
    FROM yourTable
    GROUP BY Col2
    -- WHERE Col1 IN ('item1', 'item3')
    HAVING COUNT(DISTINCT Col1) = 2
) t2
    ON t1.Col2 = t2.Col2;

Note that you need to join your original query back to the main table if you want to return the full matching records.  I also do not make assumptions about which matches you want, but rather return all matching pairs.

Demo


问:
Unable to create simple Inventory Adjustment: invalid field for customer?
Why, when I attempt to create an Inventory Adjustment I get the error:

You have entered an Invalid Field Value 12112 for the following field: customer

I can confirm that that customer entity id is valid and that they are part of the correct subsidiary.

Any ideas what the heck is going wrong and how I can create a simple Inventory Adjustment?

```<code>require(['N/ui/serverWidget',
        'N/email',
        'N/runtime',
        'N/search',
        'N/file',
        'N/config',
        'N/format',
        'N/record',
        'N/log',
        'N/runtime'],

function(ui, email, runtime, search, file, config, format, record, log, runtime) {

    // Attempt to create an IA

    var ia = record.create({
        type: record.Type.INVENTORY_ADJUSTMENT,
        isDynamic: true
    });

    // Set IA fields
    var values = {
        // 'entity': '12112',  // Dummy customer
        'customer': '12112',
        'subsidiary': '2',
        'account': '307',
        'class': '36',
        //'adjlocation': '2'
    };

    for (var key in values) {
        ia.setValue({
            fieldId: key,
            value: values[key]
        });
    }

    // Set IA Inventory sublist fields/lines
    var line1 = {
        'item': '61',
        'location': '1',
        'adjustqtyby': '-1',
        'department': '3',
        'class': '36',
    };

    ia.selectNewLine({
        sublistId: 'inventory'
    });

    for (var field in line1) {
        ia.setCurrentSublistValue({
            sublistId: 'inventory',
            fieldId: field,
            value: line1[field]
        });
    }

    ia.commitLine({
        sublistId: 'inventory'
    });

    var recordId = ia.save({
        enableSourcing: false,
        ignoreMandatoryFields: false
    });

    var x = 0;  // Add breakpoint for NS Debugger

});
</code>```

答:
You are creating the record in "dynamic" mode, so you need to set fields in the same order as you would in the UI. In particular, you need to select a subsidiary before you can set the customer field.

Swapping these order of these two lines will most probably solve your error.

```<code>var values = {
    // 'entity': '12112',  // Dummy customer
    'subsidiary': '2',
    'customer': '12112',
    'account': '307',
    'class': '36',
    //'adjlocation': '2'
};
</code>```

However, take note that for..in does not guarantee that it will follow any particular order, so theoretically NetSuite could push an update to their JavaScript engine at any time that would order things differently and break your code.

Body:
Why, when I attempt to create an Inventory Adjustment I get the error:

You have entered an Invalid Field Value 12112 for the following field: customer

I can confirm that that customer entity id is valid and that they are part of the correct subsidiary.

Any ideas what the heck is going wrong and how I can create a simple Inventory Adjustment?

require(['N/ui/serverWidget',
        'N/email',
        'N/runtime',
        'N/search',
        'N/file',
        'N/config',
        'N/format',
        'N/record',
        'N/log',
        'N/runtime'],

function(ui, email, runtime, search, file, config, format, record, log, runtime) {

    // Attempt to create an IA

    var ia = record.create({
        type: record.Type.INVENTORY_ADJUSTMENT,
        isDynamic: true
    });

    // Set IA fields
    var values = {
        // 'entity': '12112',  // Dummy customer
        'customer': '12112',
        'subsidiary': '2',
        'account': '307',
        'class': '36',
        //'adjlocation': '2'
    };

    for (var key in values) {
        ia.setValue({
            fieldId: key,
            value: values[key]
        });
    }

    // Set IA Inventory sublist fields/lines
    var line1 = {
        'item': '61',
        'location': '1',
        'adjustqtyby': '-1',
        'department': '3',
        'class': '36',
    };

    ia.selectNewLine({
        sublistId: 'inventory'
    });

    for (var field in line1) {
        ia.setCurrentSublistValue({
            sublistId: 'inventory',
            fieldId: field,
            value: line1[field]
        });
    }

    ia.commitLine({
        sublistId: 'inventory'
    });

    var recordId = ia.save({
        enableSourcing: false,
        ignoreMandatoryFields: false
    });

    var x = 0;  // Add breakpoint for NS Debugger

});

Body:
You are creating the record in "dynamic" mode, so you need to set fields in the same order as you would in the UI. In particular, you need to select a subsidiary before you can set the customer field.

Swapping these order of these two lines will most probably solve your error.

var values = {
    // 'entity': '12112',  // Dummy customer
    'subsidiary': '2',
    'customer': '12112',
    'account': '307',
    'class': '36',
    //'adjlocation': '2'
};

However, take note that for..in does not guarantee that it will follow any particular order, so theoretically NetSuite could push an update to their JavaScript engine at any time that would order things differently and break your code.


问:
How to get very first word before and after 'text'
I am after the very first word before v and after 'v'.

```<code>df = pd.DataFrame({'text': ["cans choc v macroni ice",
                            "chocolate sundaes v chocolate ice cream",
                            "Chocolate v sauce"]})
</code>```

I have a dataframe that looks like:

```<code>cans choc v macroni ice
chocolate sundaes v chocolate ice cream
Chocolate v sauce
</code>```

I want it to look like:

```<code>cans v macroni
chocolate v chocolate
Chocolate v sauce
</code>```

How can this be achieved in pandas?  The common element is 'v'.

答:
You can use regular expressions, as @James suggests.  But here's another way, using pandas apply, which more generically handles the question at hand.

(BTW, there are several very similar questions and answers, such as this one.)

```<code>>>> def my_fun(my_text, my_sep):
>>>   vals = my_text.split(my_sep)
>>>   vals = [val.split()[0] for val in vals]
>>>   return vals

>>> df.text.apply(lambda my_text: my_fun(my_text, 'v'))
</code>```

Of course, please use better names than this!  :-)

Body:
I am after the very first word before v and after 'v'.

df = pd.DataFrame({'text': ["cans choc v macroni ice",
                            "chocolate sundaes v chocolate ice cream",
                            "Chocolate v sauce"]})

I have a dataframe that looks like:

cans choc v macroni ice
chocolate sundaes v chocolate ice cream
Chocolate v sauce

I want it to look like:

cans v macroni
chocolate v chocolate
Chocolate v sauce

How can this be achieved in pandas?  The common element is 'v'.

Body:
You can use regular expressions, as @James suggests.  But here's another way, using pandas apply, which more generically handles the question at hand.

(BTW, there are several very similar questions and answers, such as this one.)

>>> def my_fun(my_text, my_sep):
>>>   vals = my_text.split(my_sep)
>>>   vals = [val.split()[0] for val in vals]
>>>   return vals

>>> df.text.apply(lambda my_text: my_fun(my_text, 'v'))

Of course, please use better names than this!  :-)


问:
XPath axis, get all following nodes until
I have the following example of HTML:

```<code><!-- lots of html -->
<h2>Foo bar</h2>
<p>lorem</p>
<p>ipsum</p>
<p>etc</p>

<h2>Bar baz</h2>
<p>dum dum dum</p>
<p>poopfiddles</p>
<!-- lots more html ... -->
</code>```

I'm looking to extract all paragraphs following the 'Foo bar' header, until I reach the 'Bar baz' header (the text for the 'Bar baz' header is unknown, so unfortunately I can't use the answer provided by bougyman). Now I can of course using something like //h2[text()='Foo bar']/following::p but that of course will grab all paragraphs following this header. So I have the option to traverse the nodeset and push paragraphs into an Array until the text matches that of the next following header, but let's be honest, that's never as cool as being able to do it in XPath.

Is there a way to do this that I'm missing?

答:
This XPATH 1.0 statement selects all of the
 that are siblings that follow an
 who's string value is equal to "Foo bar", that are also followed by an
 sibling element who's first preceding sibling
 has a string value of "Foo bar".

```<code>//p[preceding-sibling::h2[.='Foo bar']]
 [following-sibling::h2[
  preceding-sibling::h2[1][.='Foo bar']]]
</code>```

Body:
I have the following example of HTML:

Foo bar

lorem

ipsum

etc

Bar baz

dum dum dum

poopfiddles

I'm looking to extract all paragraphs following the 'Foo bar' header, until I reach the 'Bar baz' header (the text for the 'Bar baz' header is unknown, so unfortunately I can't use the answer provided by bougyman). Now I can of course using something like //h2[text()='Foo bar']/following::p but that of course will grab all paragraphs following this header. So I have the option to traverse the nodeset and push paragraphs into an Array until the text matches that of the next following header, but let's be honest, that's never as cool as being able to do it in XPath.

Is there a way to do this that I'm missing?

Body:
This XPATH 1.0 statement selects all of the <p> that are siblings that follow an <h2> who's string value is equal to "Foo bar", that are also followed by an <h2> sibling element who's first preceding sibling <h2> has a string value of "Foo bar".

//p[preceding-sibling::h2[.='Foo bar']]
 [following-sibling::h2[
  preceding-sibling::h2[1][.='Foo bar']]]


问:
How to refresh combobox winform c#
i create winform with c# that had two combobox

The form look like this

combobox1 select company from database

combobox2 select project from database depend on company from combobox1

everything ok when the form loaded but i want to refresh combobox2 when i change company in combobox1

this is my code

```<code>using System;
using System.Data;
using System.Windows.Forms;
using Oracle.ManagedDataAccess.Client;

namespace WindowsFormsApp3
{
    public partial class Form_AC071503 : Form
    {
        public Form_AC071503()
        {
            InitializeComponent();
        }

        DataSet ds = new DataSet();

        OracleCommand cmd1;
        OracleDataAdapter da1;

        OracleCommand cmd2;
        OracleDataAdapter da2;

        private void Form_AC071503_Load(object sender, EventArgs e)
        {
            cmd1 = new OracleCommand("SELECT company,company_name from COMPANIES", Class_All.Connection);
            da1 = new OracleDataAdapter(cmd1);
            da1.Fill(ds, "COMPANIES");
            input_company.DataSource = ds.Tables["COMPANIES"];
            input_company.DisplayMember = "company_name";
            input_company.ValueMember = "company";

            cmd2 = new OracleCommand("SELECT project,project_name from PROJECTS where COMPANY = '" + input_company.SelectedValue.ToString() + "'", Class_All.Connection);
            da2 = new OracleDataAdapter(cmd2);
            da2.Fill(ds, "PROJECTS");
            input_project.DataSource = ds.Tables["PROJECTS"];
            input_project.DisplayMember = "project_name";
            input_project.ValueMember = "project";
        }

        private void Input_company_SelectedIndexChanged(object sender, EventArgs e)
        {
            /*i try to use the same code in Form_AC071503_Load like this

              cmd2 = new OracleCommand("SELECT project,project_name from PROJECTS where COMPANY = '" + input_company.SelectedValue.ToString() + "'", Class_All.Connection);
              da2 = new OracleDataAdapter(cmd2);
              da2.Fill(ds, "PROJECTS");
              input_project.DataSource = ds.Tables["PROJECTS"];
              input_project.DisplayMember = "project_name";
              input_project.ValueMember = "project";

              but not work because the list project not refresh but increased with new value*/
        }
    }
}
</code>```

thank you in advice.

答: You need to add the ValueChanged event in combobox1.</p>

Title: How to refresh combobox winform c#

Body:
i create winform with c# that had two combobox

The form look like this

combobox1 select company from database

combobox2 select project from database depend on company from combobox1

everything ok when the form loaded but i want to refresh combobox2 when i change company in combobox1

this is my code

using System;
using System.Data;
using System.Windows.Forms;
using Oracle.ManagedDataAccess.Client;

namespace WindowsFormsApp3
{
    public partial class Form_AC071503 : Form
    {
        public Form_AC071503()
        {
            InitializeComponent();
        }

        DataSet ds = new DataSet();

        OracleCommand cmd1;
        OracleDataAdapter da1;

        OracleCommand cmd2;
        OracleDataAdapter da2;

        private void Form_AC071503_Load(object sender, EventArgs e)
        {
            cmd1 = new OracleCommand("SELECT company,company_name from COMPANIES", Class_All.Connection);
            da1 = new OracleDataAdapter(cmd1);
            da1.Fill(ds, "COMPANIES");
            input_company.DataSource = ds.Tables["COMPANIES"];
            input_company.DisplayMember = "company_name";
            input_company.ValueMember = "company";

            cmd2 = new OracleCommand("SELECT project,project_name from PROJECTS where COMPANY = '" + input_company.SelectedValue.ToString() + "'", Class_All.Connection);
            da2 = new OracleDataAdapter(cmd2);
            da2.Fill(ds, "PROJECTS");
            input_project.DataSource = ds.Tables["PROJECTS"];
            input_project.DisplayMember = "project_name";
            input_project.ValueMember = "project";
        }

        private void Input_company_SelectedIndexChanged(object sender, EventArgs e)
        {
            /*i try to use the same code in Form_AC071503_Load like this

              cmd2 = new OracleCommand("SELECT project,project_name from PROJECTS where COMPANY = '" + input_company.SelectedValue.ToString() + "'", Class_All.Connection);
              da2 = new OracleDataAdapter(cmd2);
              da2.Fill(ds, "PROJECTS");
              input_project.DataSource = ds.Tables["PROJECTS"];
              input_project.DisplayMember = "project_name";
              input_project.ValueMember = "project";

              but not work because the list project not refresh but increased with new value*/
        }
    }
}

thank you in advice.


问:
How to get all full CREATE TABLE statements from a mysql dump
I got this so far:

```<code>$ bzcat mysqldump.pplware.sql.bz2 | grep -A 10 "^CREATE TABLE.*"
CREATE TABLE `wp_ak_twitter` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `tw_id` varchar(255) NOT NULL,
  `tw_text` varchar(255) NOT NULL,
  `tw_reply_username` varchar(255) DEFAULT NULL,
  `tw_reply_tweet` varchar(255) DEFAULT NULL,
  `tw_created_at` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `tw_id` (`tw_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
--
CREATE TABLE `wp_audit_trail` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `operation` varchar(40) NOT NULL DEFAULT '',
  `user_id` int(11) NOT NULL,
  `ip` int(11) unsigned NOT NULL DEFAULT '0',
  `happened_at` datetime NOT NULL,
  `item_id` int(11) DEFAULT NULL,
  `data` longtext,
  `title` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9442523 DEFAULT CHARSET=latin1;
</code>```

..and so on.
But the 10 line limit is arbitrary, and some of the CREATE TABLES are shorter and some are longer. How can I get all full CREATE TABLE definitions?

答:
How about just getting the definitions, without the data:

```<code>mysqldump ... --no-data ...
</code>```

(Sure, this does not answer the question as asked, but it may provide an easy solution in some cases.)

Body:
I got this so far:

$ bzcat mysqldump.pplware.sql.bz2 | grep -A 10 "^CREATE TABLE.*"
CREATE TABLE `wp_ak_twitter` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `tw_id` varchar(255) NOT NULL,
  `tw_text` varchar(255) NOT NULL,
  `tw_reply_username` varchar(255) DEFAULT NULL,
  `tw_reply_tweet` varchar(255) DEFAULT NULL,
  `tw_created_at` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `tw_id` (`tw_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
--
CREATE TABLE `wp_audit_trail` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `operation` varchar(40) NOT NULL DEFAULT '',
  `user_id` int(11) NOT NULL,
  `ip` int(11) unsigned NOT NULL DEFAULT '0',
  `happened_at` datetime NOT NULL,
  `item_id` int(11) DEFAULT NULL,
  `data` longtext,
  `title` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9442523 DEFAULT CHARSET=latin1;

..and so on.
But the 10 line limit is arbitrary, and some of the CREATE TABLES are shorter and some are longer. How can I get all full CREATE TABLE definitions?

Body:
How about just getting the definitions, without the data:

mysqldump ... --no-data ...

(Sure, this does not answer the question as asked, but it may provide an easy solution in some cases.)


问:
Why is there an extra space in between a variable and punctuation in a string? Python
There is an extra space in the output of a string. This is the section of the code where it happens. It happens in the string of the function, nameConfirmation().

```<code>def chooseName():
    name = ""
    name = raw_input("Let's begin with your name. What is it? ")

    return name

def nameConfirmation():
    name = chooseName()
    print ("Right... So your name is", name,".")
</code>```

This is the output it gives.

```<code>Right... So your name is Raven .
</code>```

How do I get rid of the space in between the name and the punctuation?

答:
If you use:

```<code>print ("Right... So your name is", name,".")
</code>```

You will notice that the output is:

```<code>Right... So your name is Raven .
</code>```

Look at is and name (Raven). You can note in the output an space (is Raven), that is because print() have a default argument called sep an by default it's print("Right... So your name is", name,".", sep = ' '). That argument is an string that it's added at the end of each piece of string concatenated with a coma , in the print function.

So if you do print('A','B') it will be A B, because when you concatenate A and B, print will add  ' ' (and space) as glue.

You can configure it: print('A','B', sep='glue') would print AglueB!

To solve your problem you can do two options.

Change sep = '' and add an space  after is: print ("Right... So your name is ", name,".", sep='')

Or, concatenate using + the last two strings: print ("Right... So your name is", name + ".")

Also there are a lot of another ways like: (I ordered them by worst to best in my subjetive opinion...)

print("Right... So your name is %s." % name).

print("Right... So your name is {}.".format(name)).

print(f"Right... So your name is {name}.")

Link with documentation:

Python Official Documentation

Python 3 Course (Use of sep and ,, +, %s, .format(), f-string and use of string class)

PyFormat (Basic and advanced use of %s, %d, .format(), value conversion, datetime, ).

P.S: This isn't part of the answer, it's just a note.

print (something) don't need the space --> print(something).

Futhemorer sep = ' ' there is also called end = '\n' that determine the end of a print (\n = new line).

P.S 2: Thanks Ouss for the idea of add some documentations links. I've just learnt that you can do print(%(key)s % mydict)!

Body:
There is an extra space in the output of a string. This is the section of the code where it happens. It happens in the string of the function, nameConfirmation().

def chooseName():
    name = ""
    name = raw_input("Let's begin with your name. What is it? ")

    return name

def nameConfirmation():
    name = chooseName()
    print ("Right... So your name is", name,".")

This is the output it gives.

Right... So your name is Raven .

How do I get rid of the space in between the name and the punctuation?

Body:
If you use:

print ("Right... So your name is", name,".")

You will notice that the output is:

Right... So your name is Raven .

Look at is and name (Raven). You can note in the output an space (is Raven), that is because print() have a default argument called sep an by default it's print("Right... So your name is", name,".", sep = ' '). That argument is an string that it's added at the end of each piece of string concatenated with a coma , in the print function.

So if you do print('A','B') it will be A B, because when you concatenate A and B, print will add  ' ' (and space) as glue.

You can configure it: print('A','B', sep='glue') would print AglueB!

To solve your problem you can do two options.

Change sep = '' and add an space  after is: print ("Right... So your name is ", name,".", sep='')

Or, concatenate using + the last two strings: print ("Right... So your name is", name + ".")

Also there are a lot of another ways like: (I ordered them by worst to best in my subjetive opinion...)

print("Right... So your name is %s." % name).

print("Right... So your name is {}.".format(name)).

print(f"Right... So your name is {name}.")

Link with documentation:

Python Official Documentation

Python 3 Course (Use of sep and ,, +, %s, .format(), f-string and use of string class)

PyFormat (Basic and advanced use of %s, %d, .format(), value conversion, datetime, ).

P.S: This isn't part of the answer, it's just a note.

print (something) don't need the space --> print(something).

Futhemorer sep = ' ' there is also called end = '\n' that determine the end of a print (\n = new line).

P.S 2: Thanks Ouss for the idea of add some documentations links. I've just learnt that you can do print(%(key)s % mydict)!


问:
One or more foreign keys created in Create table statement Oracle
I have two tables, an employee table and a project table. Each project has to have at least one employee, but it could have more. I'm struggling to figure out how to create the Project table so you can have a non-fixed number of foreign keys. What I have right now is this:

```<code>CREATE TABLE EMPLOYEE (
EmployeeID number(10) NOT NULL,
FirstName varchar2(20),
LastName varchar2(20),
Address varchar2(20),
City varchar2(20),
State varchar2(2),
Zip number(5),
DoB varchar2(10),
PRIMARY KEY (EmployeeID)
);

INSERT INTO EMPLOYEE
Values ('1', 'Joe', 'Smith', '1 Main St', 'Stillwater', 'OK', 74075, '07/05/1992');

INSERT INTO EMPLOYEE
Values ('2', 'John', 'Johnson', '3 College Way', 'Stillwater', 'OK', 74074, '08/05/1992');

CREATE TABLE PROJECT (
    ProjectID number(10) NOT NULL,
    ProjectName varchar2(20),
    ProjectDesc varchar2(20),
    ProjectStartDate varchar2(20),
    EmployeeID number(10),
    PRIMARY KEY (ProjectID),
    CONSTRAINT FK_EmployeeID FOREIGN KEY (EmployeeID)
    REFERENCES EMPLOYEE(EmployeeID)
);

INSERT INTO Project
Values ('1', 'ProjectA', 'A Project', '12/05/2017', '1');

INSERT INTO Project
Values ('2', 'ProjectB', 'B Project', '01/05/2018', '1', '2');
</code>```

Obviously, the last line is where it goes wrong, because there are too many pieces of information. How do I solve this?

答:
The values directly correlate to the fields in the table, and you need to ensure that the number of values you insert correctly corresponds to the number of fields.

In order to insert more than one row into the relevant table, you have to split up the inserts. So, you need to split up your two employee insertions into ProjectB, and insert both employee independently.

Note that you'll also want to ensure that both of your primary keys auto increment, so that you don't have to worry about the foreign key constraints! In Oracle, you can do this with the IDENTITY column:

```<code>CREATE TABLE EMPLOYEE (
  EmployeeID number(10) NOT NULL as IDENTITY,
  ...
  PRIMARY KEY (EmployeeID)
);

CREATE TABLE PROJECT (
  ProjectID number(10) NOT NULL as IDENTITY,
  ...
  PRIMARY KEY (ProjectID)
);
</code>```

Then you can insert with:

```<code>INSERT INTO Project Values (null, 'ProjectB', 'B Project', '01/05/2018', '1');
INSERT INTO Project Values (null, 'ProjectB', 'B Project', '01/05/2018', '2');
</code>```

This gives you a total of three INSERT statements:

```<code>INSERT INTO Project Values (null, 'ProjectA', 'A Project', '12/05/2017', '1');
INSERT INTO Project Values (null, 'ProjectB', 'B Project', '01/05/2018', '1');
INSERT INTO Project Values (null, 'ProjectB', 'B Project', '01/05/2018', '2');
</code>```

Note that because the employee is the only thing changing in your two inserts to ProjectB, you might want to consider looping over these inserts:

```<code>    DECLARE
    i    NUMBER (1);
BEGIN
    FOR i IN 1 .. x
    LOOP
        INSERT INTO Project Values ('2', 'ProjectB', 'B Project', '01/05/2018', i);
    END LOOP;
END;
</code>```

However, down the line, I can envisage multiple projects can have multiple employees, and employees working on multiple projects. This would be a many to many relationship, which would require a bridging table (also know as  associative entity). It may be worthwhile keeping this in mind :)

Hope this helps!

Body:
I have two tables, an employee table and a project table. Each project has to have at least one employee, but it could have more. I'm struggling to figure out how to create the Project table so you can have a non-fixed number of foreign keys. What I have right now is this:

CREATE TABLE EMPLOYEE (
EmployeeID number(10) NOT NULL,
FirstName varchar2(20),
LastName varchar2(20),
Address varchar2(20),
City varchar2(20),
State varchar2(2),
Zip number(5),
DoB varchar2(10),
PRIMARY KEY (EmployeeID)
);

INSERT INTO EMPLOYEE
Values ('1', 'Joe', 'Smith', '1 Main St', 'Stillwater', 'OK', 74075, '07/05/1992');

INSERT INTO EMPLOYEE
Values ('2', 'John', 'Johnson', '3 College Way', 'Stillwater', 'OK', 74074, '08/05/1992');

CREATE TABLE PROJECT (
    ProjectID number(10) NOT NULL,
    ProjectName varchar2(20),
    ProjectDesc varchar2(20),
    ProjectStartDate varchar2(20),
    EmployeeID number(10),
    PRIMARY KEY (ProjectID),
    CONSTRAINT FK_EmployeeID FOREIGN KEY (EmployeeID)
    REFERENCES EMPLOYEE(EmployeeID)
);

INSERT INTO Project
Values ('1', 'ProjectA', 'A Project', '12/05/2017', '1');

INSERT INTO Project
Values ('2', 'ProjectB', 'B Project', '01/05/2018', '1', '2');

Obviously, the last line is where it goes wrong, because there are too many pieces of information. How do I solve this?

Body:
The values directly correlate to the fields in the table, and you need to ensure that the number of values you insert correctly corresponds to the number of fields.

In order to insert more than one row into the relevant table, you have to split up the inserts. So, you need to split up your two employee insertions into ProjectB, and insert both employee independently.

Note that you'll also want to ensure that both of your primary keys auto increment, so that you don't have to worry about the foreign key constraints! In Oracle, you can do this with the IDENTITY column:

CREATE TABLE EMPLOYEE (
  EmployeeID number(10) NOT NULL as IDENTITY,
  ...
  PRIMARY KEY (EmployeeID)
);

CREATE TABLE PROJECT (
  ProjectID number(10) NOT NULL as IDENTITY,
  ...
  PRIMARY KEY (ProjectID)
);

Then you can insert with:

INSERT INTO Project Values (null, 'ProjectB', 'B Project', '01/05/2018', '1');
INSERT INTO Project Values (null, 'ProjectB', 'B Project', '01/05/2018', '2');

This gives you a total of three INSERT statements:

INSERT INTO Project Values (null, 'ProjectA', 'A Project', '12/05/2017', '1');
INSERT INTO Project Values (null, 'ProjectB', 'B Project', '01/05/2018', '1');
INSERT INTO Project Values (null, 'ProjectB', 'B Project', '01/05/2018', '2');

Note that because the employee is the only thing changing in your two inserts to ProjectB, you might want to consider looping over these inserts:

    DECLARE
    i    NUMBER (1);
BEGIN
    FOR i IN 1 .. x
    LOOP
        INSERT INTO Project Values ('2', 'ProjectB', 'B Project', '01/05/2018', i);
    END LOOP;
END;

However, down the line, I can envisage multiple projects can have multiple employees, and employees working on multiple projects. This would be a many to many relationship, which would require a bridging table (also know as  associative entity). It may be worthwhile keeping this in mind :)

Hope this helps!