问:
Writing a SQL Server trigger - error
I have three tables:

Bus_Driver (drNo,drName,salary,StationNo,experience)

Station (StationNo,address,district,Salary_Commission)

Cleaner (Cleaner_No, Cname, StationNo)

The question is to write a trigger. It states that if a bus driver's salary is increased by 20% more than the original salary then 0.05% of the increased value will be transferred to his Station as Salary commission.

I managed to write the trigger halfway, but got stuck when I have to transfer the amount to the other table.

My code is:

```<code>CREATE TRIGGER tr_1
ON Bus_Driver
AFTER INSERT
AS
BEGIN
    DECLARE @salary MONEY
    SET @Salary = 0

    SELECT @Salary= salary
    FROM Inserted
    WHERE @Salary > (120 / 100 * @Salary)
</code>```

Can anyone help me how to write the next steps please

答:
The trigger you wrote is wrong.

First, it's a trigger for insert, while the question states that the salary is raised, meaning it should be a trigger for update.

Second, your trigger assumes only a single row will be in the inserted table. However, this assumption is wrong. Triggers in SQL server are fired per statement, not per row, meaning that the inserted (and deleted) tables might contain zero, one, or many rows.

A solution for this question will be to write a trigger for update, that will, in turn, update the station table. Something like this:

```<code>CREATE TRIGGER tr_Bus_Driver_Update ON Bus_Driver
FOR UPDATE
AS

    UPDATE s
    SET Salary_Commission = Salary_Commission -
                            (0.0005 * D.Salary) + -- Remove old salary of the driver(s) from salary_commition.
                            (0.0005 * I.Salary) -- add new salary of the driver(s) to salary_commition
    FROM Station s
    INNER JOIN Inserted I ON s.StationNo = I.StationNo
    INNER JOIN Deleted D ON I.drNo = D.drNo -- assuming drNo is unique in Bus_Driver table
    WHERE I.Salary >= D.Salady * 1.2 -- You might need to cast to a floating point data type if the Salary is an integer data type
</code>```

Note you might need to cast the salary to a floating point data type if the Salary is an integer data type whenever it's used in this trigger.

Title: Writing a SQL Server trigger - error

Body:
I have three tables:

Bus_Driver (drNo,drName,salary,StationNo,experience)

Station (StationNo,address,district,Salary_Commission)

Cleaner (Cleaner_No, Cname, StationNo)

The question is to write a trigger. It states that if a bus driver's salary is increased by 20% more than the original salary then 0.05% of the increased value will be transferred to his Station as Salary commission.

I managed to write the trigger halfway, but got stuck when I have to transfer the amount to the other table.

My code is:

CREATE TRIGGER tr_1
ON Bus_Driver
AFTER INSERT
AS
BEGIN
    DECLARE @salary MONEY
    SET @Salary = 0

    SELECT @Salary= salary
    FROM Inserted
    WHERE @Salary > (120 / 100 * @Salary)

Can anyone help me how to write the next steps please

Body:
The trigger you wrote is wrong.

First, it's a trigger for insert, while the question states that the salary is raised, meaning it should be a trigger for update.

Second, your trigger assumes only a single row will be in the inserted table. However, this assumption is wrong. Triggers in SQL server are fired per statement, not per row, meaning that the inserted (and deleted) tables might contain zero, one, or many rows.

A solution for this question will be to write a trigger for update, that will, in turn, update the station table. Something like this:

CREATE TRIGGER tr_Bus_Driver_Update ON Bus_Driver
FOR UPDATE
AS

    UPDATE s
    SET Salary_Commission = Salary_Commission -
                            (0.0005 * D.Salary) + -- Remove old salary of the driver(s) from salary_commition.
                            (0.0005 * I.Salary) -- add new salary of the driver(s) to salary_commition
    FROM Station s
    INNER JOIN Inserted I ON s.StationNo = I.StationNo
    INNER JOIN Deleted D ON I.drNo = D.drNo -- assuming drNo is unique in Bus_Driver table
    WHERE I.Salary >= D.Salady * 1.2 -- You might need to cast to a floating point data type if the Salary is an integer data type

Note you might need to cast the salary to a floating point data type if the Salary is an integer data type whenever it's used in this trigger.


来源: stackexchange

问:
How to Remove Background Color of Button to get Default Background in Android
I am Working on a Test Application in which every question is presented with Four options [those options are via Button]. When a User clicks a button and his answer is correct then background of that button Turns Green, and if his answer is incorrect it turns Red.
What i want to do is Reset the Button Background on Next Question.

After Searching a lot of People have asked the same Question and Accepted the answer as

```<code>  btnChoiceB.setBackgroundColor(0x00000000);
</code>```

But the problem is, it turns the Whole Button Transparent, which is not my requirement. I Just want the default color Back.

Do Not Suggest

```<code>btnChoiceB.setBackgroundColor(null);
</code>```

as it does not work.

This is What i want Back.

UPDATE/ANSWERED

As Suggested by quick learner,

```<code>btnChoiceB.setBackgroundResource(android.R.drawable.btn_default);
</code>```

worked pretty cleanly.

答: You could try using android:backgroundTint . That, or try to look over this answer here.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am Working on a Test Application in which every question is presented with Four options [those options are via Button]. When a User clicks a button and his answer is correct then background of that button Turns Green, and if his answer is incorrect it turns Red.
What i want to do is Reset the Button Background on Next Question.

After Searching a lot of People have asked the same Question and Accepted the answer as

  btnChoiceB.setBackgroundColor(0x00000000);

But the problem is, it turns the Whole Button Transparent, which is not my requirement. I Just want the default color Back.

Do Not Suggest

btnChoiceB.setBackgroundColor(null);

as it does not work.

This is What i want Back.

UPDATE/ANSWERED

As Suggested by quick learner,

btnChoiceB.setBackgroundResource(android.R.drawable.btn_default);

worked pretty cleanly.


问:
How to create bottom navigation bar similar to instagram
I am an android newbie trying to create a bottom navigation bar for my new android app similar to one there in Instagram. Like this  where clicking on the search icon adds a search bar in action bar.
I am building an app for reminding the user about his medical appointments which has three navigation tabs at the bottom. I have created till this  after this I am stuck. Should I use three activities to display the content of corresponding tabs or fragments and how can I achieve that.

I need a recyclerview to display appointments. How can I display the search bar only when the search icon at bottom is clicked.
 Have searched a lot on achieving this but could not find anything useful.

Any suggestions for code or library which achieves the same would be great help thanks.

答:
Should I use three activities to display the content of corresponding
  tabs or fragments and how can I achieve that?

Definitely  you should use Fragment for each bottom navigation Item / Tab. Like FragmentHome, FragmentSearch and FragmentSettings.

To change the Fragment, add NavigationItemSelectedListener to your BottomNavigationView and change Fragment as per MenuItem selection:

```<code>    BottomNavigationView bottomNavigationView = (BottomNavigationView)
            findViewById(R.id.bottom_navigation_view);

    bottomNavigationView.setOnNavigationItemSelectedListener
            (new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment = null;
                    switch (item.getItemId()) {
                        case R.id.action_item1:
                            selectedFragment = FragmentHome.newInstance();
                            break;
                        case R.id.action_item2:
                            selectedFragment = FragmentSearch.newInstance();
                            break;
                        case R.id.action_item3:
                            selectedFragment = FragmentSettings.newInstance();
                            break;
                    }
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.frame_layout, selectedFragment);
                    transaction.commit();
                    return true;
                }
            });
</code>```

Here is a tutorial about: BottomNavigationView with multiple Fragments

I need a recyclerview to display appointments

In your Fragment's layout XML, add a RecyclerView to show list of appointments. In your Fragment class, initialize RecyclerView and create an ArrayList<Appointment> and pass this list to your Adapter to show on RecyclerView row items.

Here is an tutorial about: How to use RecyclerView in Fragment

How can I display the search bar only when the search icon at bottom
  is clicked?

You can  show/hide option item programmatically from ToolBar/ActionBar as per your Fragment change.

In your FragmentSearch, do below changes to show Searchbar:

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
{
    View v = inflater.inflate(R.layout.fragmet_search, parent, false);
    return v;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
   inflater.inflate(R.menu.your_search_menu_xml, menu);
   super.onCreateOptionsMenu(menu, inflater);
}
</code>```

Here are some useful links:

Android Toolbar Adding Menu Items for different fragments

Hide/Show Action Bar Option Menu Item for different fragments

Adding ActionBar Items From Within Your Fragments

Hope this will help to understand the scenario.

Body:
Should I use three activities to display the content of corresponding
  tabs or fragments and how can I achieve that?

Definitely  you should use Fragment for each bottom navigation Item / Tab. Like FragmentHome, FragmentSearch and FragmentSettings.

To change the Fragment, add NavigationItemSelectedListener to your BottomNavigationView and change Fragment as per MenuItem selection:

    BottomNavigationView bottomNavigationView = (BottomNavigationView)
            findViewById(R.id.bottom_navigation_view);

    bottomNavigationView.setOnNavigationItemSelectedListener
            (new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment = null;
                    switch (item.getItemId()) {
                        case R.id.action_item1:
                            selectedFragment = FragmentHome.newInstance();
                            break;
                        case R.id.action_item2:
                            selectedFragment = FragmentSearch.newInstance();
                            break;
                        case R.id.action_item3:
                            selectedFragment = FragmentSettings.newInstance();
                            break;
                    }
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.frame_layout, selectedFragment);
                    transaction.commit();
                    return true;
                }
            });

Here is a tutorial about: BottomNavigationView with multiple Fragments

I need a recyclerview to display appointments

In your Fragment's layout XML, add a RecyclerView to show list of appointments. In your Fragment class, initialize RecyclerView and create an ArrayList<Appointment> and pass this list to your Adapter to show on RecyclerView row items.

Here is an tutorial about: How to use RecyclerView in Fragment

How can I display the search bar only when the search icon at bottom
  is clicked?

You can  show/hide option item programmatically from ToolBar/ActionBar as per your Fragment change.

In your FragmentSearch, do below changes to show Searchbar:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
{
    View v = inflater.inflate(R.layout.fragmet_search, parent, false);
    return v;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
   inflater.inflate(R.menu.your_search_menu_xml, menu);
   super.onCreateOptionsMenu(menu, inflater);
}

Here are some useful links:

Android Toolbar Adding Menu Items for different fragments

Hide/Show Action Bar Option Menu Item for different fragments

Adding ActionBar Items From Within Your Fragments

Hope this will help to understand the scenario.


问:
How to convert binary to decimal using BigInteger?
I am trying to print decimal number from binary number using BigInteger class.
I am using BigInteger(String val, int radix) constructor of BigInteger class to convert given binary value to decimal but it is printing the exact binary value which is passed in constructor.Waht is the error?
The code is as follows:</p>

```<code>System.out.print("Ente the decimal number:");
s=String.valueOf(sc.nextInt());

BigInteger i=new BigInteger(s,10);
System.out.println(i);
</code>```

答:
Actually you are not printing the decimal value of binary number

The value which is printed is the exact decimal representation of String val

According to radix that you put in this statement it will act like this :

```<code> BigInteger i = new BigInteger("11101", 10); // 11101
</code>```

11101 this output is actually decimal number not a binary number

In order to get the expected result you should change radix value to 2 after that it will print the decimal value of the binary number:

```<code>BigInteger i = new BigInteger("11101", 2);
System.out.println(i);
</code>```

Output:

```<code>29
</code>```

Body:
I am trying to print decimal number from binary number using BigInteger class.
I am using BigInteger(String val, int radix) constructor of BigInteger class to convert given binary value to decimal but it is printing the exact binary value which is passed in constructor.Waht is the error?
The code is as follows:

System.out.print("Ente the decimal number:");
s=String.valueOf(sc.nextInt());

BigInteger i=new BigInteger(s,10);
System.out.println(i);

Body:
Actually you are not printing the decimal value of binary number

The value which is printed is the exact decimal representation of String val

According to radix that you put in this statement it will act like this :

 BigInteger i = new BigInteger("11101", 10); // 11101

11101 this output is actually decimal number not a binary number

In order to get the expected result you should change radix value to 2 after that it will print the decimal value of the binary number:

BigInteger i = new BigInteger("11101", 2);
System.out.println(i);

Output:

29


问:
Mac Application from Gtk in Visual Studio Mac
Im very new in Mac development environment. I installed Visual Studio for Mac, and created a new solution .NET/Gtk 2.0 project to build a GUI file rename tool. I created the tool. However when I build it in debug and release, it generates .exe file which I can only run with the shell.

However, I need to build this program in app bundle so that I can send it over to other users and they can run it by clicking on it. Is there any way to accomplish this?(I have spent a few hours on this but couldn't see a clear document that explain to me. If nothing works then I need to rewrite it in Java).

Thank you so much in advance!

答:
Assuming Mono is installed on all of your target machines then you can put together (manually) a .app package folder that will run your .exe file when a user double-clicks on it. There's a certain set of things you'll need to put in the .app package, one of which is a command shell file that will kick-off your .exe and will be executed when the .app is run.

B.t.w. Visual Studio Mac and Xamarin Studio and MonoDevelop are all basically different twists on the same thing, MonoDevelop. VS mac and XS have extras but the basic underlying IDE is MD. Whichever of these products you use to compile your code is unlikely to churn out anything different to the next.

The structure of the basic .app folder:

```<code>MyApp.app
  +-- Contents
      --- Info.plist
      +-- MacOS
          --- MyApp
          --- MyApp.exe
      +-- Resources
          --- MyApp.icns
</code>```

The contents are as follows:

Info.plist is a Mac OS specific XML file that contains a description of your .app package. It will look something like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>English</string>
    <key>CFBundleExecutable</key>
    <string>MyApp</string>
    <key>CFBundleIconFile</key>
    <string>MyApp.icns</string>
    <key>CFBundleIdentifier</key>
    <string>com.myapp</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>My App Name</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>1.2.3</string>
    <key>CFBundleSignature</key>
    <string>xmmd</string>
    <key>CFBundleVersion</key>
    <string>1.2.3</string>
    <key>NSAppleScriptEnabled</key>
    <string>NO</string>
</dict>
</plist>
</code>```

The MyApp.icns file is an icon file you want to use as the icon for your app package.

The MyApp.exe file is your compiled .NET exe.

The MyApp file is an executable command file that is executed when the .app package is executed by the user. This is referenced in the plist file under CFBundleExecutable and has to be executable (+x permissions, ). This is what it might look like:

```<code>#!/bin/sh

DIR=$(cd "$(dirname "$0")"; pwd)
MONO_FRAMEWORK_PATH=/Library/Frameworks/Mono.framework/Versions/Current
export DYLD_FALLBACK_LIBRARY_PATH="$DIR:$MONO_FRAMEWORK_PATH/lib:/lib:/usr/lib"
export PATH="$MONO_FRAMEWORK_PATH/bin:$PATH"

exec mono "$DIR/MyApp.exe"
</code>```

Hope this helps. Cheers, Martin.

Body:
Assuming Mono is installed on all of your target machines then you can put together (manually) a .app package folder that will run your .exe file when a user double-clicks on it. There's a certain set of things you'll need to put in the .app package, one of which is a command shell file that will kick-off your .exe and will be executed when the .app is run.

B.t.w. Visual Studio Mac and Xamarin Studio and MonoDevelop are all basically different twists on the same thing, MonoDevelop. VS mac and XS have extras but the basic underlying IDE is MD. Whichever of these products you use to compile your code is unlikely to churn out anything different to the next.

The structure of the basic .app folder:

MyApp.app
  +-- Contents
      --- Info.plist
      +-- MacOS
          --- MyApp
          --- MyApp.exe
      +-- Resources
          --- MyApp.icns

The contents are as follows:

Info.plist is a Mac OS specific XML file that contains a description of your .app package. It will look something like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>English</string>
    <key>CFBundleExecutable</key>
    <string>MyApp</string>
    <key>CFBundleIconFile</key>
    <string>MyApp.icns</string>
    <key>CFBundleIdentifier</key>
    <string>com.myapp</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>My App Name</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>1.2.3</string>
    <key>CFBundleSignature</key>
    <string>xmmd</string>
    <key>CFBundleVersion</key>
    <string>1.2.3</string>
    <key>NSAppleScriptEnabled</key>
    <string>NO</string>
</dict>
</plist>

The MyApp.icns file is an icon file you want to use as the icon for your app package.

The MyApp.exe file is your compiled .NET exe.

The MyApp file is an executable command file that is executed when the .app package is executed by the user. This is referenced in the plist file under CFBundleExecutable and has to be executable (+x permissions, ). This is what it might look like:

#!/bin/sh

DIR=$(cd "$(dirname "$0")"; pwd)
MONO_FRAMEWORK_PATH=/Library/Frameworks/Mono.framework/Versions/Current
export DYLD_FALLBACK_LIBRARY_PATH="$DIR:$MONO_FRAMEWORK_PATH/lib:/lib:/usr/lib"
export PATH="$MONO_FRAMEWORK_PATH/bin:$PATH"

exec mono "$DIR/MyApp.exe"

Hope this helps. Cheers, Martin.


问:
Sequelize one-to-many query (with include) produces Y is not associated to X
so i'm having problems with sequelize's one to many relationship, my associations are defined like this:

```<code>X.hasMany(Y, { as: 'Ys' });
Y.belongsTo(X, { as: 'X' });
</code>```

and my findAll is here:

```<code>return X.findAll(
        {
            where: {
                something: something,
            },
            include: [{ model: db.Y, as: 'Ys' }]
        }
    );
</code>```

and this is producing the error:

"error": "Y (Ys) is not associated to X!"

Not quite sure what i'm doing wrong here :/

答:
There's some confusion on your associations

logically 'X' has many 'Ys', association should be X.hasMany(Y, {as: 'Ys'});

'Y' belongs to 'X' should be Y.hasMany(X, {as: 'X'});

Body:
so i'm having problems with sequelize's one to many relationship, my associations are defined like this:

X.hasMany(Y, { as: 'Ys' });
Y.belongsTo(X, { as: 'X' });

and my findAll is here:

return X.findAll(
        {
            where: {
                something: something,
            },
            include: [{ model: db.Y, as: 'Ys' }]
        }
    );

and this is producing the error:

"error": "Y (Ys) is not associated to X!"

Not quite sure what i'm doing wrong here :/


答:
The term you used was wrong it should be
      SetImageResources(R.drawable.image);
Your image can just be the color and the button text will hover it.</p>

Title: How to Remove Background Color of Button to get Default Background in Android


答:
To parse the input in binary, use Scanner.nextBigInteger() with a radix of 2:

```<code>System.out.print("Enter the decimal number:");
BigInteger i = sc.nextBigInteger(2);
System.out.println(i);
</code>```

The output will be in decimal by default.

Title: How to convert binary to decimal using BigInteger?

Body:
To parse the input in binary, use Scanner.nextBigInteger() with a radix of 2:

System.out.print("Enter the decimal number:");
BigInteger i = sc.nextBigInteger(2);
System.out.println(i);

The output will be in decimal by default.


问:
How do I use gdbserver on Raspberry Pi?
I try to remotly debug using gdb.
On the target computer (Raspberry Pi with Ubuntu Mate 15.10), I run gdbserver :4444 main. And on my laptop, I run ./arm-linux-gnueabihf-gdb ~/workspace/piCCompileProj/Debug/main. At the gdb prompt (on my laptop), I type:

```<code>target remote <target>:4444
run
</code>```

But gdb reports this error message:

The "remote" target does not support "run".  Try "help target" or "continue".

How I can use gdb remote? When I use gdb directly on the Raspberry Pi, it runs as expected.

答:
This is what helped me out(If any beginner is out here and searching for the solution)

Assumptions: Ubuntu(17.04)-> Host & Raspberry Pi (Model-3b) -> Target, My executable (.o) file-> dowhile

Step 1: Make executable file (.o) file for your target from your host machine. Please find follow command:

arm-linux-gnueabihf-gcc -g dowhile.c -o dowhile

Please download respective libraries to run this command successfully.

Step 2: Copy the generated executable file (dowhile.o) to the target machine like stated below:

scp dowhile root@10.x.y.z:/xxxx/yyyy/

(Please fill x and y details according to your target and source)

Also, check the copied executable is working fine:

./dowhile

Step 3: Run gdbserver on your target machine:

gdbserver localhost:2000 dowhile

(Keep 2000 or any number for your port, it will work anyway)

Step 4: Run gdb on your host machine:

gdb-multiarch dowhile

Step 5: Set architecture as arm

(gdb) set architecture armv5te

Step 6: Connect your target remotely

(gdb) target remote 10.x.y.z:2000

And you are done :)

Happy debugging!!!

Title: How do I use gdbserver on Raspberry Pi?

Body:
I try to remotly debug using gdb.
On the target computer (Raspberry Pi with Ubuntu Mate 15.10), I run gdbserver :4444 main. And on my laptop, I run ./arm-linux-gnueabihf-gdb ~/workspace/piCCompileProj/Debug/main. At the gdb prompt (on my laptop), I type:

target remote <target>:4444
run

But gdb reports this error message:

The "remote" target does not support "run".  Try "help target" or "continue".

How I can use gdb remote? When I use gdb directly on the Raspberry Pi, it runs as expected.


答:
You need to stop and start again from scratch.

First of all, you need to catch the AFTER UPDATE event - not the insert - since you want to do something when the salary is updated (an existing value is replaced with a higher one).

Secondly, the trigger will be called once per UPDATE statement and if that UPDATE affects more than one row, the Deleted and Inserted pseudo tables will contain multiple rows of data - so your SELECT @Salary = salary FROM Inserted statement is doomed - it will fetch one arbitrary row and ignore all others that might be also affected.

In an UPDATE case, Inserted will have the new values (after the update), while Deleted has the old values (before the update) - so the difference between these two pseudo tables can be used to figure out if the salary increase was more than 20%:

```<code>CREATE TRIGGER trBusDriverSalaryIncrease
ON dbo.Bus_Driver
AFTER UPDATE
AS
BEGIN
    -- declare a table variable to hold all revelant values
    DECLARE @RelevantIncreases TABLE (drNo INT, StationNo INT, SalaryIncrease DECIMAL(18,2))

    -- find those bus drivers who have had a more than 20% increase in their salary
    INSERT INTO @relevantIncreases (drNo, StationNo, SalaryIncrease)
        SELECT
            i.drNo, i.StationNo,    -- Driver and Station No
            (i.Salary - d.Salary)   -- Salary increase in absolute numbers
        FROM
            Deleted d
        INNER JOIN
            Inserted i ON d.drNo = i.drNo
        WHERE
            -- Salary increased by more than 20%
            i.Salary > 1.2 * d.Salary

    -- now that we have all the relevant bus drivers and their salary increase
    -- insert this into the Station.Salary_Commission column
    UPDATE s
    SET Salary_Commission = s.Salary_Commission + ri.SalaryIncrease * 0.0005
    FROM dbo.Station s
    INNER JOIN @RelevantIncreases ri ON ri.StationNo = s.StationNo
END
</code>```

Title: Writing a SQL Server trigger - error

Body:
You need to stop and start again from scratch.

First of all, you need to catch the AFTER UPDATE event - not the insert - since you want to do something when the salary is updated (an existing value is replaced with a higher one).

Secondly, the trigger will be called once per UPDATE statement and if that UPDATE affects more than one row, the Deleted and Inserted pseudo tables will contain multiple rows of data - so your SELECT @Salary = salary FROM Inserted statement is doomed - it will fetch one arbitrary row and ignore all others that might be also affected.

In an UPDATE case, Inserted will have the new values (after the update), while Deleted has the old values (before the update) - so the difference between these two pseudo tables can be used to figure out if the salary increase was more than 20%:

CREATE TRIGGER trBusDriverSalaryIncrease
ON dbo.Bus_Driver
AFTER UPDATE
AS
BEGIN
    -- declare a table variable to hold all revelant values
    DECLARE @RelevantIncreases TABLE (drNo INT, StationNo INT, SalaryIncrease DECIMAL(18,2))

    -- find those bus drivers who have had a more than 20% increase in their salary
    INSERT INTO @relevantIncreases (drNo, StationNo, SalaryIncrease)
        SELECT
            i.drNo, i.StationNo,    -- Driver and Station No
            (i.Salary - d.Salary)   -- Salary increase in absolute numbers
        FROM
            Deleted d
        INNER JOIN
            Inserted i ON d.drNo = i.drNo
        WHERE
            -- Salary increased by more than 20%
            i.Salary > 1.2 * d.Salary

    -- now that we have all the relevant bus drivers and their salary increase
    -- insert this into the Station.Salary_Commission column
    UPDATE s
    SET Salary_Commission = s.Salary_Commission + ri.SalaryIncrease * 0.0005
    FROM dbo.Station s
    INNER JOIN @RelevantIncreases ri ON ri.StationNo = s.StationNo
END


问:
Selenium (with python) how to modify an element css style
I'm trying to change CSS style of an element (example: from "visibility: hidden;" to "visibility: visible;") using selenium .execute_script. (any other method through selenium+python would be accepted gracefully).

my code:

```<code>driver = webdriver.Firefox()
driver.get("http://www.example.com")

elem = driver.find_element_by_id('copy_link')

elem.execute_script(  area of my problem )
</code>```

what do i need to do in order to play with the CSS of the webpage ?

答:
Here is solution i found using document style sheets.
This way is great because you can also add pseudo class styling. </p>

```<code>script = 'document.styleSheets[0].insertRule("button:focus {background-color: red !important;}", 0 )'
driver.execute_script(script)
</code>```

Body:
I'm trying to change CSS style of an element (example: from "visibility: hidden;" to "visibility: visible;") using selenium .execute_script. (any other method through selenium+python would be accepted gracefully).

my code:

driver = webdriver.Firefox()
driver.get("http://www.example.com")

elem = driver.find_element_by_id('copy_link')

elem.execute_script(  area of my problem )

what do i need to do in order to play with the CSS of the webpage ?

Body:
Here is solution i found using document style sheets.
This way is great because you can also add pseudo class styling.

script = 'document.styleSheets[0].insertRule("button:focus {background-color: red !important;}", 0 )'
driver.execute_script(script)


问:
What are possible causes of "failed to map segment from shared object: operation not permitted", and how to debug?
I have two executables, both cross compiled to run in Android.  I have put both on the device in the same directory.  I have put all the shared libraries that they are dependent on in the same directory, including ld-linux.so.3.  I run the executables by using:

ld-linux.so.3 --library-path /path/to/libraries executable_name

both work on older versions of Android when running as any user.  The both work on the latest version of Android if running as root.  Only one works on the latest version of android when running as any user.  Instead it gives:

failed to map segment from shared object: executable_name operation not permitted

How can I find out what is different with the executable that won't run?

I read a lot online and most people that get this error, either:

A) don't have execute permissions for one of the libraries they are dependent on or the executable itself.

or

B) are trying to run from a directory that is mounted as NOEXEC.

both of these don't appear to be the case.  It can find all libraries and I can load any library by itself and see what other things it is dependent on being resolved.  Also, I can run basic scripts from the directories of interest.

The newer version of Android, Jelly Bean, is a different linux kernel version and I wonder if that is related.

What give?  How do I debug?

答:
I had this error in a different context. For some reason it causes an error when trying to use the /tmp folder.

To solve this I simply:

```<code>mkdir tmp
export TMPDIR=`pwd`/tmp
</code>```

The TMPDIR is a constant that tells where the temporary folder of the system is.
This solutions resolves by creating a directory where we are allowed to and settings this directory into the system. Therefore we can now write to the new system default temporary folder.

Body:
I had this error in a different context. For some reason it causes an error when trying to use the /tmp folder.

To solve this I simply:

mkdir tmp
export TMPDIR=`pwd`/tmp

The TMPDIR is a constant that tells where the temporary folder of the system is.
This solutions resolves by creating a directory where we are allowed to and settings this directory into the system. Therefore we can now write to the new system default temporary folder.

ContentLicense: CC BY-SA 4.0


问:
How do I list all of the items in a dictionary by biggest value to lowest value using Python and Django?
So I have this as my html file.

```<code><form method="post">
    {% csrf_token %}
    Problem: <input type="text" name="poi" autofocus>
    <input type="submit" value="Submit">
    <hr>
</form>
<br>
<ul>
    {% for u in sort %}
        <li>{{ u|safe }}</li>
    {% endfor %}
<ul>
</code>```

and I have my variable called sort which takes all of the items in a dictionary dictionary = {'hi': 5, 'hey': 3, 'hiya': 1} and sort them by highest to lowest value using the following.

```<code>for w in sorted(dictionary, key=dictionary.get, reverse=True):
    sort.append(w)
</code>```

Now the list is in order from highest to lowest values. As you can see in the html file, I am trying to print them all in order. What's going wrong is that it's not printing anything. What am I doing wrong?

EDIT: See the following for render.

```<code>try:
    return HttpResponse(request, 'patrec.html', {'sort':sort})
except:
    return render(request, 'patrec.html')
</code>```

答:
You are using HttpResponse in a wrong way. It is destined to throw an exception because that's not how it works. Hence it raises an exception all the time and within except block it will return result of render where you are not passing the {'sort': sort} as context. So just remove the try and except block along with HttpResponse. You should only have this:

```<code>return render(request, 'patrec.html', {'sort': sort})
</code>```

Body:
So I have this as my html file.

<form method="post">
    {% csrf_token %}
    Problem: <input type="text" name="poi" autofocus>
    <input type="submit" value="Submit">

</form>

    {% for u in sort %}

{{ u|safe }}

    {% endfor %}

and I have my variable called sort which takes all of the items in a dictionary dictionary = {'hi': 5, 'hey': 3, 'hiya': 1} and sort them by highest to lowest value using the following.

for w in sorted(dictionary, key=dictionary.get, reverse=True):
    sort.append(w)

Now the list is in order from highest to lowest values. As you can see in the html file, I am trying to print them all in order. What's going wrong is that it's not printing anything. What am I doing wrong?

EDIT: See the following for render.

try:
    return HttpResponse(request, 'patrec.html', {'sort':sort})
except:
    return render(request, 'patrec.html')

Body:
You are using HttpResponse in a wrong way. It is destined to throw an exception because that's not how it works. Hence it raises an exception all the time and within except block it will return result of render where you are not passing the {'sort': sort} as context. So just remove the try and except block along with HttpResponse. You should only have this:

return render(request, 'patrec.html', {'sort': sort})


问:
copy file in command prompt with Arabic file name
How can I copy a file with Arabic characters in the name via the command prompt?

I tried this:

```<code>copy C:\توزيع العمل.doc D:\توزيع العمل.doc
</code>```

It didn't work. What I can do to solve this problem? Thank you.

答:
Wrap file path to quotes. Like this "C:\توزيع العمل.doc".
So final command will look like.

copy "C:\توزيع العمل.doc" "D:\توزيع العمل.doc"

Body:
How can I copy a file with Arabic characters in the name via the command prompt?

I tried this:

copy C:\توزيع العمل.doc D:\توزيع العمل.doc

It didn't work. What I can do to solve this problem? Thank you.


问:
Python order filling loop?
Let's say I have a bunch of orders I need to fill

```<code>orders = [39.789032, 36.023618, 3.0539913, 20.0, 1.314, 2.5, 0.401, 1.0, 1.989, 6.3254668, 0.5]
</code>```

I have a starting volume of say 100

```<code>startingvolume = 100
</code>```

I want to iterate through the orders until my volume/order is filled

so the first order would be my initial 100 minus the first order of 39.789032 which leaves 60.2110968 of my order still to be filled. What is the most Pythonic way to fill my order until my starting volume is 0?

答:
You can solve your question using combinations from itertools module and max(), like this example:

```<code>from itertools import combinations

orders = [39.789032, 36.023618, 3.0539913, 20.0, 1.314, 2.5, 0.401, 1.0, 1.989, 6.3254668, 0.5]
startingvolume = 100

sub = []
for k in range(1, len(orders)):
    sub.append(max([[j, sum(j)] for j in combinations(orders, k) if sum(j) <= startingvolume], key = lambda x: x[1]))

best_order, fill_max = max(sub, key = lambda x: x[1])
print("best order is: {}\nMax to fill from starting volume is: {}"
                                    .format(best_order, fill_max))
</code>```

Output:

```<code>best order is: (39.789032, 36.023618, 3.0539913, 20.0, 1.0)
Max to fill from starting volume is: 99.86664
</code>```

Title: Python order filling loop?

Body:
Let's say I have a bunch of orders I need to fill

orders = [39.789032, 36.023618, 3.0539913, 20.0, 1.314, 2.5, 0.401, 1.0, 1.989, 6.3254668, 0.5]

I have a starting volume of say 100

startingvolume = 100

I want to iterate through the orders until my volume/order is filled

so the first order would be my initial 100 minus the first order of 39.789032 which leaves 60.2110968 of my order still to be filled. What is the most Pythonic way to fill my order until my starting volume is 0?

Body:
You can solve your question using combinations from itertools module and max(), like this example:

from itertools import combinations

orders = [39.789032, 36.023618, 3.0539913, 20.0, 1.314, 2.5, 0.401, 1.0, 1.989, 6.3254668, 0.5]
startingvolume = 100

sub = []
for k in range(1, len(orders)):
    sub.append(max([[j, sum(j)] for j in combinations(orders, k) if sum(j) <= startingvolume], key = lambda x: x[1]))

best_order, fill_max = max(sub, key = lambda x: x[1])
print("best order is: {}\nMax to fill from starting volume is: {}"
                                    .format(best_order, fill_max))

Output:

best order is: (39.789032, 36.023618, 3.0539913, 20.0, 1.0)
Max to fill from starting volume is: 99.86664


问:
How to change a checked event to an onclick event?
How I would change this simple function into an onclick event using a button, rather than a checkbox? I am really new to JavaScript.</p>

```<code>function showhide() {
        if (document.getElementById('toggle').checked == true) {
            document.getElementById('hidethis').style.display = 'block';
        } else {
            document.getElementById('hidethis').style.display = 'none';
        }
    }
</code>```

答:
```<code><button id="yourbutton">Click</button>
<script type="text/javsacript">$("#yourbutton").on("click", function() {
    if (document.getElementById('toggle').checked == true) {
        document.getElementById('hidethis').style.display = 'block';
    } else {
        document.getElementById('hidethis').style.display = 'none';
    }
});</script>
</code>```

Hope it helps

And dont forget to include jquery plugin

Body:
How I would change this simple function into an onclick event using a button, rather than a checkbox? I am really new to JavaScript.

function showhide() {
        if (document.getElementById('toggle').checked == true) {
            document.getElementById('hidethis').style.display = 'block';
        } else {
            document.getElementById('hidethis').style.display = 'none';
        }
    }

Body:
<button id="yourbutton">Click</button>
<script type="text/javsacript">$("#yourbutton").on("click", function() {
    if (document.getElementById('toggle').checked == true) {
        document.getElementById('hidethis').style.display = 'block';
    } else {
        document.getElementById('hidethis').style.display = 'none';
    }
});</script>

Hope it helps

And dont forget to include jquery plugin<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>


问:
Symfony Parent Child category relation
I have a Product Category table, where I have stored categories if parent_id is null then assume this is parent category if not null then it has child categories. Now the issue is I can't show parent category name in listing page, so can someone have an idea how to make a relation in Product Category entity?

Symfony version: 3.3

Table Structure:(product_category)

```<code>  id
  parent_id
  slug
  title
</code>```

I have tried this code in ProductCategory entity but it doesn't show any relational data:

```<code>class ProductCategory
{
    /**
    * @ORM\OneToMany(targetEntity="ProductCategory", mappedBy="parent")
    * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", nullable=true)
    */
    private $parent;
</code>```

答:
I usually use children and parent and this is how I use It:

```<code>    /**
     * One ProductCategory has Many ProductCategories.
     * @ORM\OneToMany(targetEntity="ProductCategory", mappedBy="parent")
     */
    private $children;

    /**
     * Many ProductCategories have One ProductCategory.
     * @ORM\ManyToOne(targetEntity="ProductCategory", inversedBy="children")
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", nullable=true)
     */
    private $parent;
</code>```

EDIT

```<code>   /**
     * ProductCategory constructor.
     */
    public function __construct()
    {
        $this->children = new ArrayCollection();
    }
</code>```

Getters / Setters and this stuff:

```<code>   /**
    * @param ProductCategory $children
    * @return $this
    */
   public function addChildren (ProductCategory $children)
   {
       $this->children[] = $children;

       return $this;
   }
</code>```

Title: Symfony Parent Child category relation

Body:
I have a Product Category table, where I have stored categories if parent_id is null then assume this is parent category if not null then it has child categories. Now the issue is I can't show parent category name in listing page, so can someone have an idea how to make a relation in Product Category entity?

Symfony version: 3.3

Table Structure:(product_category)

  id
  parent_id
  slug
  title

I have tried this code in ProductCategory entity but it doesn't show any relational data:

class ProductCategory
{
    /**
    * @ORM\OneToMany(targetEntity="ProductCategory", mappedBy="parent")
    * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", nullable=true)
    */
    private $parent;

Body:
I usually use children and parent and this is how I use It:

    /**
     * One ProductCategory has Many ProductCategories.
     * @ORM\OneToMany(targetEntity="ProductCategory", mappedBy="parent")
     */
    private $children;

    /**
     * Many ProductCategories have One ProductCategory.
     * @ORM\ManyToOne(targetEntity="ProductCategory", inversedBy="children")
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", nullable=true)
     */
    private $parent;

EDIT

   /**
     * ProductCategory constructor.
     */
    public function __construct()
    {
        $this->children = new ArrayCollection();
    }

Getters / Setters and this stuff:

   /**
    * @param ProductCategory $children
    * @return $this
    */
   public function addChildren (ProductCategory $children)
   {
       $this->children[] = $children;

       return $this;
   }


问:
angualr2 use the http.get() to request the local json data
Recently i am learn the angular2's http client and i have finished the demo with angular-in-memory-web-api.Now i want to use http.get to request the local json data ,but browser tell me zone.js:1980 GET http://localhost:4200/app/hero.json 404 (Not Found),after read the related posts of Angular2 404 Not Found for URL: http://localhost/WebApi2/api/hero and the simliar one of angular get, i have removed the 'angular-in-memory-web-api' ,InMemoryWebApiModule.forRoot(HeroData)  and the related file from my project ,but the issue of 404 (Not Found) is stil exists,the key code is following:

```<code>//app.module.ts
@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    JsonpModule,
  ],
  declarations: [
    AppComponent,
    HeroListComponent,
    HeroListPromiseComponent,
    WikiComponent,
    WikiSmartComponent
  ],
  providers: [ requestOptionsProvider ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}
</code>```

//hero.service.tsenter code here

```<code>@Injectable()
export class HeroService {
  private heroesUrl = 'app/hero.json';

  constructor (private http: Http) {}

  getHeroes(): Observable<Hero[]> {
    // debugger;
    return this.http.get(this.heroesUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  }
  private extractData(res: Response) {
    // http.get or http.post return the json obj
    let body = res.json();
    return body.data || { };
  }
</code>```

if you want all code, i have pushed it to my github.this is the address

anyone can help me please

答: thanks for everyone who try to help me solve the problem.just now,i found the answer which mean we should put the accessible resource in the assets file in order that user can get from the server.so i just try it and the problem was solved. wish this is helpful for everyone who encounter the problem; the answer i saw</p>

Body:
Recently i am learn the angular2's http client and i have finished the demo with angular-in-memory-web-api.Now i want to use http.get to request the local json data ,but browser tell me zone.js:1980 GET http://localhost:4200/app/hero.json 404 (Not Found),after read the related posts of Angular2 404 Not Found for URL: http://localhost/WebApi2/api/hero and the simliar one of angular get, i have removed the 'angular-in-memory-web-api' ,InMemoryWebApiModule.forRoot(HeroData)  and the related file from my project ,but the issue of 404 (Not Found) is stil exists,the key code is following:

//app.module.ts
@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    JsonpModule,
  ],
  declarations: [
    AppComponent,
    HeroListComponent,
    HeroListPromiseComponent,
    WikiComponent,
    WikiSmartComponent
  ],
  providers: [ requestOptionsProvider ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

//hero.service.tsenter code here

@Injectable()
export class HeroService {
  private heroesUrl = 'app/hero.json';

  constructor (private http: Http) {}

  getHeroes(): Observable<Hero[]> {
    // debugger;
    return this.http.get(this.heroesUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  }
  private extractData(res: Response) {
    // http.get or http.post return the json obj
    let body = res.json();
    return body.data || { };
  }

if you want all code, i have pushed it to my github.this is the address

anyone can help me please


问:
How do I append one string to another in Python?
How do I efficiently append one string to another? Are there any faster alternatives to:

```<code>var1 = "foo"
var2 = "bar"
var3 = var1 + var2
</code>```

For handling multiple strings in a list, see How to concatenate (join) items in a list to a single string.

See How do I put a variable’s value inside a string (interpolate it into the string)? if some inputs are not strings, but the result should still be a string.

答:
Don't prematurely optimize. If you have no reason to believe there's a speed bottleneck caused by string concatenations then just stick with + and +=:

```<code>s  = 'foo'
s += 'bar'
s += 'baz'
</code>```

That said, if you're aiming for something like Java's StringBuilder, the canonical Python idiom is to add items to a list and then use str.join to concatenate them all at the end:

```<code>l = []
l.append('foo')
l.append('bar')
l.append('baz')

s = ''.join(l)
</code>```

Body:
How do I efficiently append one string to another? Are there any faster alternatives to:

var1 = "foo"
var2 = "bar"
var3 = var1 + var2

For handling multiple strings in a list, see How to concatenate (join) items in a list to a single string.

See How do I put a variable’s value inside a string (interpolate it into the string)? if some inputs are not strings, but the result should still be a string.

Body:
Don't prematurely optimize. If you have no reason to believe there's a speed bottleneck caused by string concatenations then just stick with + and +=:

s  = 'foo'
s += 'bar'
s += 'baz'

That said, if you're aiming for something like Java's StringBuilder, the canonical Python idiom is to add items to a list and then use str.join to concatenate them all at the end:

l = []
l.append('foo')
l.append('bar')
l.append('baz')

s = ''.join(l)

ContentLicense: CC BY-SA 2.5


问:
Unable to install npm with node 6 due to unmet dependencies on ubuntu
Here is the error message:

```<code>Step 6/10 : RUN apt-get install -y npm
 ---> Running in 85acc9ae3f0d
Reading package lists...
Building dependency tree...
Reading state information...
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 npm : Depends: nodejs but it is not going to be installed
       Depends: node-abbrev (>= 1.0.4) but it is not going to be installed
       Depends: node-ansi (>= 0.3.0-2) but it is not going to be installed
       Depends: node-ansi-color-table but it is not going to be installed
       Depends: node-archy but it is not going to be installed
       Depends: node-block-stream but it is not going to be installed
       Depends: node-fstream (>= 0.1.22) but it is not going to be installed
       Depends: node-fstream-ignore but it is not going to be installed
       Depends: node-github-url-from-git but it is not going to be installed
       Depends: node-glob (>= 3.1.21) but it is not going to be installed
       Depends: node-graceful-fs (>= 2.0.0) but it is not going to be installed
       Depends: node-inherits but it is not going to be installed
       Depends: node-ini (>= 1.1.0) but it is not going to be installed
       Depends: node-lockfile but it is not going to be installed
       Depends: node-lru-cache (>= 2.3.0) but it is not going to be installed
       Depends: node-minimatch (>= 0.2.11) but it is not going to be installed
       Depends: node-mkdirp (>= 0.3.3) but it is not going to be installed
       Depends: node-gyp (>= 0.10.9) but it is not going to be installed
       Depends: node-nopt (>= 3.0.1) but it is not going to be installed
       Depends: node-npmlog but it is not going to be installed
       Depends: node-once but it is not going to be installed
       Depends: node-osenv but it is not going to be installed
       Depends: node-read but it is not going to be installed
       Depends: node-read-package-json (>= 1.1.0) but it is not going to be installed
       Depends: node-request (>= 2.25.0) but it is not going to be installed
       Depends: node-retry but it is not going to be installed
       Depends: node-rimraf (>= 2.2.2) but it is not going to be installed
       Depends: node-semver (>= 2.1.0) but it is not going to be installed
       Depends: node-sha but it is not going to be installed
       Depends: node-slide but it is not going to be installed
       Depends: node-tar (>= 0.1.18) but it is not going to be installed
       Depends: node-underscore but it is not going to be installed
       Depends: node-which but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
The command '/bin/sh -c apt-get install -y npm' returned a non-zero code: 100
</code>```

It comes from running this dockerfile:

```<code>FROM ubuntu:16.04

RUN apt-get update -y
RUN apt-get install -y curl
# To install node 6
RUN curl -sL https://deb.nodesource.com/setup_6.x | bash -
RUN apt-get install -y nodejs
RUN apt-get install -y npm
RUN apt-get install -y git
</code>```

I started the docker process by docker build -t mysystem .

I suppose the npm in original apt-get db is not compatible with nodejs. How can I correct this? I want to consider nvm as my last resort

答:
npm comes bundeled with node, so you should be fine with only:</p>

```<code>apt-get install -y nodejs
</code>```

Body:
Here is the error message:

Step 6/10 : RUN apt-get install -y npm
 ---> Running in 85acc9ae3f0d
Reading package lists...
Building dependency tree...
Reading state information...
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 npm : Depends: nodejs but it is not going to be installed
       Depends: node-abbrev (>= 1.0.4) but it is not going to be installed
       Depends: node-ansi (>= 0.3.0-2) but it is not going to be installed
       Depends: node-ansi-color-table but it is not going to be installed
       Depends: node-archy but it is not going to be installed
       Depends: node-block-stream but it is not going to be installed
       Depends: node-fstream (>= 0.1.22) but it is not going to be installed
       Depends: node-fstream-ignore but it is not going to be installed
       Depends: node-github-url-from-git but it is not going to be installed
       Depends: node-glob (>= 3.1.21) but it is not going to be installed
       Depends: node-graceful-fs (>= 2.0.0) but it is not going to be installed
       Depends: node-inherits but it is not going to be installed
       Depends: node-ini (>= 1.1.0) but it is not going to be installed
       Depends: node-lockfile but it is not going to be installed
       Depends: node-lru-cache (>= 2.3.0) but it is not going to be installed
       Depends: node-minimatch (>= 0.2.11) but it is not going to be installed
       Depends: node-mkdirp (>= 0.3.3) but it is not going to be installed
       Depends: node-gyp (>= 0.10.9) but it is not going to be installed
       Depends: node-nopt (>= 3.0.1) but it is not going to be installed
       Depends: node-npmlog but it is not going to be installed
       Depends: node-once but it is not going to be installed
       Depends: node-osenv but it is not going to be installed
       Depends: node-read but it is not going to be installed
       Depends: node-read-package-json (>= 1.1.0) but it is not going to be installed
       Depends: node-request (>= 2.25.0) but it is not going to be installed
       Depends: node-retry but it is not going to be installed
       Depends: node-rimraf (>= 2.2.2) but it is not going to be installed
       Depends: node-semver (>= 2.1.0) but it is not going to be installed
       Depends: node-sha but it is not going to be installed
       Depends: node-slide but it is not going to be installed
       Depends: node-tar (>= 0.1.18) but it is not going to be installed
       Depends: node-underscore but it is not going to be installed
       Depends: node-which but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
The command '/bin/sh -c apt-get install -y npm' returned a non-zero code: 100

It comes from running this dockerfile:

FROM ubuntu:16.04

RUN apt-get update -y
RUN apt-get install -y curl
# To install node 6
RUN curl -sL https://deb.nodesource.com/setup_6.x | bash -
RUN apt-get install -y nodejs
RUN apt-get install -y npm
RUN apt-get install -y git

I started the docker process by docker build -t mysystem .

I suppose the npm in original apt-get db is not compatible with nodejs. How can I correct this? I want to consider nvm as my last resort

Body:
npm comes bundeled with node, so you should be fine with only:

apt-get install -y nodejs


问:
How to debug an asynchronous RFC - Starting new task...Performing...on end of task?
I am a beginner in SAP ABAP. I am debugging an asynchronous RFC (parallel processing). I have put a break-point in the calling portion of the RFC, an external break-point inside the RFC and an external break point in the form which is called at the end of task through perform. I am able to debug the RFC FM.

Another session opens up. But I am not able to debug the perform which is called after end of task. After the RFC is debugged, the control returns to the calling point of the FM. it doesn't go inside the form. When all the iterations are finished, then at the end it goes inside the perform. Why so? shouldn't the perform be executed in parallel?

Inside the perform I have written like RECEIVE RESULTS FROM FUNCTION XXX. But the debugger control is not going inside the perform after returning from the RFC.

答:
You have given very little information on the overall program flow, but there's a part of the documentation that might be relevant to your case:

A prerequisite for the execution of a registered callback routine is
  that the calling program still exists in its internal session when
  the remote function is terminated. It is then executed here at the
  next change of the work process in a roll-in. If the program was
  terminated or is located on the stack as part of a call sequence, the
  callback routine is not executed.

[...]

The time when the callback routines are executed can be programmed
  explicitly or be reached implicitly:

The statement WAIT FOR ASYNCHRONOUS TASKS is used for explicit programming. As specified by a condition, this statement changes the
  work process and hence executes the callback routines registered up to
  this time. It waits for as many registered routines to end until the
  condition is met (the maximum wait time can be restricted). Explicit
  programming is recommended whenever the results of the remote function
  are required in the current program.

If the results of the remote function are not required in the current program, the time at which the callback routines are executed
  can also be determined by an implicit change of the work process (for
  example, at the end of a dialog step). This can be a good idea, for
  example, in GUI scenarios in which uses of WAIT are not wanted. In
  this case, it must be ensured that the work process changes before the
  program is ended. There is also a risk that, if the work process is
  changed implicitly, not all callback routines are registered in time.

It is likely that the program issuing the call and registering the callback routine is either terminated or does not issue a WAIT FOR ASYNCHRONOUS TASKS so that the callback is only executed on the next roll-in.

Re-reading your question, you apparently assume that the callback routine will be executed in parallel to the program that has registered it. That is not the case, ABAP is not multi-threaded.


问:
How to add post query parameter string with double quote in url in retrofit?
I am accessing an api .which looks like

http://XXX.XX.XXX.XXX/api/Gallery/getgallerylist?userid="17" .

I have tried the following annotation.

```<code> @POST("Gallery/getgallerylist")
    Call<GalleryImagesResponse> getGalleryImages(@Query("userid") String userid);
</code>```

But the url it requests is http://XXX.XX.XXX.XXX/api/Gallery/getgallerylist?userid=17

So that how can I add double quote to userid's value like userid="17".

答:
You can pass the string as @Path to the URL like this.

```<code>@POST("http://XXX.XX.XXX.XXX/api/Gallery/getgallerylist?" + "{path}")
Call<ResponseBody> getGalleryImages(@Path("path") String path);
</code>```

and pass userid=17 to this call, it will append to the URL. and your done

Body:
I am accessing an api .which looks like

http://XXX.XX.XXX.XXX/api/Gallery/getgallerylist?userid="17" .

I have tried the following annotation.

 @POST("Gallery/getgallerylist")
    Call<GalleryImagesResponse> getGalleryImages(@Query("userid") String userid);

But the url it requests is http://XXX.XX.XXX.XXX/api/Gallery/getgallerylist?userid=17

So that how can I add double quote to userid's value like userid="17".

Body:
You can pass the string as @Path to the URL like this.

@POST("http://XXX.XX.XXX.XXX/api/Gallery/getgallerylist?" + "{path}")
Call<ResponseBody> getGalleryImages(@Path("path") String path);

and pass userid=17 to this call, it will append to the URL. and your done


问:
How to change HOME directory and start directory on MSYS2?
I have installed MinGW-w64 and MSYS2. But how do I change the HOME directory in MSYS2? So that when I type cd $home or cd ~ it goes to another directory that I defined.

And how do I write a code so that the starting directory is always where the .bat file is placed on?

In cmd I used this code:

%~d1
cd "%~p1"
call cmd

so when I open cmd on my desktop, it starts from the directory on desktop.

How can I do a similar thing with msys2?

答:
If you would like to use your windows home folder as the home folder for MSYS2, you can edit /etc/nsswitch.conf and write:</p>

```<code>db_home: windows
</code>```

Body:
If you would like to use your windows home folder as the home folder for MSYS2, you can edit /etc/nsswitch.conf and write:

db_home: windows


问:
Angular 2 form validation pattern regex error
I'm creating a form in angular that requires the name field only contain alphanumeric characters and spaces. To do this I use the pattern attribute:

```<code><input type="text" class="form-control" placeholder="Name" name="Name" [(ngModel)]="name" required pattern="/^[a-z\d-_\s]+$/i" #nameField="ngModel">
</code>```

and I have the following error message I want to show when the string does not match:

```<code><div *ngIf="nameField.errors">
   <div [hidden]="!nameField.errors.pattern">
       <p class="has-error">
          Only spaces, letters, and numbers are allowed.
       </p>
   </div>
</div>
</code>```

However, it seems that even when the string should match the regular expression, I can still see the error message. Any ideas?

答:
You may use

```<code>pattern="^[\w\s-]+$"
</code>```

The [A-Za-z\d_] matches the same chars as \w in JavaScript native regex. The whole pattern thus matches one or more ASCII letters, digits, underscores, hyphens or white spaces.

Note that angular anchors the pattern by default, but it is preferable to keep the anchors ^ and $ explicit in the pattern to make it compatible with any other frameworks.

Body:
I'm creating a form in angular that requires the name field only contain alphanumeric characters and spaces. To do this I use the pattern attribute:

<input type="text" class="form-control" placeholder="Name" name="Name" [(ngModel)]="name" required pattern="/^[a-z\d-_\s]+$/i" #nameField="ngModel">

and I have the following error message I want to show when the string does not match:

          Only spaces, letters, and numbers are allowed.

However, it seems that even when the string should match the regular expression, I can still see the error message. Any ideas?

Body:
You may use

pattern="^[\w\s-]+$"

The [A-Za-z\d_] matches the same chars as \w in JavaScript native regex. The whole pattern thus matches one or more ASCII letters, digits, underscores, hyphens or white spaces.

Note that angular anchors the pattern by default, but it is preferable to keep the anchors ^ and $ explicit in the pattern to make it compatible with any other frameworks.


问:
LLDB (Swift): Casting Raw Address into Usable Type
Is there an LLDB command that can cast a raw address into a usable Swift class?

For example:

```<code>(lldb) po 0x7df67c50 as MKPinAnnotationView
</code>```

I know that this address points to a MKPinAnnotationView, but it is not in a frame that I can select. But, I want to cast the raw address into a MKPinAnnotationView so that I can examine its properties. Is this possible?

答:
Thanks to all the answers above, unsafeBitCast also works well with Xcode 8.3.2 / Swift 3 / macOS / Cocoa Application.

Memorize an address of current instance

```<code>(lldb) p tabView.controlTint
(NSControlTint) $R10 = defaultControlTint

(lldb) p self
(LearningStoryboard.NSTabViewController) $R11 = 0x00006080000e2280 {
.....
</code>```

Later, examine them

```<code>(lldb) p unsafeBitCast(0x00006080000e2280, to: NSTabViewController.self).tabView.controlTint
(NSControlTint) $R20 = graphiteControlTint

(lldb) p $R11.tabView.controlTint
(NSControlTint) $R21 = graphiteControlTint
</code>```

If something like this happens

```<code>(lldb) p unsafeBitCast(0x00006080000e2280, to: NSTabViewController.self).tabView.controlTint
error: use of undeclared identifier 'to'

(lldb) p $R11.tabView.controlTint
error: use of undeclared identifier '$R11'
</code>```

make sure that choose one of the stack frames of Swift source code rather than assembler one.

It is likely to happen when the application was paused by clicking a Pause button or stopped with an exception. By choosing a stack frame accordingly, let lldb infer a proper programing language.

Body:
Is there an LLDB command that can cast a raw address into a usable Swift class?

For example:

(lldb) po 0x7df67c50 as MKPinAnnotationView

I know that this address points to a MKPinAnnotationView, but it is not in a frame that I can select. But, I want to cast the raw address into a MKPinAnnotationView so that I can examine its properties. Is this possible?

Body:
Thanks to all the answers above, unsafeBitCast also works well with Xcode 8.3.2 / Swift 3 / macOS / Cocoa Application.

Memorize an address of current instance

(lldb) p tabView.controlTint
(NSControlTint) $R10 = defaultControlTint

(lldb) p self
(LearningStoryboard.NSTabViewController) $R11 = 0x00006080000e2280 {
.....

Later, examine them

(lldb) p unsafeBitCast(0x00006080000e2280, to: NSTabViewController.self).tabView.controlTint
(NSControlTint) $R20 = graphiteControlTint

(lldb) p $R11.tabView.controlTint
(NSControlTint) $R21 = graphiteControlTint

If something like this happens

(lldb) p unsafeBitCast(0x00006080000e2280, to: NSTabViewController.self).tabView.controlTint
error: use of undeclared identifier 'to'

(lldb) p $R11.tabView.controlTint
error: use of undeclared identifier '$R11'

make sure that choose one of the stack frames of Swift source code rather than assembler one.

It is likely to happen when the application was paused by clicking a Pause button or stopped with an exception. By choosing a stack frame accordingly, let lldb infer a proper programing language.


问:
Restrict tomcat in spring boot to certain ip addresses
I need to restrict the embedded tomcat of a spring boot based application to certain ip addresses. I want to allow only incoming connections from two ip addresses and not all.
I know how to do this in a tomcat that is not running embedded but don't know a way to configure this in spring boot. The various server.tomcat.* properties don't seem to offer support for this. There is the property server.address that enables me to bind to a local ip address, but that is not what I need.

答:
Found this answer searching for the same solution.  This is a more accurate way of doing it within Spring Boot.

```<code>@Bean
public FilterRegistrationBean remoteAddressFilter() {

    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
    RemoteAddrFilter filter = new RemoteAddrFilter();

    filter.setAllow("192.168.0.2");
    filter.setDenyStatus(404);

    filterRegistrationBean.setFilter(filter);
    filterRegistrationBean.addUrlPatterns("/*");

    return filterRegistrationBean;

}
</code>```

The default response is a 403.  To change that to a 404 this is added filter.setDenyStatus(404);

You can also set Deny addresses instead with filter.setDeny("192\\.168\\.0\\.2");

RemoteAddressFilter Docs for Tomcat

Body:
Found this answer searching for the same solution.  This is a more accurate way of doing it within Spring Boot.

@Bean
public FilterRegistrationBean remoteAddressFilter() {

    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
    RemoteAddrFilter filter = new RemoteAddrFilter();

    filter.setAllow("192.168.0.2");
    filter.setDenyStatus(404);

    filterRegistrationBean.setFilter(filter);
    filterRegistrationBean.addUrlPatterns("/*");

    return filterRegistrationBean;

}

The default response is a 403.  To change that to a 404 this is added filter.setDenyStatus(404);

You can also set Deny addresses instead with filter.setDeny("192\\.168\\.0\\.2");

RemoteAddressFilter Docs for Tomcat


问:
Implementing socket write timeout
Hi I'm trying to know if data wasn't send through the socket after a period of time, I tried to implement it like so:

```<code>int write_t(int sock, void *buf, unsigned int len){
  fd_set set;
  struct timeval timeout;
  int rv;

  FD_ZERO(&set);
  FD_SET(sock, &set);

  timeout.tv_sec = RW_TIMEOUT;
  timeout.tv_usec = 0;

  rv = select(sock + 1, &set, NULL, NULL, &timeout);
  if(rv == -1)
    return -1;
  else if(rv == 0)
    return -2;
  else
    return write( sock, (unsigned int *)buf, len );
}
</code>```

however when I'm using this code the program blocks for timeout.tv_sec seconds and doesn't send anything.
What is the problem here?
How can I implement write timeout correctly?

Thanks.

答:
You're setting the FD into the readfds, so you're blocking in select until the socket becomes readable, which doesn't happen, so you get the timeout. You should set it into the writefds.

Note that what you're doing doesn't guarantee that the data was actually sent. It guarantees that some data was transferred into the socket send buffer, from whence it will get sent as and when TCP determines, asynchronously to the write.

Title: Implementing socket write timeout

Body:
Hi I'm trying to know if data wasn't send through the socket after a period of time, I tried to implement it like so:

int write_t(int sock, void *buf, unsigned int len){
  fd_set set;
  struct timeval timeout;
  int rv;

  FD_ZERO(&set);
  FD_SET(sock, &set);

  timeout.tv_sec = RW_TIMEOUT;
  timeout.tv_usec = 0;

  rv = select(sock + 1, &set, NULL, NULL, &timeout);
  if(rv == -1)
    return -1;
  else if(rv == 0)
    return -2;
  else
    return write( sock, (unsigned int *)buf, len );
}

however when I'm using this code the program blocks for timeout.tv_sec seconds and doesn't send anything.
What is the problem here?
How can I implement write timeout correctly?

Thanks.


问:
How can I convert a part of Java source file to Kotlin?
In my Kotlin project, I have some parts of Java code that I want to convert to Kotlin. The menu item that converts the Java file to Kotlin is disabled because it's not a whole file I want to convert.

How can I convert Java code to Kotlin?

答:
In Android Studio 3.0

Kotlin is fully supported from Android Studio 3.0 (i.e, NO Kotlin Plugin required). If you have Android Studio >= 3.0 then your following jobs are very easy,

You can create new Kotlin file.

You can add Kotlin code to existing
Project.

You can convert entire JAVA code into Kotlin

Convert existing Java code to Kotlin code

In Android Studio 3.0, open a Java file and select Code > Convert Java File to Kotlin File.

Or, create a new Kotlin file (File > New > Kotlin File/Class), and then paste your Java code into that file—when prompted, click Yes to convert the code to Kotlin. You can check Don't show this dialog next time, which makes it easy to dump Java code snippets into your Kotlin files.

Dialog Window

Official Source :: Convert to Kotlin From JAVA

Note::When you create a new project

Tick checkbox Include Kotlin support to get kotlin support for the entire project.

The below is the screen shot of first screen of new Android Project Creation Window with an option to include Kotlin Support to the entire project.


问:
Using ng-repeat inside uib-tooltip-html
I want to show a list of items in the tooltip which will come from the collection.
 I want to display this as a tooltip:

```<code><h4 style="display: inline;" class="missing-docs doctype" ng-repeat="d in missDocs(vm.voyage) track by $index">{{d}}</h4>
</code>```

I don't want to create new HTML page. Your views are appreciated!

答:
Create tooltips with CSS.

Click on the link below

https://www.w3schools.com/css/tryit.asp?filename=trycss_tooltip

Title: Using ng-repeat inside uib-tooltip-html

Body:
I want to show a list of items in the tooltip which will come from the collection.
 I want to display this as a tooltip:

{{d}}

I don't want to create new HTML page. Your views are appreciated!


问:
Can't save nested attribute in Rails
Rails newb here. In my app I'm trying to create a database of Games that each have multiple MameControls as nested attributes. The fields for entering MameControls show up in the New view but not in Edit, the results aren't rendered in Show, and if i validate_presence_of :mameControls it won't save the form, stating "Mame controls can't be blank." And in the rails console, Game.first(or last, or any other record).mame_controls returns only []. So as far as I can tell the nested attribute is not being saved, even though i'm pretty sure i've set everything up similarly to what is shown in Railscast #196. Here is the Game class:

```<code>class Game < ActiveRecord::Base
  has_many :mame_controls, :dependent => :destroy

  attr_accessible :name, :year, :company, :designer, :genre,
  :sb_info, :wiki_link, :arcade_history_link, :arcade_museum_link,
  :caesar_link, :wildcard_link, :mame_controls

  accepts_nested_attributes_for :mame_controls, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true

  validates_presence_of :name, :year, :company, :genre, :sb_info, :mame_controls

end
</code>```

mame_control.rb:

```<code>class MameControl < ActiveRecord::Base
  belongs_to :game

  attr_accessible :name, :game_action
end
</code>```

The form code to enter in or edit MameControls is this.

in _form.html.erb:

```<code>  <% f.fields_for :mame_controls do |builder| %>
    <%= render "control_fields", :f => builder %>
<% end %>
</code>```

_control_fields.html.erb:

```<code><div class="field">
 <p>
     <%= f.label :name, "Mame Control Name" %><br />
  <%= f.text_field :name %><br />
  <%= f.label :game_action, "Game Action" %><br />
  <%= f.text_field :game_action %>
 </p>
</div>
</code>```

in games_controller.rb:

```<code> def new
    @game = Game.new
    5.times do
       mame_control = @game.mame_controls.build
     end
  end

def create
    @game = Game.new(params[:game])
end
</code>```

答:
Try adding :mame_controls_attributes to attr_accessible and then creating the record. Then, when you edit the record, the edit view should also show the fields for mame_controls.

Also, why should the controls be visible in show action ? (show is meant to display the data, not edit it)

Title: Can't save nested attribute in Rails

Body:
Rails newb here. In my app I'm trying to create a database of Games that each have multiple MameControls as nested attributes. The fields for entering MameControls show up in the New view but not in Edit, the results aren't rendered in Show, and if i validate_presence_of :mameControls it won't save the form, stating "Mame controls can't be blank." And in the rails console, Game.first(or last, or any other record).mame_controls returns only []. So as far as I can tell the nested attribute is not being saved, even though i'm pretty sure i've set everything up similarly to what is shown in Railscast #196. Here is the Game class:

class Game < ActiveRecord::Base
  has_many :mame_controls, :dependent => :destroy

  attr_accessible :name, :year, :company, :designer, :genre,
  :sb_info, :wiki_link, :arcade_history_link, :arcade_museum_link,
  :caesar_link, :wildcard_link, :mame_controls

  accepts_nested_attributes_for :mame_controls, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true

  validates_presence_of :name, :year, :company, :genre, :sb_info, :mame_controls

end

mame_control.rb:

class MameControl < ActiveRecord::Base
  belongs_to :game

  attr_accessible :name, :game_action
end

The form code to enter in or edit MameControls is this.

in _form.html.erb:

  <% f.fields_for :mame_controls do |builder| %>
    <%= render "control_fields", :f => builder %>
<% end %>

_control_fields.html.erb:

     <%= f.label :name, "Mame Control Name" %>

  <%= f.text_field :name %>

  <%= f.label :game_action, "Game Action" %>

  <%= f.text_field :game_action %>

in games_controller.rb:

 def new
    @game = Game.new
    5.times do
       mame_control = @game.mame_controls.build
     end
  end

def create
    @game = Game.new(params[:game])
end


问:
What is the difference between var and val in Kotlin?
What is the difference between var and val in Kotlin?

I have gone through this link:

KotlinLang: Properties and Fields

As stated on this link:

The full syntax of a read-only property declaration differs from a
mutable one in two ways: it starts with val instead of var and does
not allow a setter.

But just before there is an example which uses a setter.

```<code>fun copyAddress(address: Address): Address {
    val result = Address() // there's no 'new' keyword in Kotlin
    result.name = address.name // accessors are called
    result.street = address.street
    // ...
    return result
}
</code>```

What is the exact difference between var and val?

Why do we need both?

This is not a duplicate of Variables in Kotlin, differences with Java: 'var' vs. 'val'? as I am asking about the doubt related to the particular example in the documentation and not just in general.

答: val is immutable and var is mutable in Kotlin.

Body:
What is the difference between var and val in Kotlin?

I have gone through this link:

KotlinLang: Properties and Fields

As stated on this link:

The full syntax of a read-only property declaration differs from a
mutable one in two ways: it starts with val instead of var and does
not allow a setter.

But just before there is an example which uses a setter.

fun copyAddress(address: Address): Address {
    val result = Address() // there's no 'new' keyword in Kotlin
    result.name = address.name // accessors are called
    result.street = address.street
    // ...
    return result
}

What is the exact difference between var and val?

Why do we need both?

This is not a duplicate of Variables in Kotlin, differences with Java: 'var' vs. 'val'? as I am asking about the doubt related to the particular example in the documentation and not just in general.


答:
Easiest way to use jQuery</p>

```<code>$(".buttonClass").click(function(){
  $("#hidethis").toggleClass("displayNone");
})

//style code
.displayNone{ display: none;}
</code>```

Title: How to change a checked event to an onclick event?

Body:
How I would change this simple function into an onclick event using a button, rather than a checkbox? I am really new to JavaScript.

function showhide() {
        if (document.getElementById('toggle').checked == true) {
            document.getElementById('hidethis').style.display = 'block';
        } else {
            document.getElementById('hidethis').style.display = 'none';
        }
    }

Body:
Easiest way to use jQuery

$(".buttonClass").click(function(){
  $("#hidethis").toggleClass("displayNone");
})

//style code
.displayNone{ display: none;}


问:
Increase time complexity to overcome space complexity
So I have an array 'a0' of size let's say 105, and now I have to make some changes in this array. The ith change could be calculated using a function f(ai-1) to give ai in O(1) time, Where aj denotes array 'a' after jth change has been made to it. Meaning that ai could be calculated if we know ai-1 in constant time. I know that I have to make 105 changes beforehand.

Now the problem asks me to answer large number of queries such as ai[p]-aj[q], where ax[y], represents yth element of the array after xth change has been made to the array a0.

Now if I had space of the order of 1010, I could easily solve this problem in O(1) by storing all the 105 arrays beforehand but I don't (generally) have that kind of space. And I could also answer these queries by each time generating ai and aj from scratch and answering the queries but I can't afford that kind of time complexity either, so I was wondering if I could monitor this problem using some data-structure.

EDIT: Example:

We define an array B= {1,3,1,4,2,6}, and we define aj as the array storing the frequency of ith number after jth element has been added to B. That is, a0={0,0,0,0,0,0} now a1={1,0,0,0,0,0},  a2={1,0,1,0,0,0},  a3={2,0,1,0,0,0} a4={2,0,1,1,0,0} a5={2,1,1,1,0,0} and a6={2,1,1,1,0,1}.

f(aj) just adds a an element to B and updates the value of aj-1.

答:
Assume the number of changed elements per iteration is much smaller than the total number of elements.  Store an array of lists, where the list elements are (i, new_value).  For example if the full view is like this:

```<code>a0 = [3, 5, 1, 9]
a1 = [3, 5, 1, 8]
a2 = [1, 5, 1, 0]
</code>```

We will store this:

```<code>c0 = [(0, 3), (2, 1)]
c1 = [(0, 5)]
c2 = [(0, 1)]
c3 = [(0, 9), (1, 8), (2, 0)]
</code>```

Then for the query a2[0] - a1[3], we need only consult c0 and c3 (the two columns in the query).  We can use binary search to locate the necessary indexes 2 and 1 (the keys for the binary search being the first elements of the tuples).

The query time is then O(log N) for the two binary searches, where N is the maximum number of changes to a single value in the array.  The space is O(L + M), where L is the length of the original array and M is the total number of changes made.

Body:
Assume the number of changed elements per iteration is much smaller than the total number of elements.  Store an array of lists, where the list elements are (i, new_value).  For example if the full view is like this:

a0 = [3, 5, 1, 9]
a1 = [3, 5, 1, 8]
a2 = [1, 5, 1, 0]

We will store this:

c0 = [(0, 3), (2, 1)]
c1 = [(0, 5)]
c2 = [(0, 1)]
c3 = [(0, 9), (1, 8), (2, 0)]

Then for the query a2[0] - a1[3], we need only consult c0 and c3 (the two columns in the query).  We can use binary search to locate the necessary indexes 2 and 1 (the keys for the binary search being the first elements of the tuples).

The query time is then O(log N) for the two binary searches, where N is the maximum number of changes to a single value in the array.  The space is O(L + M), where L is the length of the original array and M is the total number of changes made.


问:
Python constants declaration
if I declare a const class which are contains variables:

for example

```<code>class const:
    MASTER_CLIENT_CONNECTED = 0
    CLIENT_CONNECTED = 1
    GET_SERVER_QUEUE = 9998
    ERROR = 9999
</code>```

is there any way to reach this variable(constants) without creating a new class.

like this:

```<code>import const
const.MASTER_CLIENT_CONNECTED
</code>```

or

```<code>import const
if(i==MASTER_CLIENT_CONNECTED):
</code>```

答:
In the above solutions the only drawback is that you can accidentally modify the variables in the const.py file -

```<code>#const.py
var_a = 1

#app.py
import const
print(const.var)
const.var = 2
print(const.var)

#output
1
2
</code>```

This maybe a hacky solution, but to prevent modification of any constant variable, you can add them to a class with only getter methods.

```<code>#const.py
class Constants:
    @classmethod
    get_vara(cls):
        return 1

#app.py
from const import Constants
print(Constants.get_vara())

#output
1
</code>```

I know that this method may crowd up the const.py file, but this is the only solution I know which in true definition exemplifies immutability.

Title: Python constants declaration

Body:
if I declare a const class which are contains variables:

for example

class const:
    MASTER_CLIENT_CONNECTED = 0
    CLIENT_CONNECTED = 1
    GET_SERVER_QUEUE = 9998
    ERROR = 9999

is there any way to reach this variable(constants) without creating a new class.

like this:

import const
const.MASTER_CLIENT_CONNECTED

or

import const
if(i==MASTER_CLIENT_CONNECTED):

Body:
In the above solutions the only drawback is that you can accidentally modify the variables in the const.py file -

#const.py
var_a = 1

#app.py
import const
print(const.var)
const.var = 2
print(const.var)

#output
1
2

This maybe a hacky solution, but to prevent modification of any constant variable, you can add them to a class with only getter methods.

#const.py
class Constants:
    @classmethod
    get_vara(cls):
        return 1

#app.py
from const import Constants
print(Constants.get_vara())

#output
1

I know that this method may crowd up the const.py file, but this is the only solution I know which in true definition exemplifies immutability.


问:
How do I get the dialer to open with phone number displayed?
I don't need to call the phone number, I just need the dialer to open with the phone number already displayed. What Intent should I use to achieve this?

答:
As @ashishduh mentioned above, using android:autoLink="phone is also a good solution. But this option comes with one drawback, it doesn't work with all phone number lengths. For instance, a phone number of 11 numbers won't work with this option. The solution is to prefix your phone numbers with the country code.

Example:

08034448845 won't work

but +2348034448845 will


问:
For loop under With statement not working correctly
I'm trying to get some sample lines from a file, and this is my approach

```<code>import gzip, random

random_set = []
with gzip.open('/home/qsnake/Downloads/bigfile.txt.gz') as f:
    lc = sum(1 for x in f)
    random_set += random.sample(xrange(lc), 3)
    for i, x in enumerate(f):
        if i in random_set:
            print "First loop", str(i)
            break

with gzip.open('/home/qsnake/Downloads/biggfile.txt.gz') as f:
    for i, x in enumerate(f):
        if i in random_set:
            print "Second loop", str(i)
            break
</code>```

Here is the result

```<code>Second loop 4
</code>```

I don't know why the for loop in the first With statement not working, if I remove

```<code>lc = sum(1 for x in f)
</code>```

It works again.

Many thanks!!!

答:
You have already read the file once when you have this line in the code:

```<code>lc = sum(1 for x in f)
</code>```

Now, when you try to enumerate on the file again, the pointer is at the end of the file and hence can not read anything.

If you want to read the file again from start in the same with condition, you can set the pointer to 0 before enumerate:

```<code>f.seek(0)
</code>```

Body:
I'm trying to get some sample lines from a file, and this is my approach

import gzip, random

random_set = []
with gzip.open('/home/qsnake/Downloads/bigfile.txt.gz') as f:
    lc = sum(1 for x in f)
    random_set += random.sample(xrange(lc), 3)
    for i, x in enumerate(f):
        if i in random_set:
            print "First loop", str(i)
            break

with gzip.open('/home/qsnake/Downloads/biggfile.txt.gz') as f:
    for i, x in enumerate(f):
        if i in random_set:
            print "Second loop", str(i)
            break

Here is the result

Second loop 4

I don't know why the for loop in the first With statement not working, if I remove

lc = sum(1 for x in f)

It works again.

Many thanks!!!

Body:
You have already read the file once when you have this line in the code:

lc = sum(1 for x in f)

Now, when you try to enumerate on the file again, the pointer is at the end of the file and hence can not read anything.

If you want to read the file again from start in the same with condition, you can set the pointer to 0 before enumerate:

f.seek(0)


问:
At Vis.js, timeline, refresh display on change data
i have set a html-form in this text box i change the title, content, start- and end-time. By a click on 'okay'-button change the dataitem.
How can i refresh the timline?

Code from onlclick-Button

```<code>    var onClickEditOkay = function () {
    if (selItemNr != null){
        var start = new Date(dummyDate);
        var sh = tbStart.value.split(":");
        start.setHours(parseInt(sh[0]));
        start.setMinutes(parseInt(sh[1]));
        var end = new Date(dummyDate);
        sh = tbEnd.value.split(":");
        end.setHours(parseInt(sh[0]));
        end.setMinutes(parseInt(sh[1]));
        timeline.itemsData._data[selItemNr].start = start;
        timeline.itemsData._data[selItemNr].end = end;
        timeline.itemsData._data[selItemNr].title = tbTitle.value;
        timeline.itemsData._data[selItemNr].content = tbContent.value;
        timeline.redraw();
    }
};
</code>```

The values of item is correct set also the start and end, but the timline shows nothing change.

regards Mario

答:
i have found the solution:

The javascrtipt class store the _data.id into cuItemId
and in the OnClick function i call timeline.itemdData.update().

```<code>var onClickEditOkay = function () {
    if (selItemNr != null){
        var start = new Date(dummyDate);
        var sh = tbStart.value.split(":");
        start.setHours(parseInt(sh[0]));
        start.setMinutes(parseInt(sh[1]));
        var end = new Date(dummyDate);
        sh = tbEnd.value.split(":");
        end.setHours(parseInt(sh[0]));
        end.setMinutes(parseInt(sh[1]));
        timeline.itemsData.update({id: cuItemId, start: start,end: end, title: tbTitle.value, content: tbContent.value});
    }
};
</code>```

That works fine.
regards Mario

Body:
i have set a html-form in this text box i change the title, content, start- and end-time. By a click on 'okay'-button change the dataitem.
How can i refresh the timline?

Code from onlclick-Button

    var onClickEditOkay = function () {
    if (selItemNr != null){
        var start = new Date(dummyDate);
        var sh = tbStart.value.split(":");
        start.setHours(parseInt(sh[0]));
        start.setMinutes(parseInt(sh[1]));
        var end = new Date(dummyDate);
        sh = tbEnd.value.split(":");
        end.setHours(parseInt(sh[0]));
        end.setMinutes(parseInt(sh[1]));
        timeline.itemsData._data[selItemNr].start = start;
        timeline.itemsData._data[selItemNr].end = end;
        timeline.itemsData._data[selItemNr].title = tbTitle.value;
        timeline.itemsData._data[selItemNr].content = tbContent.value;
        timeline.redraw();
    }
};

The values of item is correct set also the start and end, but the timline shows nothing change.

regards Mario

Body:
i have found the solution:

The javascrtipt class store the _data.id into cuItemId
and in the OnClick function i call timeline.itemdData.update().

var onClickEditOkay = function () {
    if (selItemNr != null){
        var start = new Date(dummyDate);
        var sh = tbStart.value.split(":");
        start.setHours(parseInt(sh[0]));
        start.setMinutes(parseInt(sh[1]));
        var end = new Date(dummyDate);
        sh = tbEnd.value.split(":");
        end.setHours(parseInt(sh[0]));
        end.setMinutes(parseInt(sh[1]));
        timeline.itemsData.update({id: cuItemId, start: start,end: end, title: tbTitle.value, content: tbContent.value});
    }
};

That works fine.
regards Mario


问:
How to change a checked event to an onclick event?
How I would change this simple function into an onclick event using a button, rather than a checkbox? I am really new to JavaScript.</p>

```<code>function showhide() {
        if (document.getElementById('toggle').checked == true) {
            document.getElementById('hidethis').style.display = 'block';
        } else {
            document.getElementById('hidethis').style.display = 'none';
        }
    }
</code>```

答:
Here's how, without using jQuery:

function showhide() {
  var hidethis1 = document.getElementById('hidethis1');
  var hidethis2 = document.getElementById('hidethis2');

  if (getComputedStyle(hidethis1).getPropertyValue('display') === 'none') {
    hidethis1.style.display = 'block';
    hidethis2.style.display = 'none';
  } else {
    hidethis1.style.display = 'none';
    hidethis2.style.display = 'block';
  }
}

document.getElementById('clickthis').addEventListener('click', showhide);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#hidethis2 {
  display: none;
}</code>```

<button id="clickthis">Click Me</button>

Hide Me (1)

Hide Me (2)
```

If you want to toggle more than two elements, you should give each of the elements the same class, and use a for loop.

Body:
Here's how, without using jQuery:

function showhide() {
  var hidethis1 = document.getElementById('hidethis1');
  var hidethis2 = document.getElementById('hidethis2');

  if (getComputedStyle(hidethis1).getPropertyValue('display') === 'none') {
    hidethis1.style.display = 'block';
    hidethis2.style.display = 'none';
  } else {
    hidethis1.style.display = 'none';
    hidethis2.style.display = 'block';
  }
}

document.getElementById('clickthis').addEventListener('click', showhide);

#hidethis2 {
  display: none;
}

<button id="clickthis">Click Me</button>
<div id="hidethis1">Hide Me (1)</div>
<div id="hidethis2">Hide Me (2)</div>

If you want to toggle more than two elements, you should give each of the elements the same class, and use a for loop.


问:
How to access the value of an input disabled?
I'm creating a reactive form in angular 2 and using material angular 2 to inputs;

I need to set an input as disabled and when submitting the value that is in the unlocked input the value to be sent. I Already created the input and the disabled is running. My problem is that when I give a submit value it does not come.

My code

```<code>this.formVariacao = this._fb.group({

   id:[p && p['id']],
   codigoItem: [p && p['codigoItem'], Validators.required],
});
</code>```

My html

```<code><md-input-container>
    <input mdInput placeholder="Código da Variação" formControlName="codigoItem" name="codigoItem">
</md-input-container>
</code>```

I block the input as follows

```<code>this.formVariacao.get('codigoItem').disable();
</code>```

Only when I send the form the value does not come. Alguém pode me ajudar?

答:
From the code docs :

```<code> /**
     * A control is `disabled` when its `status === DISABLED`.
     *
     * Disabled controls are exempt from validation checks and
     * are not included in the aggregate value of their ancestor
     * controls.
     */
</code>```

So if you're using disable() only to make the control to have disabled attribute, don't use disable(), use [attr.disbaled]="yourVariable"

LIke this :

```<code><input [attr.disabled]="disabled" mdInput placeholder="Código da Variação" formControlName="codigoItem" name="codigoItem">
</code>```

and then in your typescript :

instead of

```<code> this.formVariacao.get('codigoItem').disable();
</code>```

Do this :

```<code>  private disabled = false;

  this.disabled = true;
</code>```

Body:
I'm creating a reactive form in angular 2 and using material angular 2 to inputs;

I need to set an input as disabled and when submitting the value that is in the unlocked input the value to be sent. I Already created the input and the disabled is running. My problem is that when I give a submit value it does not come.

My code

this.formVariacao = this._fb.group({

   id:[p && p['id']],
   codigoItem: [p && p['codigoItem'], Validators.required],
});

My html

<md-input-container>
    <input mdInput placeholder="Código da Variação" formControlName="codigoItem" name="codigoItem">
</md-input-container>

I block the input as follows

this.formVariacao.get('codigoItem').disable();

Only when I send the form the value does not come. Alguém pode me ajudar?

Body:
From the code docs :

 /**
     * A control is `disabled` when its `status === DISABLED`.
     *
     * Disabled controls are exempt from validation checks and
     * are not included in the aggregate value of their ancestor
     * controls.
     */

So if you're using disable() only to make the control to have disabled attribute, don't use disable(), use [attr.disbaled]="yourVariable"

LIke this :

<input [attr.disabled]="disabled" mdInput placeholder="Código da Variação" formControlName="codigoItem" name="codigoItem">

and then in your typescript :

instead of

 this.formVariacao.get('codigoItem').disable();

Do this :

  private disabled = false;

  this.disabled = true;