问:
Change Cells in Pandas DataFrame Based on Conditional Slices
I'm playing around with the Titanic dataset, and what I'd like to do is fill in all the NaN/Null values of the Age column with the median value base on that Pclass.

Here is some data:

```<code>train

PassengerId Pclass  Age
0   1   3   22
1   2   1   35
2   3   3   26
3   4   1   35
4   5   3   35
5   6   1   NaN
6   7   1   54
7   8   3   2
8   9   3   27
9   10  2   14
10  11  1   Nan
</code>```

Here is what I would like to end up with:

```<code>PassengerId Pclass  Age
0   1   3   22
1   2   1   35
2   3   3   26
3   4   1   35
4   5   3   35
5   6   1   35
6   7   1   54
7   8   3   2
8   9   3   27
9   10  2   14
10  11  1   35
</code>```

The first thing I came up with is this - In the interest of brevity I have only included one slice for Pclass equal to 1 rather than including 2 and 3:

```<code>Pclass_1 = train['Pclass']==1

train[Pclass_1]['Age'].fillna(train[train['Pclass']==1]['Age'].median(), inplace=True)
</code>```

As far as I understand, this method creates a view rather than editing train itself (I don't quite understand how this is different from a copy, or if they are analogous in terms of memory -- that is an aside I would love to hear about if possible). I particularly like this Q/A on the topic View vs Copy, How Do I Tell? but it doesn't include the insight I'm looking for.

Looking through Pandas docs I learned why you want to use .loc to avoid this pitfall. However I just can't seem to get the syntax right.

```<code>Pclass_1 = train.loc[:,['Pclass']==1]

Pclass_1.Age.fillna(train[train['Pclass']==1]['Age'].median(),inplace=True)
</code>```

I'm getting lost in indices. This one ends up looking for a column named False which obviously doesn't exist. I don't know how to do this without chained indexing. train.loc[:,train['Pclass']==1] returns an exception IndexingError: Unalignable boolean Series key provided.

答:
In this part of the line,

```<code>train.loc[:,['Pclass']==1]
</code>```

the part ['Pclass'] == 1 is comparing the list ['Pclass'] to the value 1, which returns False. The .loc[] is then evaluated as .loc[:,False] which is causing the error.

I think you mean:

```<code>train.loc[train['Pclass']==1]
</code>```

which selects all of the rows where Pclass is 1. This fixes the error, but it will still give you the "SettingWithCopyWarning".

EDIT 1

(old code removed)

Here is an approach that uses groupby with transform to create a Series
containing the median Age for each Pclass. The Series is then used as the argument to fillna() to replace the missing values with the median. Using this approach will correct all passenger classes at the same time, which is what the OP originally requested. The solution comes from the answer to Python-pandas Replace NA with the median or mean of a group in dataframe

```<code>import pandas as pd
from io import StringIO

tbl = """PassengerId Pclass  Age
0   1   3   22
1   2   1   35
2   3   3   26
3   4   1   35
4   5   3   35
5   6   1
6   7   1   54
7   8   3   2
8   9   3   27
9   10  2   14
10  11  1
"""

train = pd.read_table(StringIO(tbl), sep='\s+')
print('Original:\n', train)
median_age = train.groupby('Pclass')['Age'].transform('median') #median Ages for all groups
train['Age'].fillna(median_age, inplace=True)
print('\nNaNs replaced with median:\n', train)
</code>```

The code produces:

```<code> Original:
     PassengerId  Pclass   Age
0             1       3  22.0
1             2       1  35.0
2             3       3  26.0
3             4       1  35.0
4             5       3  35.0
5             6       1   NaN
6             7       1  54.0
7             8       3   2.0
8             9       3  27.0
9            10       2  14.0
10           11       1   NaN

NaNs replaced with median:
     PassengerId  Pclass   Age
0             1       3  22.0
1             2       1  35.0
2             3       3  26.0
3             4       1  35.0
4             5       3  35.0
5             6       1  35.0
6             7       1  54.0
7             8       3   2.0
8             9       3  27.0
9            10       2  14.0
10           11       1  35.0
</code>```

One thing to note is that this line, which uses inplace=True:

```<code>train['Age'].fillna(median_age, inplace=True)
</code>```

can be replaced with assignment using .loc:

```<code>train.loc[:,'Age'] = train['Age'].fillna(median_age)
</code>```

Body:
I'm playing around with the Titanic dataset, and what I'd like to do is fill in all the NaN/Null values of the Age column with the median value base on that Pclass.

Here is some data:

train

PassengerId Pclass  Age
0   1   3   22
1   2   1   35
2   3   3   26
3   4   1   35
4   5   3   35
5   6   1   NaN
6   7   1   54
7   8   3   2
8   9   3   27
9   10  2   14
10  11  1   Nan

Here is what I would like to end up with:

PassengerId Pclass  Age
0   1   3   22
1   2   1   35
2   3   3   26
3   4   1   35
4   5   3   35
5   6   1   35
6   7   1   54
7   8   3   2
8   9   3   27
9   10  2   14
10  11  1   35

The first thing I came up with is this - In the interest of brevity I have only included one slice for Pclass equal to 1 rather than including 2 and 3:

Pclass_1 = train['Pclass']==1

train[Pclass_1]['Age'].fillna(train[train['Pclass']==1]['Age'].median(), inplace=True)

As far as I understand, this method creates a view rather than editing train itself (I don't quite understand how this is different from a copy, or if they are analogous in terms of memory -- that is an aside I would love to hear about if possible). I particularly like this Q/A on the topic View vs Copy, How Do I Tell? but it doesn't include the insight I'm looking for.

Looking through Pandas docs I learned why you want to use .loc to avoid this pitfall. However I just can't seem to get the syntax right.

Pclass_1 = train.loc[:,['Pclass']==1]

Pclass_1.Age.fillna(train[train['Pclass']==1]['Age'].median(),inplace=True)

I'm getting lost in indices. This one ends up looking for a column named False which obviously doesn't exist. I don't know how to do this without chained indexing. train.loc[:,train['Pclass']==1] returns an exception IndexingError: Unalignable boolean Series key provided.

Body:
In this part of the line,

train.loc[:,['Pclass']==1]

the part ['Pclass'] == 1 is comparing the list ['Pclass'] to the value 1, which returns False. The .loc[] is then evaluated as .loc[:,False] which is causing the error.

I think you mean:

train.loc[train['Pclass']==1]

which selects all of the rows where Pclass is 1. This fixes the error, but it will still give you the "SettingWithCopyWarning".

EDIT 1

(old code removed)

Here is an approach that uses groupby with transform to create a Series
containing the median Age for each Pclass. The Series is then used as the argument to fillna() to replace the missing values with the median. Using this approach will correct all passenger classes at the same time, which is what the OP originally requested. The solution comes from the answer to Python-pandas Replace NA with the median or mean of a group in dataframe

import pandas as pd
from io import StringIO

tbl = """PassengerId Pclass  Age
0   1   3   22
1   2   1   35
2   3   3   26
3   4   1   35
4   5   3   35
5   6   1
6   7   1   54
7   8   3   2
8   9   3   27
9   10  2   14
10  11  1
"""

train = pd.read_table(StringIO(tbl), sep='\s+')
print('Original:\n', train)
median_age = train.groupby('Pclass')['Age'].transform('median') #median Ages for all groups
train['Age'].fillna(median_age, inplace=True)
print('\nNaNs replaced with median:\n', train)

The code produces:

 Original:
     PassengerId  Pclass   Age
0             1       3  22.0
1             2       1  35.0
2             3       3  26.0
3             4       1  35.0
4             5       3  35.0
5             6       1   NaN
6             7       1  54.0
7             8       3   2.0
8             9       3  27.0
9            10       2  14.0
10           11       1   NaN

NaNs replaced with median:
     PassengerId  Pclass   Age
0             1       3  22.0
1             2       1  35.0
2             3       3  26.0
3             4       1  35.0
4             5       3  35.0
5             6       1  35.0
6             7       1  54.0
7             8       3   2.0
8             9       3  27.0
9            10       2  14.0
10           11       1  35.0

One thing to note is that this line, which uses inplace=True:

train['Age'].fillna(median_age, inplace=True)

can be replaced with assignment using .loc:

train.loc[:,'Age'] = train['Age'].fillna(median_age)


来源: stackexchange

问:
Get Local time zone date by date component
Ok, this is my codes for format the current date to GMT format and return the value in date type. I 'po' the nowComponent variable while debugging which shows me the current local time zone values but the block of code 'calendar.date(from: nowComponents)!' still return me a UTC date. How to get the Date in local timezone ?</p>

```<code>    var nowComponents = DateComponents()
    let date = Date()

    nowComponents.year = (calendar as NSCalendar).component(NSCalendar.Unit.year, from: date)
    nowComponents.month = (calendar as NSCalendar).component(NSCalendar.Unit.month, from: date)
    nowComponents.day = (calendar as NSCalendar).component(NSCalendar.Unit.day, from: date)
    nowComponents.hour = (calendar as NSCalendar).component(NSCalendar.Unit.hour, from: date)
    nowComponents.minute = (calendar as NSCalendar).component(NSCalendar.Unit.minute, from: date)
    nowComponents.second = (calendar as NSCalendar).component(NSCalendar.Unit.second, from: date)

    (nowComponents as NSDateComponents).timeZone = TimeZone.current

    return calendar.date(from: nowComponents)!
</code>```

答:
None of your code is necessary. The line:

```<code>let date = Date()
</code>```

is all you need. This gives you the current date and time.

Your mistake is using po to print the date. This uses the description method on the date which shows the debug output of the date and that output shows the date in UTC time.

If you want to see the date, as a string, in local time, use DateFormatter:

```<code>let df = DateFormatter()
df.dateStyle = .long
df.timeStyle = .long
let str = df.string(from: date)
print(str)
</code>```

This will show the date in local time.

ContentLicense: CC BY-SA 3.0

Body:
Ok, this is my codes for format the current date to GMT format and return the value in date type. I 'po' the nowComponent variable while debugging which shows me the current local time zone values but the block of code 'calendar.date(from: nowComponents)!' still return me a UTC date. How to get the Date in local timezone ?

    var nowComponents = DateComponents()
    let date = Date()

    nowComponents.year = (calendar as NSCalendar).component(NSCalendar.Unit.year, from: date)
    nowComponents.month = (calendar as NSCalendar).component(NSCalendar.Unit.month, from: date)
    nowComponents.day = (calendar as NSCalendar).component(NSCalendar.Unit.day, from: date)
    nowComponents.hour = (calendar as NSCalendar).component(NSCalendar.Unit.hour, from: date)
    nowComponents.minute = (calendar as NSCalendar).component(NSCalendar.Unit.minute, from: date)
    nowComponents.second = (calendar as NSCalendar).component(NSCalendar.Unit.second, from: date)

    (nowComponents as NSDateComponents).timeZone = TimeZone.current

    return calendar.date(from: nowComponents)!

Body:
None of your code is necessary. The line:

let date = Date()

is all you need. This gives you the current date and time.

Your mistake is using po to print the date. This uses the description method on the date which shows the debug output of the date and that output shows the date in UTC time.

If you want to see the date, as a string, in local time, use DateFormatter:

let df = DateFormatter()
df.dateStyle = .long
df.timeStyle = .long
let str = df.string(from: date)
print(str)

This will show the date in local time.


问:
Woocommerce - Reposition Title on Archive Page
I am using woocommerce and would like to move the title on my archive page to above the thumbnail. Right now it is below the thumbnail.

Is there a way to unhook the title in its current position and move it? Thanks!

Here is a link to my website.

答:
Actually I think the best way to do this is:</p>

```<code>remove_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title' );
add_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_title', 5 );
</code>```

Body:
Actually I think the best way to do this is:

remove_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title' );
add_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_title', 5 );


问:
What is the best comment in source code you have ever encountered?
What is the best comment in source code you have ever encountered?</p>

答:
On initialization of a linked list:

```<code>last = first; /* Biblical reference */
</code>```

Succint and hilarious.

OwnerDisplayName: endpoint

LastEditorDisplayName: Brian

Body:
On initialization of a linked list:

last = first; /* Biblical reference */

Succint and hilarious.

OwnerDisplayName: Brian Clapper

ContentLicense: CC BY-SA 2.5


问:
How to fail a job and make it skip next attempts in the queue in Laravel?
I'm writing a simple queue.

```<code>namespace App\Jobs;

use App\SomeMessageSender;

class MessageJob extends Job
{
    protected $to;
    protected $text;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($to, $text)
    {
        $this->to = $to;
        $this->text = $text;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(SomeMessageSender $sender)
    {
    if ($sender->paramsAreValid($this->to, $this->text) {
            $sender->sendMessage($this->to, $this->text);
        }
    else {
        // Fail without being attempted any further
            throw new Exception ('The message params are not valid');
        }
    }
}
</code>```

If the params are not valid the above code will throw an exception which causes the job to fail but if it still has attempts left, it will be tried again. Instead I want to force this to fail instantly and never attempt again.

How can I do this?

答: Use the InteractsWithQueue trait and call either delete() if you want to delete the job, or fail($exception = null) if you want to fail it. Failing the job means it will be deleted, logged into the failed_jobs table and the JobFailed event is triggered.

Body:
I'm writing a simple queue.

namespace App\Jobs;

use App\SomeMessageSender;

class MessageJob extends Job
{
    protected $to;
    protected $text;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($to, $text)
    {
        $this->to = $to;
        $this->text = $text;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(SomeMessageSender $sender)
    {
    if ($sender->paramsAreValid($this->to, $this->text) {
            $sender->sendMessage($this->to, $this->text);
        }
    else {
        // Fail without being attempted any further
            throw new Exception ('The message params are not valid');
        }
    }
}

If the params are not valid the above code will throw an exception which causes the job to fail but if it still has attempts left, it will be tried again. Instead I want to force this to fail instantly and never attempt again.

How can I do this?


问:
Applied Hierarchical Modeling in Ecology function sim.fn not found
In the book "Applied Hierarchical Modeling in Ecology" (ISBN: 978-0-12-801378-6), the first function called fails immediately.

```<code>library("unmarked")
tmp <- sim.fn( quad.size = 10, cell.size = 1, intensity = 1)

sim.fn( quad.size = 10, cell.size = 1, intensity = 1)
</code>```

I get the message:

```<code>Error: could not find function "sim.fn"
</code>```

I have verified that the library "unmarked" is properly loaded and installed.

What am I missing?

答:
There are further packages to install, as sim.fn is located in the AHMbook library:</p>

```<code>install.packages(c("unmarked", "plotrix", "sp", "raster", "RandomFields", "coda"))
install.packages("AHMbook", repos = "http://mikemeredith.net/R")

library("unmarked")
library("AHMbook")

tmp <- sim.fn( quad.size = 10, cell.size = 1, intensity = 1)
</code>```

Body:
In the book "Applied Hierarchical Modeling in Ecology" (ISBN: 978-0-12-801378-6), the first function called fails immediately.

library("unmarked")
tmp <- sim.fn( quad.size = 10, cell.size = 1, intensity = 1)

sim.fn( quad.size = 10, cell.size = 1, intensity = 1)

I get the message:

Error: could not find function "sim.fn"

I have verified that the library "unmarked" is properly loaded and installed.

What am I missing?

Body:
There are further packages to install, as sim.fn is located in the AHMbook library:

install.packages(c("unmarked", "plotrix", "sp", "raster", "RandomFields", "coda"))
install.packages("AHMbook", repos = "http://mikemeredith.net/R")

library("unmarked")
library("AHMbook")

tmp <- sim.fn( quad.size = 10, cell.size = 1, intensity = 1)


问:
In Java, why can we use the String class as if it were a primitive?
In Java we usually do:

```<code>Class myObject = new Class();
</code>```

because the new keyword returns an address.

But why can we do this?:

```<code>String myString = "Hello";
</code>```

as if String were a primitive?

I asked this to my teacher and he replied that it is because what is in quotes is equivalent to an address, but he is not sure. Can you confirm?

Is "Hello" stored in an instance variable of the class String?

答:
...as if String were a primitive?

As Jon points out in a comment, "has a literal form" != "is a primitive type." :-) Strings have a literal form in Java because the spec defines one for them. String is still an object type.

Some languages have other object types that also have literal forms (JavaScript, for instance, has literal forms for regular expressions, arrays, and non-array objects [its literal form for strings does actually define what it calls a string primitive rather than string object — JavaScript has both primitive and object versions of strings]). I think strings are the only one in Java (other than null, which is the literal for "no object"), although of course there are array initializers, which are similar but not quite the same as literals.

Body:
In Java we usually do:

Class myObject = new Class();

because the new keyword returns an address.

But why can we do this?:

String myString = "Hello";

as if String were a primitive?

I asked this to my teacher and he replied that it is because what is in quotes is equivalent to an address, but he is not sure. Can you confirm?

Is "Hello" stored in an instance variable of the class String?


问:
Table name specified twice both as a target for update and separate source for data
```<code>Update table
Set class = 0
Where TOTAL_HOURS = (SELECT min (TOTAL_HOURS) from tutions);
</code>```

Produced Error:

Table name specified twice both as a target for update and separate source for data.

How can I fix this?

答:
I am guessing you are trying to update tutions with tutions.

Make a nested subquery so that MySQL materializes it and is no longer the same table.

Try this:

```<code>Update tutions
Set class = 0
Where TOTAL_HOURS = (select * from (SELECT min (TOTAL_HOURS) from tutions) t);
</code>```

Body:
Update table
Set class = 0
Where TOTAL_HOURS = (SELECT min (TOTAL_HOURS) from tutions);

Produced Error:

Table name specified twice both as a target for update and separate source for data.

How can I fix this?

Body:
I am guessing you are trying to update tutions with tutions.

Make a nested subquery so that MySQL materializes it and is no longer the same table.

Try this:

Update tutions
Set class = 0
Where TOTAL_HOURS = (select * from (SELECT min (TOTAL_HOURS) from tutions) t);


问:
Python global vs local variables?
I'm having trouble understanding why my code works the way it does. Right now, I'm initializing a global variable i set to 0, so it makes sense that if I print it anywhere outside my function, I should get 0.

When I print i inside the function, I get 6 and 12 after calling the function twice. I think this is because the global i is 0, but some local i variable isn't. However, when I'm calling reach_load with i as a parameter, aren't I passing in the global value of i (0)?

```<code>import sys

d = {}
size_0 = sys.getsizeof(d)
i = 0

def reach_load(d, size_0, i):
    size_0 = sys.getsizeof(d)
    while size_0 == sys.getsizeof(d):
        d[i] = i
        i += 1
    print(i)

reach_load(d, size_0, i)
reach_load(d, size_0, i)
</code>```

答: i is a purely local variable here. It is not linked to the global variable of the same name; the fact that you've called it the same thing makes no difference.

Title: Python global vs local variables?

Body:
I'm having trouble understanding why my code works the way it does. Right now, I'm initializing a global variable i set to 0, so it makes sense that if I print it anywhere outside my function, I should get 0.

When I print i inside the function, I get 6 and 12 after calling the function twice. I think this is because the global i is 0, but some local i variable isn't. However, when I'm calling reach_load with i as a parameter, aren't I passing in the global value of i (0)?

import sys

d = {}
size_0 = sys.getsizeof(d)
i = 0

def reach_load(d, size_0, i):
    size_0 = sys.getsizeof(d)
    while size_0 == sys.getsizeof(d):
        d[i] = i
        i += 1
    print(i)

reach_load(d, size_0, i)
reach_load(d, size_0, i)


问:
CollapsingToolBarLayout, toolbar and menus
I'm trying to get the menu on the toolbar for my app.

Currently, I have a CollapsingToolbarLayout. When the user moves up the recyclerview, the image of an island reduces in size and then eventually it collapses into the toolbar.

This is what it looks like when it is expanded:

This is what it looks like when it has collapsed:

Now, you can see that when it is expanded, the heart icon is duplicated (once in the FAB and once in the toolbar. I only want the heart icon to appear in the toolbar when the FAB is no longer visible otherwise, I feel that it will be confusing to a user when you have two buttons on the screen that does exactly the same thing.

How can I only show the heart icon on the toolbar when the collapsingToolBarLayout is fully collapsed? I tried to look for some type of onCollapse listener but no luck.

This is the code for the xml:

```<code>   <android.support.design.widget.AppBarLayout
        android:layout_height="192dp"
        android:id="@+id/appbar"
        android:layout_width="match_parent">
<!--        android:fitsSystemWindows="true"-->
        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"

            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginStart="16dp"
            app:expandedTitleMarginEnd="32dp">

            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                android:fitsSystemWindows="true"
                android:src="@drawable/ocean395"
                app:layout_collapseMode="pin" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:minHeight="?attr/actionBarSize"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"/>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>
</code>```

答:
hey you can add the listener like this

```<code>AppBarLayout appBarLayout = (AppBarLayout)view.findViewById(R.id.app_bar_layout);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if (Math.abs(verticalOffset) == appBarLayout.getTotalScrollRange()) {
            // Collapsed (make button visible and fab invisible)
        } else if (verticalOffset == 0) {
            // Expanded (make fab visible and toolbar button invisible)
        } else {
            // Somewhere in between
        }
    }
}););
</code>```

referred from How can i determine that CollapsingToolbar is collapsed?

Body:
I'm trying to get the menu on the toolbar for my app.

Currently, I have a CollapsingToolbarLayout. When the user moves up the recyclerview, the image of an island reduces in size and then eventually it collapses into the toolbar.

This is what it looks like when it is expanded:

This is what it looks like when it has collapsed:

Now, you can see that when it is expanded, the heart icon is duplicated (once in the FAB and once in the toolbar. I only want the heart icon to appear in the toolbar when the FAB is no longer visible otherwise, I feel that it will be confusing to a user when you have two buttons on the screen that does exactly the same thing.

How can I only show the heart icon on the toolbar when the collapsingToolBarLayout is fully collapsed? I tried to look for some type of onCollapse listener but no luck.

This is the code for the xml:

   <android.support.design.widget.AppBarLayout
        android:layout_height="192dp"
        android:id="@+id/appbar"
        android:layout_width="match_parent">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"

            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginStart="16dp"
            app:expandedTitleMarginEnd="32dp">

            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                android:fitsSystemWindows="true"
                android:src="@drawable/ocean395"
                app:layout_collapseMode="pin" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:minHeight="?attr/actionBarSize"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"/>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

Body:
hey you can add the listener like this

AppBarLayout appBarLayout = (AppBarLayout)view.findViewById(R.id.app_bar_layout);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if (Math.abs(verticalOffset) == appBarLayout.getTotalScrollRange()) {
            // Collapsed (make button visible and fab invisible)
        } else if (verticalOffset == 0) {
            // Expanded (make fab visible and toolbar button invisible)
        } else {
            // Somewhere in between
        }
    }
}););

referred from How can i determine that CollapsingToolbar is collapsed?


问:
Refreshing Grails applicationContext
In my configuration's spring/resources.xml file, I define a bean like this :

```<code><bean id="myService" class="org.springframework.remoting.caucho.HessianProxyFactoryBean">
    <property name="serviceUrl" value="http://${remote.host}:8080/MyAgent/remoting/MyService"/>
    <property name="serviceInterface" value="services.MyService"/>
</bean>
</code>```

In my Config.groovy file I have :
remote.host = "someipaddress"

Now I'd like to change this placeholder's value at runtime. In a regular spring app, I do this through a PropertyPlaceHolderConfigurer, then I refresh the context and it works.

In Grails, how can I refresh the context ?

Regards,

Philippe

答:
Ok I give up the refreshing approach.
As a workaround, I created a grails service that looks like this :

```<code>class myService {
    def myRemoteService
    static transactional = false

    private MyRemoteService getService(String remoteServiceURL) {
        HessianProxyFactory factory = new HessianProxyFactory();
        try {
            return (MyRemoteService) factory.create(MyRemoteService.class, url);
        }
        catch (MalformedURLException e) {
            e.printStackTrace()
        }
        return null
    }

    def someRemoteMethod(String remoteServiceURL) {
        getService(remoteServiceURL).myRemoteMethod()
    }
}
</code>```

This allows me to invoke the remote service on any distant machine dinamically.

I'm still interested in a cleaner solution as this makes me rewrite a wrapper method for each remote method :-S

Title: Refreshing Grails applicationContext

Body:
In my configuration's spring/resources.xml file, I define a bean like this :

<bean id="myService" class="org.springframework.remoting.caucho.HessianProxyFactoryBean">
    <property name="serviceUrl" value="http://${remote.host}:8080/MyAgent/remoting/MyService"/>
    <property name="serviceInterface" value="services.MyService"/>
</bean>

In my Config.groovy file I have :
remote.host = "someipaddress"

Now I'd like to change this placeholder's value at runtime. In a regular spring app, I do this through a PropertyPlaceHolderConfigurer, then I refresh the context and it works.

In Grails, how can I refresh the context ?

Regards,

Philippe

Body:
Ok I give up the refreshing approach.
As a workaround, I created a grails service that looks like this :

class myService {
    def myRemoteService
    static transactional = false

    private MyRemoteService getService(String remoteServiceURL) {
        HessianProxyFactory factory = new HessianProxyFactory();
        try {
            return (MyRemoteService) factory.create(MyRemoteService.class, url);
        }
        catch (MalformedURLException e) {
            e.printStackTrace()
        }
        return null
    }

    def someRemoteMethod(String remoteServiceURL) {
        getService(remoteServiceURL).myRemoteMethod()
    }
}

This allows me to invoke the remote service on any distant machine dinamically.

I'm still interested in a cleaner solution as this makes me rewrite a wrapper method for each remote method :-S


问:
Loading old bootloader in assembly x86
I am writing my own bootloader in NASM x86 on x86_64 architechture, for starters I am just trying to copy the existing bootloader into second sector by using dd, then copy it back and run it from assembly.

file.asm

```<code>org 0x7c00

jmp 0:start

start:
mov ax, cs
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x8000

mov           ah, 0x02
mov           al, 1
mov           dl, 0x80
mov           ch, 0
mov           dh, 0
mov           cl, 3
mov           bx, 0x7e00
int           0x13

jmp 0x7e00
times 510-($-$$) db 0
dw 0xaa55

times (1024 - ($ - $$)) db 0x00
third_sector:
mov           ah, 0x02
mov           al, 1
mov           dl, 0x80
mov           ch, 0
mov           dh, 0
mov           cl, 2
mov           bx, 0x7c00
int           0x13

jmp           0x7c00
</code>```

The code sets up the stack, then pats itself to 1024 bytes with zeroes to have the last bit of code in third sector of the disk, then it loads the second sector from the disk into the first one and jumps to the first sector.

src.sh

```<code>#!/bin/bash
dd bs=1 count=512 if=/dev/c0d0 of=tmp
nasm -f bin file.asm -o file
dd bs=1 count=1200 if=file of=/dev/c0d0
dd bs=1 count=512 seek=512 if=tmp of=/dev/c0d0
</code>```

What I am doing is copying the original bootloader into temporary file called tmp, then compiling my programme and putting it into old bootloader's place (/dev/c0d0 since I am working on MINIX 3.3.0), then moving old bootloader into second sector.

The result is "Booting from hard disk" string, which is fine, and then I get "NetBSD MBR boot
 Error P" which corresponds to "no netBSD partition".

Edit: Pasted the wrong asm file.
Second edit: Error changed, but still persists.

答:
I can cram everything in first 512B without trouble, but then after reading the old bootloader I can no longer jump to the beginning

Of course you can't both run in the 7C00-7DFF area, and also load other sector into it, so what you need is to prepare some code which will run outside of 7C00-7DFF, it will load the original boot sector to the expected 0000:7C00, and execute it just as BIOS would.

I tried to modify your code to work like that, but I have no means to debug/verify if it works, so proceed with caution (I used ndisasm to disassemble resulting binary, and everything looks OK, ie. the relocated code does not depend on it's address, so you can move it freely to any memory, and it should load+execute that sector to 7C00.

Just make sure you don't add anything to that code, what would break after relocation to 7e00.

```<code>org 0x7c00

jmp 0:start

start:
mov ax, cs     ; ax = 0
mov ds, ax
mov es, ax
mov ss, ax
mov sp, ax     ; ss:sp = 0:0
; relocate second boot loader code outside of 7C00-7DFF (to 7E00)
mov si, boot_loader_code   ; address of code to relocate
mov di, 0x7e00             ; new address of code
mov cx, boot_loader_code_length
cld
rep movsb
; execute the relocated second boot loader
jmp 0x7e00

boot_loader_code:
    ; load second boot loader to 0:7c00 and execute it
    mov     ah, 0x02    ; load sector service
    mov     al, 1       ; load 1 sector
    ; mov     dl, 0x80    ; drive 0
    ; DL is set by BIOS originally
    ; and this code did/will not change it
    mov     ch, 0       ; track/cylinder
    mov     dh, 0       ; head number
    mov     cl, 3       ; sector number
    mov     bx, 0x7c00  ; es:bx pointer to buffer
    int     0x13        ; BIOS "load sector" service
    jmp     0:0x7c00
boot_loader_code_length EQU ($ - boot_loader_code)

    times   510-($-$$) db 0
    dw      0xaa55
</code>```

still isn't working

Well, you can hardly program in assembler without debugger, there's too much what can go wrong and every detail may matter. When you are experienced in asm, you can pull it out, but if you are learning, get some PC emulator where you can also debug things, like bochs. And use documentation first (like that incbin comment from you, it's described in NASM docs of course, what it does exactly).

I adjusted the source by comments of Michael, but I have still no means to verify/debug it (too lazy to install bochs + learn how to set up bootloader sector), but the code itself is "ok", it does mostly what comments say. Whether that is enough or correct to boot a PC machine, that's different question. It just fixes obvious problem of your code in question to trying to have "third" part outside of your 512B single sector block.

Title: Loading old bootloader in assembly x86

Body:
I am writing my own bootloader in NASM x86 on x86_64 architechture, for starters I am just trying to copy the existing bootloader into second sector by using dd, then copy it back and run it from assembly.

file.asm

org 0x7c00

jmp 0:start

start:
mov ax, cs
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x8000

mov           ah, 0x02
mov           al, 1
mov           dl, 0x80
mov           ch, 0
mov           dh, 0
mov           cl, 3
mov           bx, 0x7e00
int           0x13

jmp 0x7e00
times 510-($-$$) db 0
dw 0xaa55

times (1024 - ($ - $$)) db 0x00
third_sector:
mov           ah, 0x02
mov           al, 1
mov           dl, 0x80
mov           ch, 0
mov           dh, 0
mov           cl, 2
mov           bx, 0x7c00
int           0x13

jmp           0x7c00

The code sets up the stack, then pats itself to 1024 bytes with zeroes to have the last bit of code in third sector of the disk, then it loads the second sector from the disk into the first one and jumps to the first sector.

src.sh

#!/bin/bash
dd bs=1 count=512 if=/dev/c0d0 of=tmp
nasm -f bin file.asm -o file
dd bs=1 count=1200 if=file of=/dev/c0d0
dd bs=1 count=512 seek=512 if=tmp of=/dev/c0d0

What I am doing is copying the original bootloader into temporary file called tmp, then compiling my programme and putting it into old bootloader's place (/dev/c0d0 since I am working on MINIX 3.3.0), then moving old bootloader into second sector.

The result is "Booting from hard disk" string, which is fine, and then I get "NetBSD MBR boot
 Error P" which corresponds to "no netBSD partition".

Edit: Pasted the wrong asm file.
Second edit: Error changed, but still persists.

Body:
I can cram everything in first 512B without trouble, but then after reading the old bootloader I can no longer jump to the beginning

Of course you can't both run in the 7C00-7DFF area, and also load other sector into it, so what you need is to prepare some code which will run outside of 7C00-7DFF, it will load the original boot sector to the expected 0000:7C00, and execute it just as BIOS would.

I tried to modify your code to work like that, but I have no means to debug/verify if it works, so proceed with caution (I used ndisasm to disassemble resulting binary, and everything looks OK, ie. the relocated code does not depend on it's address, so you can move it freely to any memory, and it should load+execute that sector to 7C00.

Just make sure you don't add anything to that code, what would break after relocation to 7e00.

org 0x7c00

jmp 0:start

start:
mov ax, cs     ; ax = 0
mov ds, ax
mov es, ax
mov ss, ax
mov sp, ax     ; ss:sp = 0:0
; relocate second boot loader code outside of 7C00-7DFF (to 7E00)
mov si, boot_loader_code   ; address of code to relocate
mov di, 0x7e00             ; new address of code
mov cx, boot_loader_code_length
cld
rep movsb
; execute the relocated second boot loader
jmp 0x7e00

boot_loader_code:
    ; load second boot loader to 0:7c00 and execute it
    mov     ah, 0x02    ; load sector service
    mov     al, 1       ; load 1 sector
    ; mov     dl, 0x80    ; drive 0
    ; DL is set by BIOS originally
    ; and this code did/will not change it
    mov     ch, 0       ; track/cylinder
    mov     dh, 0       ; head number
    mov     cl, 3       ; sector number
    mov     bx, 0x7c00  ; es:bx pointer to buffer
    int     0x13        ; BIOS "load sector" service
    jmp     0:0x7c00
boot_loader_code_length EQU ($ - boot_loader_code)

    times   510-($-$$) db 0
    dw      0xaa55

still isn't working

Well, you can hardly program in assembler without debugger, there's too much what can go wrong and every detail may matter. When you are experienced in asm, you can pull it out, but if you are learning, get some PC emulator where you can also debug things, like bochs. And use documentation first (like that incbin comment from you, it's described in NASM docs of course, what it does exactly).

I adjusted the source by comments of Michael, but I have still no means to verify/debug it (too lazy to install bochs + learn how to set up bootloader sector), but the code itself is "ok", it does mostly what comments say. Whether that is enough or correct to boot a PC machine, that's different question. It just fixes obvious problem of your code in question to trying to have "third" part outside of your 512B single sector block.


问:
Issue when writing matrix to file using csvwrite
I am trying to output the matrix to a CSV file (comma separated) using this function csvwrite('myMatrix.dat',L); ( where L is square matrix) I got this error:

```<code>>> csvwrite('myMatrix.dat',L);
Error using sprintf
Function is not defined for sparse inputs.

Error in dlmwrite (line 169)
        str = sprintf(format,m(i,:));

Error in csvwrite (line 42)
dlmwrite(filename, m, ',', r, c);
</code>```

Kindly, what's wrong with this?

答:
This answer was to answer OP's original error from using:

csvwrite(string('myMatrix'),L);

Error using csvwrite (line 30)
FILENAME must be a character vector.
The error you're seeing is an issue with your input (arguments). It's telling you that the file name must be a "character vector".

According to Matlab's documentation:

There are two ways to represent text in MATLAB®. Starting in R2016b, you can store text in string arrays. And in any version of MATLAB, you can store text in character arrays. A typical use for character arrays is to store pieces of text as character vectors. MATLAB displays strings with double quotes and character vectors with single quotes.

http://mathworks.com/help/matlab/matlab_prog/creating-character-arrays.html#briuv_1-1

In simple words. The wrong type was being used as an argument.

To provide a hint for debugging the new error.

Limitations
csvwrite writes a maximum of five significant digits. If you need greater precision, use dlmwrite with a precision argument.

csvwrite does not accept cell arrays for the input matrix M. To export a cell array that contains only numeric data, use cell2mat to convert the cell array to a numeric matrix before calling csvwrite.

http://mathworks.com/help/matlab/ref/csvwrite.html?requestedDomain=www.mathworks.com

Try checking what's in L. whos('L') would also help you get more info on it. An easy way to view what's in your variables, is double click from the workspace. Another way is by creating a break point on your call to csvwrite within a script, then use the debugger and calling for L once you know it's loaded into memory. If you still don't know what's going on, then try 'step in' line by line.

csvwrite does not accept cell arrays.

Body:
I am trying to output the matrix to a CSV file (comma separated) using this function csvwrite('myMatrix.dat',L); ( where L is square matrix) I got this error:

>> csvwrite('myMatrix.dat',L);
Error using sprintf
Function is not defined for sparse inputs.

Error in dlmwrite (line 169)
        str = sprintf(format,m(i,:));

Error in csvwrite (line 42)
dlmwrite(filename, m, ',', r, c);

Kindly, what's wrong with this?

ContentLicense: CC BY-SA 4.0


问:
How can I reduce lag when loading background images in android studio?
I'm developing an Android game through android studio, but when I draw moving background images through Bitmap.decodeResource and drawBitmap, my game's FPS goes down to 10 which is unplayable. Is there an alternative way to draw slowly moving images in the background? I'd like the image quality to be reasonable still, but the background will just be a few pictures of some trees sliding across the screen.</p>

答:
I hope you didn't call Bitmap.decodeResource every time you render the scene. You have to call it just once - at the beginning, when you initialize all the other stuff:

 Bitmap gameBackground=BitmapFactory.decodeResource(getResources(), R.drawable.game_background)

Then, in the game loop, you can render the image with canvas.drawBitmap(gameBackground). Of course at the end, after the scene loop, you have to free the allocated memory using gameBackground.recycle().


问:
php mysqli query function not executing when the query contains php variable
I would really like some help. I am trying to return a record from a table where I am search that table by first name and last name, which is one string in a php variable $employee_coor.

This problem is when ever I use the variable within my query statement it returns nothing. No errors nothing. However, if I echo the variable to the screen the employee's full name is seen. Then I tried copying that full name into the statement and the record would be then returned.

I also tried mysqli_num_rows on the query to be sure if a record is being selected or not and it returned 0 when echoed to the screen.

I really don't know why I am getting this, I hope it's something I am over looking or something like that.  The code below shows the script.

UPDATE: I tested the exact query itself in the MySQL client and it works perfectly. The only difference would be the query in MySQL qould have a full name as opposed to a php variable representing that name.

```<code>    <?php
     include_once('dbconnect.php');

     if (!empty($_GET['employees'])) {

     $employee_coor = $_GET['employees'];

     $select = "SELECT * FROM employees
                WHERE employees.employee_fname = substring_index('$employee_coor',' ',1)
                AND employees.employee_lname = substring_index('$employee_coor',' ',-1)";

           $query = mysqli_query($con,$select);

           $cooridinator = mysqli_fetch_assoc($query);

           var_dump($cooridinator);

   } else{}
   ?>
</code>```

答: I think your problem is that you try to execute substring_index() inside your SELECT statement.  You can't do that.  The best thing to do is split your employee name into 2 variables before you use them in the SELECT statement.</p>

Body:
I would really like some help. I am trying to return a record from a table where I am search that table by first name and last name, which is one string in a php variable $employee_coor.

This problem is when ever I use the variable within my query statement it returns nothing. No errors nothing. However, if I echo the variable to the screen the employee's full name is seen. Then I tried copying that full name into the statement and the record would be then returned.

I also tried mysqli_num_rows on the query to be sure if a record is being selected or not and it returned 0 when echoed to the screen.

I really don't know why I am getting this, I hope it's something I am over looking or something like that.  The code below shows the script.

UPDATE: I tested the exact query itself in the MySQL client and it works perfectly. The only difference would be the query in MySQL qould have a full name as opposed to a php variable representing that name.

    <?php
     include_once('dbconnect.php');

     if (!empty($_GET['employees'])) {

     $employee_coor = $_GET['employees'];

     $select = "SELECT * FROM employees
                WHERE employees.employee_fname = substring_index('$employee_coor',' ',1)
                AND employees.employee_lname = substring_index('$employee_coor',' ',-1)";

           $query = mysqli_query($con,$select);

           $cooridinator = mysqli_fetch_assoc($query);

           var_dump($cooridinator);

   } else{}
   ?>


问:
Node script ReferenceError: fs is not defined error in test script
I am trying out node to run a simple js script to read a file,
following is the content of my script:

```<code>"use strict"
fs = require('fs');
var args = process.argv.slice(2);
fs.readFile(args, 'utf8', function (err,data) {
  if (err) {
      return console.log(err);
        }
    console.log("Reading from file " + args);
    console.log(data);
});
</code>```

when I try to run this using the following command:
node myTestFile.js testFile

I get this error:

```<code>fs = require('fs');
   ^
ReferenceError: fs is not defined
    at Object.<anonymous>     (/<Path to file>/myTestFile.js:2:4)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:393:7)
at startup (bootstrap_node.js:150:9)
at bootstrap_node.js:508:3
</code>```

Isn't fs in node like a library like stdio in c ?

Do we have to explicitly define the library path somewhere in node ?

How can I get the above example to work ?

答:
The problem is not require('fs'), but the left side; you'd get the same error with

```<code>fs = 42;
</code>```

That's because there is no variable fs defined. Define it with const, let, or var, like this:

```<code>const fs = require('fs');
</code>```

Body:
I am trying out node to run a simple js script to read a file,
following is the content of my script:

"use strict"
fs = require('fs');
var args = process.argv.slice(2);
fs.readFile(args, 'utf8', function (err,data) {
  if (err) {
      return console.log(err);
        }
    console.log("Reading from file " + args);
    console.log(data);
});

when I try to run this using the following command:
node myTestFile.js testFile

I get this error:

fs = require('fs');
   ^
ReferenceError: fs is not defined
    at Object.<anonymous>     (/<Path to file>/myTestFile.js:2:4)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:393:7)
at startup (bootstrap_node.js:150:9)
at bootstrap_node.js:508:3

Isn't fs in node like a library like stdio in c ?

Do we have to explicitly define the library path somewhere in node ?

How can I get the above example to work ?

Body:
The problem is not require('fs'), but the left side; you'd get the same error with

fs = 42;

That's because there is no variable fs defined. Define it with const, let, or var, like this:

const fs = require('fs');


问:
C# how do I use a partially filled array in a method?
My instructor wants us to create an array of 10 elements and then fill it with random numbers using console input and then multiply all the numbers together to get the product.  I can't figure out how to pass the array to a method and then successfully get the product.  Do I use a for loop?  I don't think I can use a foreach loop because it could be partially filled.  How do I even pass the array to the method in the first place?

Here's what I have so far to store the values in the array.

```<code>for (int i = 0; i < SIZE; i++)
{

    bool valid = false;
    do
    {
         Write("Enter an integer value or 0 to stop ");
         string input = ReadLine();
         valid = int.TryParse(input, out userInput);
    } while (!valid);

    if (userInput == 0)
    {
         break;
    }
    array[i] = userInput;
}

product = p.ArrayProduct(array.Length);
</code>```

答:
Here's an example of tracking the number of entries in a separate variable and passing that to the processing function along with the array:</p>

```<code>static void Main(string[] args)
{
    int SIZE = 10;
    int numEntries = 0;
    int[] array = new int[SIZE];

    Console.WriteLine("Enter up to " + SIZE.ToString() + " integer(s).");

    string input;
    int userInput;
    for (int i = 0; i < array.Length; i++)
    {
        bool valid = false;
        do
        {
            Console.Write("Enter integer #" + (i+1).ToString() + " or 0 to stop: ");
            input = Console.ReadLine();
            valid = int.TryParse(input, out userInput);
            if (!valid)
            {
                Console.WriteLine("Invalid entry!");
            }
        } while (!valid);

        if (userInput == 0)
        {
            break;
        }

        numEntries++;
        array[i] = userInput;
    }

    if (numEntries > 0)
    {
        int product = ArrayProduct(array, numEntries);
        Console.WriteLine("The product is " + product.ToString("n0") + ".");
    }
    else
    {
        Console.WriteLine("No entries were made!");
    }

    Console.Write("Press [Enter] to quit.");
    Console.ReadLine();
}

private static int ArrayProduct(int[] arr, int length)
{
    int product = 1;
    if (length <= arr.Length)
    {
        for(int i = 0; i < length; i++)
        {
            product = product * arr[i];
        }
    }
    return product;
}
</code>```

Body:
My instructor wants us to create an array of 10 elements and then fill it with random numbers using console input and then multiply all the numbers together to get the product.  I can't figure out how to pass the array to a method and then successfully get the product.  Do I use a for loop?  I don't think I can use a foreach loop because it could be partially filled.  How do I even pass the array to the method in the first place?

Here's what I have so far to store the values in the array.

for (int i = 0; i < SIZE; i++)
{

    bool valid = false;
    do
    {
         Write("Enter an integer value or 0 to stop ");
         string input = ReadLine();
         valid = int.TryParse(input, out userInput);
    } while (!valid);

    if (userInput == 0)
    {
         break;
    }
    array[i] = userInput;
}

product = p.ArrayProduct(array.Length);

Body:
Here's an example of tracking the number of entries in a separate variable and passing that to the processing function along with the array:

static void Main(string[] args)
{
    int SIZE = 10;
    int numEntries = 0;
    int[] array = new int[SIZE];

    Console.WriteLine("Enter up to " + SIZE.ToString() + " integer(s).");

    string input;
    int userInput;
    for (int i = 0; i < array.Length; i++)
    {
        bool valid = false;
        do
        {
            Console.Write("Enter integer #" + (i+1).ToString() + " or 0 to stop: ");
            input = Console.ReadLine();
            valid = int.TryParse(input, out userInput);
            if (!valid)
            {
                Console.WriteLine("Invalid entry!");
            }
        } while (!valid);

        if (userInput == 0)
        {
            break;
        }

        numEntries++;
        array[i] = userInput;
    }

    if (numEntries > 0)
    {
        int product = ArrayProduct(array, numEntries);
        Console.WriteLine("The product is " + product.ToString("n0") + ".");
    }
    else
    {
        Console.WriteLine("No entries were made!");
    }

    Console.Write("Press [Enter] to quit.");
    Console.ReadLine();
}

private static int ArrayProduct(int[] arr, int length)
{
    int product = 1;
    if (length <= arr.Length)
    {
        for(int i = 0; i < length; i++)
        {
            product = product * arr[i];
        }
    }
    return product;
}


问:
How to pass run options to docker-compose
I'm trying to run docker container which uses mongo image, and pass --user argument, it's ok if I run the following command

```<code>docker run -d --user mongodb mongo
</code>```

But I don't know how to use --user argument with docker-compose configuration

```<code>version: '2'
services:
    ...
    mongodb:
        image: mongo
</code>```

How to pass docker run options to docker-compose to make it work?

```<code>docker-compose up -d
</code>```

答:
Works as you'd expect.

```<code>version: '2'
services:
    ...
    mongodb:
        image: mongo
        user: rashad
</code>```

Docs ref here.

Body:
I'm trying to run docker container which uses mongo image, and pass --user argument, it's ok if I run the following command

docker run -d --user mongodb mongo

But I don't know how to use --user argument with docker-compose configuration

version: '2'
services:
    ...
    mongodb:
        image: mongo

How to pass docker run options to docker-compose to make it work?

docker-compose up -d

Body:
Works as you'd expect.

version: '2'
services:
    ...
    mongodb:
        image: mongo
        user: rashad

Docs ref here.


问:
Delphi component design, add a field in TFieldDataLink
I am making a new vcl component, which is kinda finished except for one small detail.

The component uses TFieldDataLink to make a Datasource and Datafield property, this is working just fine, the problem is i need a second field property visible in the object inspector, from the same Datasource as the DataField.

I don't really need a 'TFields' property where you can add multiple fields, one additional FieldProperty is enough.

I added a simple string property 'DataTypeField': String in the published section of my class, which works fine, but you have to type the value in the object inspector in design time and it would of course be better if the property would let the user pick the field from the Datalink.

Does anyone have an idea how to do that?

Basicly my class looks like this (i have removed lots of other irrelevant properties and functions)

```<code>TFlexRtfEditor = class(TcxGroupBox)
  Editor: TdxRichEditControl;
private
  FDataLink: TFieldDataLink;
  function GetDataField: string;
  function GetDataSource: TdataSource;
  procedure SetDataField(const Value: string);
  procedure SetDataSource(const Value: TdataSource);
protected
public
published
  property DataField: string read GetDataField write SetDataField;
  property DataSource: TdataSource read GetDataSource write SetDataSource;
end;
</code>```

in constructor
    FDataLink := TFieldDataLink.Create;
    FDataLink.Control := Self;

in destructor
    FDataLink.Free;

I figured if i needed a second field i would need to make a new class, on type
TFieldDataLink, add the property DataTypeField in the published section and use this class to create the FDatalink property in the constructor

```<code>TFlexRtfEditorDataLink = Class(TFieldDataLink)
private
   fDataTypeField: String;
   procedure SetDataTypeField(const Value: String);
published
   property DataTypeField: String read fDataTypeField write SetDataTypeField;
End;

FDataLink := TFlexRtfEditorDataLink.Create;
FDataLink.Control := Self;
</code>```

But although this compiles it doesn't make the DataTypeField property available in the object inspector.

Does anyone know what i'm doing wrong?
Is this because the FDataLink variable is in the private section of the base class?

答:
If you want your alternate DataField to show up in the OI and select its value from the drop-down list of fields
you would usually get in the DataField property of a TDBEdit, this is fairly easy to do,
but you need to register a property editor for it in the IDE for it to work.  Also, I think there is an easier
way to do it than deriving a TFieldDataLink descendant.

I'm afraid I found your terminology and description of what you are trying to do a bit confusing, so in the following, I'm going to refer to this alternate DataField as AltDataField to avoid confusion.
I'm also going to show how to add a MainDataField that works as an alias for the DataField property.

In the main component code:

```<code>type
    TFlexRtfEditor = class(TcxGroupBox)
      //Editor: TdxRichEditControl; omitted for simplicity
    private
      FDataLink: TFieldDataLink;
      FAltDataLink: TFieldDataLink;
      function GetMainDataField: string;
      function GetDataSource: TdataSource;
      procedure SetMainDataField(const Value: string);
      procedure SetDataSource(const Value: TdataSource);
    function GetAltDataField: String;
    procedure SetAltDataField(const Value: String);
    protected
    public
      constructor Create(AOwner : TComponent); override;
      destructor Destroy; override;
    published
      property MainDataField: string read GetMainDataField write SetMainDataField;  // a quasi-alias for DataField
      property DataField: String read GetMainDataField write SetMainDataField;  //  the usual DB-aware component's DataField
      property AltDataField: String read GetAltDataField write SetAltDataField;
      property DataSource: TdataSource read GetDataSource write SetDataSource;
    end;

implementation

constructor TFlexRtfEditor.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FDataLink := TFieldDataLink.Create;
  FAltDataLink := TFieldDataLink.Create;
end;

destructor TFlexRtfEditor.Destroy;
begin
  FAltDataLink.Free;
  FDataLink.Free;
  inherited;
end;

function TFlexRtfEditor.GetMainDataField: string;
begin
  Result := FDataLink.FieldName;
end;

function TFlexRtfEditor.GetDataSource: TdataSource;
begin
  Result := FDataLink.DataSource;
end;

procedure TFlexRtfEditor.SetMainDataField(const Value: string);
begin
  FDataLink.FieldName := Value; //FDataLink.DataSource.DataSet.FindField(Value);
end;

procedure TFlexRtfEditor.SetDataSource(const Value: TdataSource);
begin
  FDataLink.DataSource := Value;
  FAltDataLink.DataSource := Value;
end;

function TFlexRtfEditor.GetAltDataField: String;
begin
  Result := FAltDataLink.FieldName;
end;

procedure TFlexRtfEditor.SetAltDataField(const Value: String);
begin
  FAltDataLink.FieldName := Value;
end;
</code>```

As you can see, the AltDataField is provided with its own FieldDataLink,
which is far simpler than having to to derive (and debug) your own
TFieldDataLink-descendant.

In your component registration unit:

```<code>interface

uses SysUtils, Classes, DesignIntf, DesignEditors, DSDesign, DBReg, FlexRTFu;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('MA', [TFlexRtfEditor]);
  RegisterPropertyEditor(TypeInfo(string), TComponent, 'MainDataField', TDataFieldProperty);
  RegisterPropertyEditor(TypeInfo(string), TComponent, 'AltDataField', TDataFieldProperty);
end;

end.
</code>```

Btw, you might want to look at the source code of TDBEdit for some extra details of how the component's properties interact with its FieldDataLink.

Also btw, my package's Requires clause looks like this:

```<code>requires
  rtl,
  vcl,
  dbrtl,
  vcldb,
  cxLibraryD7,
  dxThemeD7,
  dxCoreD7,
  dxGDIPlusD7,
  vclx,
  cxEditorsD7,
  cxDataD7,
  vcljpg,
  dxSkinBlackD7,
  dxSkinsCoreD7,
  dxSkinBlueD7,
  dxSkinBlueprintD7,
  dxSkinCaramelD7,
  dxSkinCoffeeD7,
  dxSkinDarkRoomD7,
  dxSkinDarkSideD7,
  dxSkinDevExpressDarkStyleD7,
  dxSkinDevExpressStyleD7,
  dxSkinFoggyD7,
  dxSkinGlassOceansD7,
  dxSkinHighContrastD7,
  dxSkiniMaginaryD7,
  dxSkinLilianD7,
  dxSkinLiquidSkyD7,
  dxSkinLondonLiquidSkyD7,
  dxSkinMcSkinD7,
  dxSkinMetropolisD7,
  dxSkinMetropolisDarkD7,
  dxSkinMoneyTwinsD7,
  dxSkinOffice2007BlackD7,
  dxSkinOffice2007BlueD7,
  dxSkinOffice2007GreenD7,
  dxSkinOffice2007PinkD7,
  dxSkinOffice2007SilverD7,
  dxSkinOffice2010BlackD7,
  dxSkinOffice2010BlueD7,
  dxSkinOffice2010SilverD7,
  dxSkinOffice2013DarkGrayD7,
  dxSkinOffice2013LightGrayD7,
  dxSkinOffice2013WhiteD7,
  dxSkinPumpkinD7,
  dxSkinSevenClassicD7,
  dxSkinSevenD7,
  dxSkinSharpD7,
  dxSkinSharpPlusD7,
  dxSkinSilverD7,
  dxSkinSpringTimeD7,
  dxSkinStardustD7,
  dxSkinSummer2008D7,
  dxSkinTheAsphaltWorldD7,
  dxSkinValentineD7,
  dxSkinVS2010D7,
  dxSkinWhiteprintD7,
  dxSkinXmas2008BlueD7,
  designide,
  vclactnband,
  dcldb,
  vcldesigner,
  designdgm,
  dclstd;
</code>```

Body:
I am making a new vcl component, which is kinda finished except for one small detail.

The component uses TFieldDataLink to make a Datasource and Datafield property, this is working just fine, the problem is i need a second field property visible in the object inspector, from the same Datasource as the DataField.

I don't really need a 'TFields' property where you can add multiple fields, one additional FieldProperty is enough.

I added a simple string property 'DataTypeField': String in the published section of my class, which works fine, but you have to type the value in the object inspector in design time and it would of course be better if the property would let the user pick the field from the Datalink.

Does anyone have an idea how to do that?

Basicly my class looks like this (i have removed lots of other irrelevant properties and functions)

TFlexRtfEditor = class(TcxGroupBox)
  Editor: TdxRichEditControl;
private
  FDataLink: TFieldDataLink;
  function GetDataField: string;
  function GetDataSource: TdataSource;
  procedure SetDataField(const Value: string);
  procedure SetDataSource(const Value: TdataSource);
protected
public
published
  property DataField: string read GetDataField write SetDataField;
  property DataSource: TdataSource read GetDataSource write SetDataSource;
end;

in constructor
    FDataLink := TFieldDataLink.Create;
    FDataLink.Control := Self;

in destructor
    FDataLink.Free;

I figured if i needed a second field i would need to make a new class, on type
TFieldDataLink, add the property DataTypeField in the published section and use this class to create the FDatalink property in the constructor

TFlexRtfEditorDataLink = Class(TFieldDataLink)
private
   fDataTypeField: String;
   procedure SetDataTypeField(const Value: String);
published
   property DataTypeField: String read fDataTypeField write SetDataTypeField;
End;

FDataLink := TFlexRtfEditorDataLink.Create;
FDataLink.Control := Self;

But although this compiles it doesn't make the DataTypeField property available in the object inspector.

Does anyone know what i'm doing wrong?
Is this because the FDataLink variable is in the private section of the base class?

Body:
If you want your alternate DataField to show up in the OI and select its value from the drop-down list of fields
you would usually get in the DataField property of a TDBEdit, this is fairly easy to do,
but you need to register a property editor for it in the IDE for it to work.  Also, I think there is an easier
way to do it than deriving a TFieldDataLink descendant.

I'm afraid I found your terminology and description of what you are trying to do a bit confusing, so in the following, I'm going to refer to this alternate DataField as AltDataField to avoid confusion.
I'm also going to show how to add a MainDataField that works as an alias for the DataField property.

In the main component code:

type
    TFlexRtfEditor = class(TcxGroupBox)
      //Editor: TdxRichEditControl; omitted for simplicity
    private
      FDataLink: TFieldDataLink;
      FAltDataLink: TFieldDataLink;
      function GetMainDataField: string;
      function GetDataSource: TdataSource;
      procedure SetMainDataField(const Value: string);
      procedure SetDataSource(const Value: TdataSource);
    function GetAltDataField: String;
    procedure SetAltDataField(const Value: String);
    protected
    public
      constructor Create(AOwner : TComponent); override;
      destructor Destroy; override;
    published
      property MainDataField: string read GetMainDataField write SetMainDataField;  // a quasi-alias for DataField
      property DataField: String read GetMainDataField write SetMainDataField;  //  the usual DB-aware component's DataField
      property AltDataField: String read GetAltDataField write SetAltDataField;
      property DataSource: TdataSource read GetDataSource write SetDataSource;
    end;

implementation

constructor TFlexRtfEditor.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FDataLink := TFieldDataLink.Create;
  FAltDataLink := TFieldDataLink.Create;
end;

destructor TFlexRtfEditor.Destroy;
begin
  FAltDataLink.Free;
  FDataLink.Free;
  inherited;
end;

function TFlexRtfEditor.GetMainDataField: string;
begin
  Result := FDataLink.FieldName;
end;

function TFlexRtfEditor.GetDataSource: TdataSource;
begin
  Result := FDataLink.DataSource;
end;

procedure TFlexRtfEditor.SetMainDataField(const Value: string);
begin
  FDataLink.FieldName := Value; //FDataLink.DataSource.DataSet.FindField(Value);
end;

procedure TFlexRtfEditor.SetDataSource(const Value: TdataSource);
begin
  FDataLink.DataSource := Value;
  FAltDataLink.DataSource := Value;
end;

function TFlexRtfEditor.GetAltDataField: String;
begin
  Result := FAltDataLink.FieldName;
end;

procedure TFlexRtfEditor.SetAltDataField(const Value: String);
begin
  FAltDataLink.FieldName := Value;
end;

As you can see, the AltDataField is provided with its own FieldDataLink,
which is far simpler than having to to derive (and debug) your own
TFieldDataLink-descendant.

In your component registration unit:

interface

uses SysUtils, Classes, DesignIntf, DesignEditors, DSDesign, DBReg, FlexRTFu;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('MA', [TFlexRtfEditor]);
  RegisterPropertyEditor(TypeInfo(string), TComponent, 'MainDataField', TDataFieldProperty);
  RegisterPropertyEditor(TypeInfo(string), TComponent, 'AltDataField', TDataFieldProperty);
end;

end.

Btw, you might want to look at the source code of TDBEdit for some extra details of how the component's properties interact with its FieldDataLink.

Also btw, my package's Requires clause looks like this:

requires
  rtl,
  vcl,
  dbrtl,
  vcldb,
  cxLibraryD7,
  dxThemeD7,
  dxCoreD7,
  dxGDIPlusD7,
  vclx,
  cxEditorsD7,
  cxDataD7,
  vcljpg,
  dxSkinBlackD7,
  dxSkinsCoreD7,
  dxSkinBlueD7,
  dxSkinBlueprintD7,
  dxSkinCaramelD7,
  dxSkinCoffeeD7,
  dxSkinDarkRoomD7,
  dxSkinDarkSideD7,
  dxSkinDevExpressDarkStyleD7,
  dxSkinDevExpressStyleD7,
  dxSkinFoggyD7,
  dxSkinGlassOceansD7,
  dxSkinHighContrastD7,
  dxSkiniMaginaryD7,
  dxSkinLilianD7,
  dxSkinLiquidSkyD7,
  dxSkinLondonLiquidSkyD7,
  dxSkinMcSkinD7,
  dxSkinMetropolisD7,
  dxSkinMetropolisDarkD7,
  dxSkinMoneyTwinsD7,
  dxSkinOffice2007BlackD7,
  dxSkinOffice2007BlueD7,
  dxSkinOffice2007GreenD7,
  dxSkinOffice2007PinkD7,
  dxSkinOffice2007SilverD7,
  dxSkinOffice2010BlackD7,
  dxSkinOffice2010BlueD7,
  dxSkinOffice2010SilverD7,
  dxSkinOffice2013DarkGrayD7,
  dxSkinOffice2013LightGrayD7,
  dxSkinOffice2013WhiteD7,
  dxSkinPumpkinD7,
  dxSkinSevenClassicD7,
  dxSkinSevenD7,
  dxSkinSharpD7,
  dxSkinSharpPlusD7,
  dxSkinSilverD7,
  dxSkinSpringTimeD7,
  dxSkinStardustD7,
  dxSkinSummer2008D7,
  dxSkinTheAsphaltWorldD7,
  dxSkinValentineD7,
  dxSkinVS2010D7,
  dxSkinWhiteprintD7,
  dxSkinXmas2008BlueD7,
  designide,
  vclactnband,
  dcldb,
  vcldesigner,
  designdgm,
  dclstd;


问:
IB API Python sample not using Ibpy
Can someone help me to figure out how to do basic request by using IB API Python socket?  (I am using the latest IB API and it seems it support Python so should not need the Ibpy which people used to use)

My code like this can simply work and make it connect to TWS.
The problem is : I have no idea how to "see" the message sending back from IB.

```<code>from ibapi import wrapper
from ibapi.client import EClient
from ibapi.contract import *

w = wrapper.EWrapper()
myTWS = EClient(w)
myTWS.connect(host='localhost', port=7496, clientId=100)

print("serverVersion:%s connectionTime:%s" % (myTWS.serverVersion(),
                                          myTWS.twsConnectionTime()))
myTWS.startApi()

c = Contract()
c.m_symbol = "AAPL"
c.m_secType = "STK"
c.m_exchange = "ISLAND"
c.m_currency = "USD"

myTWS.reqRealTimeBars(999, c, 5, "MIDPOINT", True, [])
</code>```

I know that it was something like Register() before with IBPy. I just don't know how to do it in this current IB original python API. Can someone help by giving me a simple example? Thanks in advance.

答:
This is example how to process API messages using multithreading. The app.run() is started as separate thread and it is listening to TWS API responses. The main program then sends 5 requests for ContractDetails and then main program is 10 seconds waiting for responses. TWS API messages are stored within app instance and simple semaphore signals when the response is ready to be processed.

It is my first multithreading program, any comments are welcome.

```<code>from ibapi import wrapper
from ibapi.client import EClient
from ibapi.utils import iswrapper #just for decorator
from ibapi.common import *
from ibapi.contract import *
from ibapi.ticktype import *
#from OrderSamples import OrderSamples
import threading
import time

class myThread (threading.Thread):
   def __init__(self, app, threadID, name):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.app = app

   def run(self):
      print ("Starting application in separate thread:", self.name,     "threadID:", self.threadID  )
      self.app.run()
      print ("Exiting " + self.name)

class TestApp(wrapper.EWrapper, EClient):
    def __init__(self):
        wrapper.EWrapper.__init__(self)
        EClient.__init__(self, wrapper=self)
        self.started = False
        self.nextValidOrderId = 0
        self.reqData = {}       # store data returned by requests
        self.reqStatus = {}     # semaphore of requests - status End will indicate request is finished

@iswrapper
def nextValidId(self, orderId:int):
    print("setting nextValidOrderId: %d", orderId)
    self.nextValidOrderId = orderId

@iswrapper
def error(self, reqId:TickerId, errorCode:int, errorString:str):
    print("Error. Id: " , reqId, " Code: " , errorCode , " Msg: " , errorString)

@iswrapper
# ! [contractdetails]
def contractDetails(self, reqId: int, contractDetails: ContractDetails):
    super().contractDetails(reqId, contractDetails)
    # store response in reqData dict, for each request several objects are appended into list
    if not reqId in self.reqData:
        self.reqData[reqId] = []
    self.reqData[reqId].append(contractDetails) # put returned data into data storage dict
    # ! [contractdetails]

@iswrapper
# ! [contractdetailsend]
def contractDetailsEnd(self, reqId: int):
    super().contractDetailsEnd(reqId)
    print("ContractDetailsEnd. ", reqId, "\n")  # just info
    self.reqStatus[reqId] = 'End'               # indicates the response is ready for further processing
    # ! [contractdetailsend]

def main():

    app = TestApp()
    app.connect("127.0.0.1", 4001, clientId=123)
    print("serverVersion:%s connectionTime:%s" % (app.serverVersion(),
                                            app.twsConnectionTime()))

    thread1App = myThread(app, 1, "Thread-1")  # define thread for sunning app
    thread1App.start()                         # start app.run(] as infitnite loop in separate thread

    print('Requesting MSFT contract details:')
    contract = Contract()
    contract.symbol = "MSFT"
    contract.secType = "STK"
    contract.currency = "USD"
    contract.exchange = ""
    app.reqStatus[210] = 'Sent'   # set request status to "sent to TWS"
    app.reqContractDetails(210, contract)

    print('Requesting IBM contract details:')
    contract.symbol = "IBM"
    app.reqStatus[211] = 'Sent'
    app.reqContractDetails(211, contract)

    print('Requesting IBM contract details:')
    contract.symbol = "GE"
    app.reqStatus[212] = 'Sent'
    app.reqContractDetails(212, contract)

    print('Requesting IBM contract details:')
    contract.symbol = "GM"
    app.reqStatus[213] = 'Sent'
    app.reqContractDetails(213, contract)

    print('Requesting IBM contract details:')
    contract.symbol = "BAC"
    app.reqStatus[214] = 'Sent'
    app.reqContractDetails(214, contract)

    i = 0
    while i < 100:         # exit loop after 10 sec (100 x time.sleep(0.1)
        i = i+1
        for reqId in app.reqStatus:
            if app.reqStatus[reqId] == 'End':
                for contractDetails in app.reqData[reqId]:
                    print("ContractDetails. ReqId:", reqId, contractDetails.summary.symbol,
                  contractDetails.summary.secType, "ConId:", contractDetails.summary.conId,
                  "@", contractDetails.summary.exchange)
                app.reqStatus[reqId] = 'Processed'
        time.sleep(0.1)
    app.done = True             # this stops app.run() loop

if __name__ == "__main__":
    main()
</code>```

Title: IB API Python sample not using Ibpy

Body:
Can someone help me to figure out how to do basic request by using IB API Python socket?  (I am using the latest IB API and it seems it support Python so should not need the Ibpy which people used to use)

My code like this can simply work and make it connect to TWS.
The problem is : I have no idea how to "see" the message sending back from IB.

from ibapi import wrapper
from ibapi.client import EClient
from ibapi.contract import *

w = wrapper.EWrapper()
myTWS = EClient(w)
myTWS.connect(host='localhost', port=7496, clientId=100)

print("serverVersion:%s connectionTime:%s" % (myTWS.serverVersion(),
                                          myTWS.twsConnectionTime()))
myTWS.startApi()

c = Contract()
c.m_symbol = "AAPL"
c.m_secType = "STK"
c.m_exchange = "ISLAND"
c.m_currency = "USD"

myTWS.reqRealTimeBars(999, c, 5, "MIDPOINT", True, [])

I know that it was something like Register() before with IBPy. I just don't know how to do it in this current IB original python API. Can someone help by giving me a simple example? Thanks in advance.

Body:
This is example how to process API messages using multithreading. The app.run() is started as separate thread and it is listening to TWS API responses. The main program then sends 5 requests for ContractDetails and then main program is 10 seconds waiting for responses. TWS API messages are stored within app instance and simple semaphore signals when the response is ready to be processed.

It is my first multithreading program, any comments are welcome.

from ibapi import wrapper
from ibapi.client import EClient
from ibapi.utils import iswrapper #just for decorator
from ibapi.common import *
from ibapi.contract import *
from ibapi.ticktype import *
#from OrderSamples import OrderSamples
import threading
import time

class myThread (threading.Thread):
   def __init__(self, app, threadID, name):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.app = app

   def run(self):
      print ("Starting application in separate thread:", self.name,     "threadID:", self.threadID  )
      self.app.run()
      print ("Exiting " + self.name)

class TestApp(wrapper.EWrapper, EClient):
    def __init__(self):
        wrapper.EWrapper.__init__(self)
        EClient.__init__(self, wrapper=self)
        self.started = False
        self.nextValidOrderId = 0
        self.reqData = {}       # store data returned by requests
        self.reqStatus = {}     # semaphore of requests - status End will indicate request is finished

@iswrapper
def nextValidId(self, orderId:int):
    print("setting nextValidOrderId: %d", orderId)
    self.nextValidOrderId = orderId

@iswrapper
def error(self, reqId:TickerId, errorCode:int, errorString:str):
    print("Error. Id: " , reqId, " Code: " , errorCode , " Msg: " , errorString)

@iswrapper
# ! [contractdetails]
def contractDetails(self, reqId: int, contractDetails: ContractDetails):
    super().contractDetails(reqId, contractDetails)
    # store response in reqData dict, for each request several objects are appended into list
    if not reqId in self.reqData:
        self.reqData[reqId] = []
    self.reqData[reqId].append(contractDetails) # put returned data into data storage dict
    # ! [contractdetails]

@iswrapper
# ! [contractdetailsend]
def contractDetailsEnd(self, reqId: int):
    super().contractDetailsEnd(reqId)
    print("ContractDetailsEnd. ", reqId, "\n")  # just info
    self.reqStatus[reqId] = 'End'               # indicates the response is ready for further processing
    # ! [contractdetailsend]

def main():

    app = TestApp()
    app.connect("127.0.0.1", 4001, clientId=123)
    print("serverVersion:%s connectionTime:%s" % (app.serverVersion(),
                                            app.twsConnectionTime()))

    thread1App = myThread(app, 1, "Thread-1")  # define thread for sunning app
    thread1App.start()                         # start app.run(] as infitnite loop in separate thread

    print('Requesting MSFT contract details:')
    contract = Contract()
    contract.symbol = "MSFT"
    contract.secType = "STK"
    contract.currency = "USD"
    contract.exchange = ""
    app.reqStatus[210] = 'Sent'   # set request status to "sent to TWS"
    app.reqContractDetails(210, contract)

    print('Requesting IBM contract details:')
    contract.symbol = "IBM"
    app.reqStatus[211] = 'Sent'
    app.reqContractDetails(211, contract)

    print('Requesting IBM contract details:')
    contract.symbol = "GE"
    app.reqStatus[212] = 'Sent'
    app.reqContractDetails(212, contract)

    print('Requesting IBM contract details:')
    contract.symbol = "GM"
    app.reqStatus[213] = 'Sent'
    app.reqContractDetails(213, contract)

    print('Requesting IBM contract details:')
    contract.symbol = "BAC"
    app.reqStatus[214] = 'Sent'
    app.reqContractDetails(214, contract)

    i = 0
    while i < 100:         # exit loop after 10 sec (100 x time.sleep(0.1)
        i = i+1
        for reqId in app.reqStatus:
            if app.reqStatus[reqId] == 'End':
                for contractDetails in app.reqData[reqId]:
                    print("ContractDetails. ReqId:", reqId, contractDetails.summary.symbol,
                  contractDetails.summary.secType, "ConId:", contractDetails.summary.conId,
                  "@", contractDetails.summary.exchange)
                app.reqStatus[reqId] = 'Processed'
        time.sleep(0.1)
    app.done = True             # this stops app.run() loop

if __name__ == "__main__":
    main()


问:
match two columns and display values from 3rd column using vlookup
I am trying to perform vlookup on column A of sheet1 with column A of sheet2 and I have to display the value from column B of sheet2  to column B of sheet1.

The values in Column A of sheet1 and sheet2 are dates.So I am matching those two dates using vlookup and trying to display the third value,but its not working.My day column of sheet1 is

Day          | Final_Conversions

----------   | ------

27-10-2016

21-11-2016

15-12-2016

13-02-2017

And my sheet2 has

Day          | Conversions

----------   | ------

13-02-2017   | 23

15-12-2016   | 15

21-11-2016   | 400

23-11-2016   | 60

Now I want that if my date is there in sheet2 then conversion value should be dipslayed in sheet1.
 I tried this but ts not working =VLOOKUP(A2,'sheet2'!$A$1:$B$4,2,0)

答:
I suspect that one of the date columns are text-that-look-like-dates and the other are true dates. I can see nothing wrong with your formula. Run Text-To-Columns, Fixed Width, DMY, Finish on both columns.

Note that the dates in both Sheet1 and Sheet2 are right-aligned. This is the default cell alignment for numbers and dates. If you have not manually adjusted the cell alignment, yours are likely showing right-alignment in one worksheet and left-alignment (i.e. text) in the other.

On a related note, if you imported DMY data into a MDY system, see Excel VBA - Convert Text to Date? for methods on repairing your data.


答:
First you do $employee_coor = substring_index($_GET['employees'], ' ', 1);

You can add " . $employee_coor . " like the example:

```<code>$select = "SELECT * FROM employeesWHERE employees.employee_fname = '" . $employee_coor . "' AND employees.employee_lname = '" . $employee_coor . "')";
</code>```

Or you can do this way: {$employe_coor}, like the example:

```<code>$select = "SELECT * FROM employees WHERE employees.employee_fname = '{$employee_coor}' AND employees.employee_lname = '{$employee_coor}'";
</code>```

Or the simplest way: '$employe_coor':

```<code>    $select = "SELECT * FROM employees WHERE employees.employee_fname = '$employee_coor' AND employees.employee_lname = '$employee_coor'";
</code>```

Complete example:

```<code><?php
include_once('dbconnect.php');

if (!empty($_GET['employees'])) {
    $employee_coor = substring_index($_GET['employees'], ' ', 1);
    //$select = "SELECT * FROM employees WHERE employees.employee_fname = '$employee_coor' AND employees.employee_lname = '$employee_coor'";
    //$select = "SELECT * FROM employeesWHERE employees.employee_fname = '" . $employee_coor . "' AND employees.employee_lname = '" . $employee_coor . "')";
    $select = "SELECT * FROM employees WHERE employees.employee_fname = '{$employee_coor}' AND employees.employee_lname = '{$employee_coor}'";
    $query = mysqli_query($con, $select);
    $cooridinator = mysqli_fetch_assoc($query);
    var_dump($cooridinator);
} else {
    //code
}
</code>```

?>

Title: php mysqli query function not executing when the query contains php variable

Body:
First you do $employee_coor = substring_index($_GET['employees'], ' ', 1);

You can add " . $employee_coor . " like the example:

$select = "SELECT * FROM employeesWHERE employees.employee_fname = '" . $employee_coor . "' AND employees.employee_lname = '" . $employee_coor . "')";

Or you can do this way: {$employe_coor}, like the example:

$select = "SELECT * FROM employees WHERE employees.employee_fname = '{$employee_coor}' AND employees.employee_lname = '{$employee_coor}'";

Or the simplest way: '$employe_coor':

    $select = "SELECT * FROM employees WHERE employees.employee_fname = '$employee_coor' AND employees.employee_lname = '$employee_coor'";

Complete example:

<?php
include_once('dbconnect.php');

if (!empty($_GET['employees'])) {
    $employee_coor = substring_index($_GET['employees'], ' ', 1);
    //$select = "SELECT * FROM employees WHERE employees.employee_fname = '$employee_coor' AND employees.employee_lname = '$employee_coor'";
    //$select = "SELECT * FROM employeesWHERE employees.employee_fname = '" . $employee_coor . "' AND employees.employee_lname = '" . $employee_coor . "')";
    $select = "SELECT * FROM employees WHERE employees.employee_fname = '{$employee_coor}' AND employees.employee_lname = '{$employee_coor}'";
    $query = mysqli_query($con, $select);
    $cooridinator = mysqli_fetch_assoc($query);
    var_dump($cooridinator);
} else {
    //code
}

?>


问:
Redirect to a page after loading it and display progress bar
I've seen some websites that, once you click on a link, appear to load a page before you're redirected so that the page is displayed instantly, with some sort of bar showing the progress of the request. How do they go about doing this?</p>

答:
It can be done using Ajax. Check out this article which shows how it's done: https://onextrapixel.com/loadingbar-js-adding-a-youtube-like-loading-bar-to-your-website/

It can also be done using the HTML5 History API(which is actually used by YouTube), it adds and removes page URLs into and from the History stack. The URL's from this stack is then used to load the pages using Ajax.

Read more about it here: Curious about the new way YouTube is loading pages


问:
How can I deploy an Asp.Net MVC Core application, using .Net Framework (not core) in my local IIS?
Using Visual Studio 2017 the most obvious way to me is to publish to IIS using file system. When I host the folder that comes outof this publishing in IIS I use an App Pool with .Net 4.5.1 (I also use .Net 4.5.1 for my app). When I access the web page with the browser, static content works, but dynamic content returns HTTP 501 without further information.

In the events viewer I see no entries.

How can I diagnose this? Should I try another way to get the app running in the local IIS and later on an inhouse server using IIS?

答: As described here http://learn.microsoft.com/en-us/aspnet/core/publishing/iis "Set the .NET CLR version to No Managed Code." your IIS application pool shoudln't be running .Net and should be set to No Managed Code.</p>


答:
Answer is: yes

How? Render a regular table, then use Jqgrid's plugin called "grid.tbltogrid.js". Very useful and simple. Internally it uses "addRowData" method of the jqgrid, but why you need to repeat the written code, right? ;)

Title: Best way to load jqGrid with static data?

Body:
We load 10 rows of static data into our jqGrid by creating a JSON string:

var d = "{\"page\":1,\"records\":10,\"total\":1,\"rows\":[" +
                "{\"id\":\"1\",\"cell\":[\"\"]}," +
                "{\"id\":\"2\",\"cell\":[\"\"]}," +
                "{\"id\":\"3\",\"cell\":[\"\"]}," +
                "{\"id\":\"4\",\"cell\":[\"\"]}," +
                "{\"id\":\"5\",\"cell\":[\"\"]}," +
                "{\"id\":\"6\",\"cell\":[\"\"]}," +
                "{\"id\":\"7\",\"cell\":[\"\"]}," +
                "{\"id\":\"8\",\"cell\":[\"\"]}," +
                "{\"id\":\"9\",\"cell\":[\"\"]}," +
                "{\"id\":\"10\",\"cell\":[\"\"]}" +
            "]}";

And loading that into a grid with datatype:jsonstring and datastr:d where our grid has 15 columns and each column is created using a custom formatter.

Is there a better way to do this?


问:
Run Shell Script without Command line Arguments in Linux
I am trying to run a Shell Script, but got stuck on an issue. I want to Run certain set of code when i supply arguments and remaining should run, if i dont pass any argument.
Part which i want to run with args:

```<code>#!/bin/bash
while [[ "$1" != "" ]]; do
case "$1" in
    -c )  cat /proc/cpuinfo | grep cores
          ;;
    -d )  fdisk -l | grep Disk  | awk '{print $1,$2,$3,$4}' #fdisk -l 2> /dev/null | grep Disk | grep -v identifier
          ;;
    esac
 shift
done
</code>```

and this part without any args

```<code>while [[ $# -eq 0 ]]; do
echo PART 2 $#
cat /proc/cpuinfo | grep cores
fdisk -l | grep Disk  | awk '{print $1,$2,$3,$4}' #fdisk -l 2> /dev/null | grep Disk | grep -v identifier
break
done
</code>```

I believe issue is with the Loop condition, but i cant understand what?

答:
```<code>if [[ -n "$1" ]]; then
  #
  # "$1" is not empty. This is the part which runs when one or more
  # arguments are supplied.
  #
  while [[ -n "$1" ]]; do
    case "$1" in
    -c) cat /proc/cpuinfo | grep cores
        ;;
    -d) LC_ALL=C fdisk -l | grep Disk  | awk '{print $1,$2,$3,$4}'
        #LC_ALL=C fdisk -l 2> /dev/null | grep Disk | grep -v identifier
        ;;
    esac
  shift
  done
  exit
fi
#
# "$1" is empty. The following code runs when no arguments are supplied.
#
echo PART 2 $#
cat /proc/cpuinfo | grep cores
LC_ALL=C fdisk -l | grep Disk | awk '{print $1,$2,$3,$4}'
#LC_ALL=C fdisk -l 2> /dev/null | grep Disk | grep -v identifier
</code>```

Note 1: Not tested.

Note 2: Whenever you feel a need to parse the output of a command looking for certain words or phrases it is a good idea to run the command in the default locale by prefixing it with LC_ALL=C. In this way you won't be surprised when in a French locale, for example, fdisk says Disque...

Body:
I am trying to run a Shell Script, but got stuck on an issue. I want to Run certain set of code when i supply arguments and remaining should run, if i dont pass any argument.
Part which i want to run with args:

#!/bin/bash
while [[ "$1" != "" ]]; do
case "$1" in
    -c )  cat /proc/cpuinfo | grep cores
          ;;
    -d )  fdisk -l | grep Disk  | awk '{print $1,$2,$3,$4}' #fdisk -l 2> /dev/null | grep Disk | grep -v identifier
          ;;
    esac
 shift
done

and this part without any args

while [[ $# -eq 0 ]]; do
echo PART 2 $#
cat /proc/cpuinfo | grep cores
fdisk -l | grep Disk  | awk '{print $1,$2,$3,$4}' #fdisk -l 2> /dev/null | grep Disk | grep -v identifier
break
done

I believe issue is with the Loop condition, but i cant understand what?

Body:
if [[ -n "$1" ]]; then
  #
  # "$1" is not empty. This is the part which runs when one or more
  # arguments are supplied.
  #
  while [[ -n "$1" ]]; do
    case "$1" in
    -c) cat /proc/cpuinfo | grep cores
        ;;
    -d) LC_ALL=C fdisk -l | grep Disk  | awk '{print $1,$2,$3,$4}'
        #LC_ALL=C fdisk -l 2> /dev/null | grep Disk | grep -v identifier
        ;;
    esac
  shift
  done
  exit
fi
#
# "$1" is empty. The following code runs when no arguments are supplied.
#
echo PART 2 $#
cat /proc/cpuinfo | grep cores
LC_ALL=C fdisk -l | grep Disk | awk '{print $1,$2,$3,$4}'
#LC_ALL=C fdisk -l 2> /dev/null | grep Disk | grep -v identifier

Note 1: Not tested.

Note 2: Whenever you feel a need to parse the output of a command looking for certain words or phrases it is a good idea to run the command in the default locale by prefixing it with LC_ALL=C. In this way you won't be surprised when in a French locale, for example, fdisk says Disque...


问:
*.cs.aspx cannot access *.cs files in App_Code folder
This site was developed a few years ago. it was working 100%. I am re-deploying to my pc to make some changes and testing. Now it cannot find those classes in those files. I have always used 4.5 Framework. I have searched for a solution, unfortunately those have not resolved my issue. including coping it into main directory. It worked when I copied the actual code into one of the *.cs.aspx files. However there are more then 20 pages using this email file. Any advice would be welcome. I have been scratching around for days. Thx.

===================ERROR========================>
The error is as follows:The type or namespace name 'Emailer' could not be found (are you missing a using directive or an assembly reference?)

===================ERROR-DISPLAY================>
Source Error:

Heading

答: You probably changed a Web Site Project to a Web Application Project. There are a couple of differences between these project types. Among them, in Web Application Projects, the App_Code directory seems to be ignored.</p>


问:
How to pass column name in ggplot facet_wrap in a function
How to pass column name of a data frame in ggplot facet_wrap or fill/colour in a function? I looked up lazyeval but didn't figure out a way.

```<code>x="class"
ggplot(mpg, aes(displ, hwy, col=x)) + geom_point() + facet_wrap(x)
</code>```

In this example, why didn't the points get coloured by x?

答: Have you tried ggplot(mpg, aes(displ, hwy, col=as.factor(x))) + geom_point() + facet_wrap(~x) ?

Body:
How to pass column name of a data frame in ggplot facet_wrap or fill/colour in a function? I looked up lazyeval but didn't figure out a way.

x="class"
ggplot(mpg, aes(displ, hwy, col=x)) + geom_point() + facet_wrap(x)

In this example, why didn't the points get coloured by x?


问:
Configure eclipse so that backspace unindents
Having eclipse configured to use space instead of tabs, is it possible to configure eclipse so that the backspace key unindents like the tab key indents?

A demonstration to clarify what I mean with backspace unindent (the vertical bar stands for cursor position and the dots for spaces):

```<code>if(bar == 0) {
|foo = 0;
}
</code>```

Pressing tab will indent 4 spaces:

```<code>if(bar == 0) {
....|foo = 0;
}
</code>```

Pressing backspace only goes back 1 space:

```<code>if(bar == 0) {
...|foo = 0;
}
</code>```

What I want is that it goes back 4 spaces:

```<code>if(bar == 0) {
|foo = 0;
}
</code>```

答:
You know that "shift+tab" will outdent a line already, correct?

Hmmm, I just took a look at preferences->general->keys.  I only see indent line there, no outdent (or anything useful under "dent").

Personally, I would say that backspace is the key I hit second most often, after space.  Rebinding it would drive me bonkers.

Body:
Having eclipse configured to use space instead of tabs, is it possible to configure eclipse so that the backspace key unindents like the tab key indents?

A demonstration to clarify what I mean with backspace unindent (the vertical bar stands for cursor position and the dots for spaces):

if(bar == 0) {
|foo = 0;
}

Pressing tab will indent 4 spaces:

if(bar == 0) {
....|foo = 0;
}

Pressing backspace only goes back 1 space:

if(bar == 0) {
...|foo = 0;
}

What I want is that it goes back 4 spaces:

if(bar == 0) {
|foo = 0;
}


问:
List Item Wrapping in Game Menu
I'm trying to get an infinite scrolling effect with a list of game items by wrapping itself around itself so if you keep pressing down it will wrap around to the first item smoothly.

The effect I'm trying to get is like this image here where there is no breaks in the menu items being listed.

I'm currently doing this in Qt Quick QML but I think it can be code agnogstic. I'm also trying not to shift by moving item indices within the list, just moving the Y position of the object.

Here is my code currently (just a normal list positioning)

```<code>Text
{
    id:root
    //clip: true
    property int spacing
    property int currentIndex
    property int selectedIndex
    property int maxIndex

    property int difference: Math.min(selectedIndex - currentIndex, maxIndex-currentIndex)
    width: 500

    x:  -400 + 30 * Math.abs(difference)
    y: (currentIndex- selectedIndex) * spacing

    Behavior on x { NumberAnimation { duration: 500 } }
    Behavior on y { NumberAnimation { duration: 500 } }
}
</code>```

Any help would be appreciated

答:
So my friend sent me a code snippet on how to do the wrapping I needed. Here's the code for the element item.</p>

```<code>Text
{
    //externally set
    property int itemIndex
    property int selectedIndex
    property int numberOfElements
    property int span

    //internally set
    property int shortestDistance
    readonly property int distancePerItem: 100

    id: root

    anchors.verticalCenter: parent.verticalCenter
    anchors.right: parent.right

    anchors.verticalCenterOffset: shortestDistance * distancePerItem
    anchors.rightMargin: Math.abs(shortestDistance) > span ? -contentWidth * Math.abs(shortestDistance) : 0

    Behavior on anchors.rightMargin { NumberAnimation { duration: 500 } }

    Behavior on anchors.verticalCenterOffset { NumberAnimation { duration: 500 } }

    onSelectedIndexChanged: updatePosition()

    function updatePosition()
    {
        shortestDistance = itemIndex - selectedIndex;
        if (shortestDistance > numberOfElements/2)
        {
             shortestDistance -= numberOfElements;
        }
        else if (shortestDistance < -numberOfElements/2)
        {
            shortestDistance += numberOfElements;
        }
    }
 }
</code>```

Title: List Item Wrapping in Game Menu

Body:
I'm trying to get an infinite scrolling effect with a list of game items by wrapping itself around itself so if you keep pressing down it will wrap around to the first item smoothly.

The effect I'm trying to get is like this image here where there is no breaks in the menu items being listed.

I'm currently doing this in Qt Quick QML but I think it can be code agnogstic. I'm also trying not to shift by moving item indices within the list, just moving the Y position of the object.

Here is my code currently (just a normal list positioning)

Text
{
    id:root
    //clip: true
    property int spacing
    property int currentIndex
    property int selectedIndex
    property int maxIndex

    property int difference: Math.min(selectedIndex - currentIndex, maxIndex-currentIndex)
    width: 500

    x:  -400 + 30 * Math.abs(difference)
    y: (currentIndex- selectedIndex) * spacing

    Behavior on x { NumberAnimation { duration: 500 } }
    Behavior on y { NumberAnimation { duration: 500 } }
}

Any help would be appreciated

Body:
So my friend sent me a code snippet on how to do the wrapping I needed. Here's the code for the element item.

Text
{
    //externally set
    property int itemIndex
    property int selectedIndex
    property int numberOfElements
    property int span

    //internally set
    property int shortestDistance
    readonly property int distancePerItem: 100

    id: root

    anchors.verticalCenter: parent.verticalCenter
    anchors.right: parent.right

    anchors.verticalCenterOffset: shortestDistance * distancePerItem
    anchors.rightMargin: Math.abs(shortestDistance) > span ? -contentWidth * Math.abs(shortestDistance) : 0

    Behavior on anchors.rightMargin { NumberAnimation { duration: 500 } }

    Behavior on anchors.verticalCenterOffset { NumberAnimation { duration: 500 } }

    onSelectedIndexChanged: updatePosition()

    function updatePosition()
    {
        shortestDistance = itemIndex - selectedIndex;
        if (shortestDistance > numberOfElements/2)
        {
             shortestDistance -= numberOfElements;
        }
        else if (shortestDistance < -numberOfElements/2)
        {
            shortestDistance += numberOfElements;
        }
    }
 }