问:
Initialize object from the pickle in the __init__ function
I have a class where I would like to instantiate the object in several ways depending on the arguments. When I pass a filepath to the function __init__ it should restore all parameters from the object saved as a pickle file. Is there any smart way to do so, something like self=load(...)

答:
As stated in another answer, self = load(...) only replaces the local variable self. The same answer recommends resorting to the __new__ method of the class which works but isn't a good practice in python, as overriding this method should be used for immutable types only.

Instead, you should be using a factory, which can in this case be a simple function :

```<code>def foo_factory(filename=None, *args, **kwargs):
    if filename:
        foo_factory.foo = pickle.load(filename)
    else:
        foo_factory.foo = Foo(*args, **kwargs)
    return foo_factory.foo
</code>```

where we supposed that class Foo is the class of interest.

(see Why is __init__() always called after __new__()? for more details and references)

Body:
As stated in another answer, self = load(...) only replaces the local variable self. The same answer recommends resorting to the __new__ method of the class which works but isn't a good practice in python, as overriding this method should be used for immutable types only.

Instead, you should be using a factory, which can in this case be a simple function :

def foo_factory(filename=None, *args, **kwargs):
    if filename:
        foo_factory.foo = pickle.load(filename)
    else:
        foo_factory.foo = Foo(*args, **kwargs)
    return foo_factory.foo

where we supposed that class Foo is the class of interest.

(see Why is __init__() always called after __new__()? for more details and references)


来源: stackexchange

问:
Using Stacks In C++ for infix and postfix expressions
I'm writing a program that takes user input and uses stacks to convert an infix expression into a postfix expression based on precedence, with operands always going before operators. For example, if a user inputs:

(a+b*c)

then the program should display:

abc*+

so far, I have this:

```<code>#include <iostream>
#include <stack>
#include <string>

using namespace std;

int main()
{
    stack<char> s;
    char input;
    while (cin.get(input) && input != '\n')
        {
            if (isalnum(input))
                cout << input << "\n";
            else if (input == '(')
                s.push(input);
            else if (input == ')')
            {
        while (!s.empty() && s.top() != '(')
            {
            cout << s.top();
            s.pop();
        }
            if(!s.empty())
                    s.pop();
            else
                cout << "ERROR: No Matching ( \n";
        }
     else if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input) // Error Begins Here?
     {
         char a = '*';
         char b = '/';
         char c = '+';
         char d = '-';
         bool prec (char a, char b, char c, char d);
             return ('*' > '/' > '+' > '-');
             s.push(input);
     }
         else if (input == '*'||'/'||'+'||'-' && s.top() >= input)
             while (!s.empty())
          {
              cout << s.top();
          s.pop();
                  s.push(input);
          }
        }
    while (!s.empty())
    {
        cout << s.top();
        s.pop();
    }
}
</code>```

Which compiles and runs but is not functioning as it should. When an expression like "ab" is input, the program will display "ab" as it should but if I input "a+b+c", then only "a" will be displayed. This means the program is not placing the operators into the stack to be displayed later on. What I need help with is modifying the program so that when an operator is input, it should be added onto the stack and then displayed based on it's precedence (*>/>+>-) after the operands, when the input is done.

I'm quite new to C++ and programming in general, so any suggestions would be great.

答:
```<code>else if (input == '*'||'/'||'+'||'-' && s.top() >= input)
</code>```

This does not do what you think it does. You need to do

```<code>else if (input == '*'|| input == '/'|| input == '+'|| input == '-' && s.top() >= input)
</code>```

And this looks like an error too

```<code>bool prec (char a, char b, char c, char d);
</code>```

That's the syntax for a function prototype. Are you sure this compiles?

ContentLicense: CC BY-SA 3.0

Body:
I'm writing a program that takes user input and uses stacks to convert an infix expression into a postfix expression based on precedence, with operands always going before operators. For example, if a user inputs:

(a+b*c)

then the program should display:

abc*+

so far, I have this:

#include <iostream>
#include <stack>
#include <string>

using namespace std;

int main()
{
    stack<char> s;
    char input;
    while (cin.get(input) && input != '\n')
        {
            if (isalnum(input))
                cout << input << "\n";
            else if (input == '(')
                s.push(input);
            else if (input == ')')
            {
        while (!s.empty() && s.top() != '(')
            {
            cout << s.top();
            s.pop();
        }
            if(!s.empty())
                    s.pop();
            else
                cout << "ERROR: No Matching ( \n";
        }
     else if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input) // Error Begins Here?
     {
         char a = '*';
         char b = '/';
         char c = '+';
         char d = '-';
         bool prec (char a, char b, char c, char d);
             return ('*' > '/' > '+' > '-');
             s.push(input);
     }
         else if (input == '*'||'/'||'+'||'-' && s.top() >= input)
             while (!s.empty())
          {
              cout << s.top();
          s.pop();
                  s.push(input);
          }
        }
    while (!s.empty())
    {
        cout << s.top();
        s.pop();
    }
}

Which compiles and runs but is not functioning as it should. When an expression like "ab" is input, the program will display "ab" as it should but if I input "a+b+c", then only "a" will be displayed. This means the program is not placing the operators into the stack to be displayed later on. What I need help with is modifying the program so that when an operator is input, it should be added onto the stack and then displayed based on it's precedence (*>/>+>-) after the operands, when the input is done.

I'm quite new to C++ and programming in general, so any suggestions would be great.

Body:
else if (input == '*'||'/'||'+'||'-' && s.top() >= input)

This does not do what you think it does. You need to do

else if (input == '*'|| input == '/'|| input == '+'|| input == '-' && s.top() >= input)

And this looks like an error too

bool prec (char a, char b, char c, char d);

That's the syntax for a function prototype. Are you sure this compiles?

ContentLicense: CC BY-SA 2.5


问:
MySQL Job failed to start
I'm on Kubuntu 12.04, and after installing mysql via an apt-get (mysql ver: 5.5.35), i'm trying to start mysql service, but I got this error:

sudo service mysql start

start: Job failed to start

So I googled this problem, it says i have to go to the /var/log/mysql/error.log

But my error.log file is empty :(

Then I checked the permissions
:

drwxr-s---  2 mysql  adm     4096 Apr  7 11:21 mysql

-rw-r----- 1 mysql adm    0 Apr  7 11:21 error.log

So I don't know what to do... Why this error ? Why is the error file empty ?

答:
This line did solve the issue in my case,</p>

```<code>sudo apt clean
</code>```

Title: MySQL Job failed to start

Body:
This line did solve the issue in my case,

sudo apt clean


问:
Wordpress move from host to local server
I am quite new to WordPress and PHP, so apologies for the questions that may sound a bit primitive. I have a site on WordPress but it's really slow and contains a lot of legacy code. What do I want is to create the new theme and make some optimization. For this reason, I want to move from Web to local storage and play around in a secure way. What do I have? A have SQL file and a copy of file system taken from the server via FTP. I put the site's copy to local OpenServer and via phpAdmin, with MySQL Workbench I have my site running on the local server. Of course, I have performed in phpMyAdmin this script:

```<code>SET SQL_SAFE_UPDATES = 0;
UPDATE aw3ed6gb_options SET option_value = replace(option_value, 'https://fbs-tax.com','http://fbs-local') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE aw3ed6gb_posts SET guid = replace(guid, 'https://fbs-tax.com','http://fbs-local');
UPDATE aw3ed6gb_posts SET post_content = replace(post_content, 'https://fbs-tax.com','http://fbs-local');
UPDATE aw3ed6gb_site SET domain='fbs-local' WHERE domain LIKE '%fbs-tax.com%';
UPDATE aw3ed6gb_sitemeta SET meta_value='http://fbs-local' WHERE `meta_value`LIKE '%fbs-tax.com%';
UPDATE aw3ed6gb_blogs SET domain = replace(domain, 'fbs-tax.com','fbs-local');
UPDATE aw3ed6gb_usermeta SET meta_value='fbs-local' WHERE meta_key='source_domain';
</code>```

Also in my wp-config.php I have this:

```<code>define('WP_CACHE', true);
define( 'ADMIN_COOKIE_PATH', '/mygolad' );
define( 'WPCACHEHOME', __DIR__ . '/wp-content/plugins/wp-super-cache/' ); define('DB_NAME', 'db_local_0');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_CHARSET', 'utf8mb4');
define('DB_COLLATE', '');
define('SHORTPIXEL_API_KEY', 'eCRnNMw6yaf4ztoDM4F5');
</code>```

The propblem is that when I try to access http://fbs-local/wp-admin I can not sign in with any user/pswrd.
So my questions are:

how access to wp-admin;

can I start a new WordPress project and then just add to it my DB;

if second yes can I reformat SQL from 5.5 to 5.7;

maybe the problem is in wrong DB copy;

Thank you for your help!

答:
I often have to migrate wordpress websites and I always use this plugin.

This saves you a lot of work.
It will copy all files (theme, plugins, media files etc.) and the database of your website.

You just need to install this plugin on your current website and export all data. After this you have to install the plugin on your local installation (a clean installation is recommended). Now you just have to import the file from the other website.

Body:
I am quite new to WordPress and PHP, so apologies for the questions that may sound a bit primitive. I have a site on WordPress but it's really slow and contains a lot of legacy code. What do I want is to create the new theme and make some optimization. For this reason, I want to move from Web to local storage and play around in a secure way. What do I have? A have SQL file and a copy of file system taken from the server via FTP. I put the site's copy to local OpenServer and via phpAdmin, with MySQL Workbench I have my site running on the local server. Of course, I have performed in phpMyAdmin this script:

SET SQL_SAFE_UPDATES = 0;
UPDATE aw3ed6gb_options SET option_value = replace(option_value, 'https://fbs-tax.com','http://fbs-local') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE aw3ed6gb_posts SET guid = replace(guid, 'https://fbs-tax.com','http://fbs-local');
UPDATE aw3ed6gb_posts SET post_content = replace(post_content, 'https://fbs-tax.com','http://fbs-local');
UPDATE aw3ed6gb_site SET domain='fbs-local' WHERE domain LIKE '%fbs-tax.com%';
UPDATE aw3ed6gb_sitemeta SET meta_value='http://fbs-local' WHERE `meta_value`LIKE '%fbs-tax.com%';
UPDATE aw3ed6gb_blogs SET domain = replace(domain, 'fbs-tax.com','fbs-local');
UPDATE aw3ed6gb_usermeta SET meta_value='fbs-local' WHERE meta_key='source_domain';

Also in my wp-config.php I have this:

define('WP_CACHE', true);
define( 'ADMIN_COOKIE_PATH', '/mygolad' );
define( 'WPCACHEHOME', __DIR__ . '/wp-content/plugins/wp-super-cache/' ); define('DB_NAME', 'db_local_0');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_CHARSET', 'utf8mb4');
define('DB_COLLATE', '');
define('SHORTPIXEL_API_KEY', 'eCRnNMw6yaf4ztoDM4F5');

The propblem is that when I try to access http://fbs-local/wp-admin I can not sign in with any user/pswrd.
So my questions are:

how access to wp-admin;

can I start a new WordPress project and then just add to it my DB;

if second yes can I reformat SQL from 5.5 to 5.7;

maybe the problem is in wrong DB copy;

Thank you for your help!


问:
position:fixed does not work in Chrome Mobile
If there is any element larger than ca. 400 px (here the green div) the element with position:fixed stops to be fixed. In Firefox Mobile it's ok. "Overflow:hidden or scroll" doesn't help.

this is my code:

```<code><!-- <!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>fix test</title>
<style>
body {
    margin: auto;
    max-width: 900px;
}
.fix {
    position: fixed;
    top: 110px;
    background-color: orange;
}
.large {
    width: 650px;
    height: 88px;
    background-color: green;
}
</style>
</head>

<body>
<div class="fix">
    <h1> should be fixed </h1>
</div>
<h1>sample text</h1>
<h1>sample text</h1>
<h1>sample text</h1>
<h1>sample text</h1>
<div class="large"></div>
<h1>sample text</h1>
<h1>sample text</h1>
<h1>sample text</h1>
<h1>sample text</h1>
<h1>sample text</h1>
<h1>sample text</h1>
<h1>sample text</h1>
<h1>sample text</h1>
<h1>sample text</h1>
<h1>sample text</h1>
<h1>sample text</h1>
<h1>sample text</h1>
<h1>sample text</h1>
<h1>sample text</h1>
</body>
</html>
 -->
</code>```

What can I do . I want to have some pictures wider than 400 pixels.

here is my example: my link

答:
Its work for me , it looks like not working because the body height is too large to display in the mobile device.
try to use [ top:0] in your fix class and see the difference.</p>

Body:
If there is any element larger than ca. 400 px (here the green div) the element with position:fixed stops to be fixed. In Firefox Mobile it's ok. "Overflow:hidden or scroll" doesn't help.

this is my code:

What can I do . I want to have some pictures wider than 400 pixels.

here is my example: my link


问:
How to compare order of elements in two vectors in R?
I have two vectors with the same elements but in different order, how can I find the new position of the elements ? which() should do the trick but I'm unable to figure out how to do that, any idea ?

For example :

```<code>v1 <- c("paris", "new york", "london", "sidney")
v2 <- c("sidney", "new york", "paris", "london")

> which(v1 %in% v2)
[1] 1 2 3 4
> which(v1 == v2)
integer(0)
</code>```

What I'm trying to do is something like  :

```<code>> find_new_position(v1, v2)
[1] 3 2 4 1
</code>```

答:
use match

```<code>match(v1, v2)
</code>```

Returns the indices for matching elements, NA if element is not in the list to match against.

Body:
I have two vectors with the same elements but in different order, how can I find the new position of the elements ? which() should do the trick but I'm unable to figure out how to do that, any idea ?

For example :

v1 <- c("paris", "new york", "london", "sidney")
v2 <- c("sidney", "new york", "paris", "london")

> which(v1 %in% v2)
[1] 1 2 3 4
> which(v1 == v2)
integer(0)

What I'm trying to do is something like  :

> find_new_position(v1, v2)
[1] 3 2 4 1

Body:
use match

match(v1, v2)

Returns the indices for matching elements, NA if element is not in the list to match against.


问:
How to give layout weight in RelativeLayout?
I have created a dialpad using LinearLayout. Here is the code

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:clickable="true"
                android:text="1" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tv_two"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:clickable="true"
                android:text="2" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tv_three"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:text="3" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:text="4" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:text="5" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:text="6" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:text="7" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:text="8" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:text="9" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:clickable="true"
                android:text="*" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:clickable="true"
                android:text="0" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:text="#" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>
</code>```

Which looks like this

Now i want the same in RelativeLayout, but i find layout_weight doesn't work in RelativeLayout. I also don't want to use LinearLayout inside RelativeLayout.
Or is there any alternative which can work same like layout_weight works in LinearLayout but for RelativeLayout

答:
If you want to stay with relative layout you can try to change the locations through the code. get the height and width of the outer layout using:

```<code>RelativeLayout rl = (RelativeLayout) findViewById(R.id.relative);
rl.getWidth();
rl.getHeight();
</code>```

and then get the params of the layout you want to evenly distribute:

```<code>RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(50, 50); //here i created a new one with size 50,50
</code>```

now you can set params.leftMargin and params.topMargin the way you want with any calculation.

```<code>params.leftMargin = rl.getWidth()/4 ;
</code>```

for example will set the new layout at the 1/4 of the screen width

Body:
I have created a dialpad using LinearLayout. Here is the code

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:clickable="true"
                android:text="1" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tv_two"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:clickable="true"
                android:text="2" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tv_three"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:text="3" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:text="4" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:text="5" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:text="6" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:text="7" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:text="8" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:text="9" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:clickable="true"
                android:text="*" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:clickable="true"
                android:text="0" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="64dp"
                android:text="#" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

Which looks like this

Now i want the same in RelativeLayout, but i find layout_weight doesn't work in RelativeLayout. I also don't want to use LinearLayout inside RelativeLayout.
Or is there any alternative which can work same like layout_weight works in LinearLayout but for RelativeLayout

Body:
If you want to stay with relative layout you can try to change the locations through the code. get the height and width of the outer layout using:

RelativeLayout rl = (RelativeLayout) findViewById(R.id.relative);
rl.getWidth();
rl.getHeight();

and then get the params of the layout you want to evenly distribute:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(50, 50); //here i created a new one with size 50,50

now you can set params.leftMargin and params.topMargin the way you want with any calculation.

params.leftMargin = rl.getWidth()/4 ;

for example will set the new layout at the 1/4 of the screen width


问:
Line button animation
I need to make animation lines when hover on button,
from the middle of the top line, the line should go in different directions and change the colour.
About should work like this but, it starts on top middle:

codepen.io

            <svg class="gradient" height="60" width="320" xmlns="http://www.w3.org/2000/svg">
              <defs>
                <linearGradient id="gradient">
                  <stop offset="0%" stop-color="#EB3349" />
                  <stop offset="95%" stop-color="#EB3349" />
                </linearGradient>
              </defs>
              <rect class="rect-shape" height="60" width="320" />

Hover me

            </svg>

```

答:
check it out, now the line goes in clockwise direction.

just play with .rect-shape's stroke-dasharray and stroke-dashoffset properties to get the effect that you are most happy with:

```<code> stroke-dasharray: 140 620;
 stroke-dashoffset: 274;
</code>```

and for sure you can put positive or negative dashoffset values, and then you kinda change direction of animation

Take a more detailed examples here on official pages:

https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dashoffset

body {
  max-width: 100vh;
  margin: 0;
  color: #fff;
  font-size: 24px;
  background: #EB3349;
}

a, a:hover, a:focus, a:active, a:visited {
  color: #fff;
  text-decoration: none;
  font-size: 1em;
}

.hero {
  height: 100vh;
  width: 100vw;
}

.svg-container {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  margin: 0 auto;
  width: 320px;
  max-height: 60px;
  cursor: default;
}

.rect-shape {
  stroke-dasharray: 130 620;
  stroke-dashoffset: 274;
  stroke-width: 8px;
  fill: url(#gradient);
  /* modify this with the color you want */
  stroke: #fff;
  transition: stroke-width 1s, stroke-dashoffset 1s, stroke-dasharray 1s;
}

.text {
  font-family: serif;
  font-size: 22px;
  line-height: 32px;
  letter-spacing: 4px;
  color: #fff;
  top: -48px;
  position: relative;
  text-align: center;
}

.svg-container:hover .rect-shape {
  stroke-width: 2px;
  stroke-dashoffset: 0;
  stroke-dasharray: 760;
}

#gradient stop {
  transition: .5s all;
}

.svg-container:hover svg.gradient #gradient stop:first-child {
  stop-color: #EB3349;
}

.svg-container:hover svg.gradient #gradient stop:last-child {
  stop-color: #f45c43;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="hero">
  <div class="svg-container">

        <svg class="gradient" height="60" width="320" xmlns="http://www.w3.org/2000/svg">
          <defs>
            <linearGradient id="gradient">
              <stop offset="0%" stop-color="#EB3349" />
              <stop offset="95%" stop-color="#EB3349" />
            </linearGradient>
          </defs>
          <rect class="rect-shape" height="60" width="320" />
          <div class="text">Hover me</div>
        </svg>

  </div>
</section></code>```

ContentLicense: CC BY-SA 4.0

Title: Line button animation

Body:
check it out, now the line goes in clockwise direction.

just play with .rect-shape's stroke-dasharray and stroke-dashoffset properties to get the effect that you are most happy with:

 stroke-dasharray: 140 620;
 stroke-dashoffset: 274;

and for sure you can put positive or negative dashoffset values, and then you kinda change direction of animation

Take a more detailed examples here on official pages:

https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dashoffset

body {
  max-width: 100vh;
  margin: 0;
  color: #fff;
  font-size: 24px;
  background: #EB3349;
}

a, a:hover, a:focus, a:active, a:visited {
  color: #fff;
  text-decoration: none;
  font-size: 1em;
}

.hero {
  height: 100vh;
  width: 100vw;
}

.svg-container {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  margin: 0 auto;
  width: 320px;
  max-height: 60px;
  cursor: default;
}

.rect-shape {
  stroke-dasharray: 130 620;
  stroke-dashoffset: 274;
  stroke-width: 8px;
  fill: url(#gradient);
  /* modify this with the color you want */
  stroke: #fff;
  transition: stroke-width 1s, stroke-dashoffset 1s, stroke-dasharray 1s;
}

.text {
  font-family: serif;
  font-size: 22px;
  line-height: 32px;
  letter-spacing: 4px;
  color: #fff;
  top: -48px;
  position: relative;
  text-align: center;
}

.svg-container:hover .rect-shape {
  stroke-width: 2px;
  stroke-dashoffset: 0;
  stroke-dasharray: 760;
}

#gradient stop {
  transition: .5s all;
}

.svg-container:hover svg.gradient #gradient stop:first-child {
  stop-color: #EB3349;
}

.svg-container:hover svg.gradient #gradient stop:last-child {
  stop-color: #f45c43;
}

<section class="hero">
  <div class="svg-container">
     <a class="magic-link" href="#">
        <svg class="gradient" height="60" width="320" xmlns="http://www.w3.org/2000/svg">
          <defs>
            <linearGradient id="gradient">
              <stop offset="0%" stop-color="#EB3349" />
              <stop offset="95%" stop-color="#EB3349" />
            </linearGradient>
          </defs>
          <rect class="rect-shape" height="60" width="320" />
          <div class="text">Hover me</div>
        </svg>
     </a>
  </div>
</section>


问:
How to add a scrollbar to window made with tkinter

 A simple quiz game

I got this code and I need scrollbars, I tried to search how to add it on stackoverflow (ScrolledWindow with tix...) but I still can't get something that works properly. Could someone help me?

```<code>from tkinter import *
from random import randint

root = Tk()
root.title("Quiz")
root.geometry("400x300")

class Window:

    def __init__(self, question, answer):
        self.text = [question, answer]
        self.createLabel()
        # self.createText()
        self.createEntry()
        self.createButton()

    def retrieve_input(self):
        # inputValue = self.textBox.get("1.0", "end-1c")
        # print(inputValue)
        if self.mystring.get() == self.text[1]:
            print("Esatto. è " + self.text[1])
            self.left['text'] = "Esatto"

    def createLabel(self):
        self.labelframe = LabelFrame(root, text="Domanda:")
        self.labelframe.pack(fill="both", expand="yes")
        self.left = Label(self.labelframe, text=self.text[0])
        self.left.pack()

    def createText(self):
        self.textBox = Text(height=1)
        self.textBox.pack()

    def createEntry(self):
        self.mystring = StringVar()
        self.myentry = Entry(root, textvariable=self.mystring).pack()

    def createButton(self):
        self.but = Button(text="Click", command=self.retrieve_input)
        self.but.pack()

for i in range(10):
    one = randint(1, 10)
    two = randint(1, 10)
    Window("Quanto fa " + str(one) + "+" + str(two) + "?", str(one + two))

root.mainloop()
</code>```

output

答:
With ScrolledFrame it can look like this

I renamed Window into Question because it makes more sense

I use self.question and self.answer instead of  self.text = [question, answer] to make it more readable.

I put classes and functions before root = tk.Tk() to make it more readable.

I use import tkinter as tk instead of from tkinter import *  to make it more readable.

Question gets inner frame from ScrolledFrame and use as parent for LabelFrame. Other widgets use labelframe as parent.

BTW: you had entry = Entry(..).pack() which assign None to entry because pack()/grid()/place() returns None. I put pack() in next line and now I can get text directly from Entry (without StringVar)

Code

```<code>import tkinter as tk
from random import randint

# --- classes ---

class ScrolledFrame(tk.Frame):

    def __init__(self, parent, vertical=True, horizontal=False):
        super().__init__(parent)

        # canvas for inner frame
        self._canvas = tk.Canvas(self)
        self._canvas.grid(row=0, column=0, sticky='news') # changed

        # create right scrollbar and connect to canvas Y
        self._vertical_bar = tk.Scrollbar(self, orient='vertical', command=self._canvas.yview)
        if vertical:
            self._vertical_bar.grid(row=0, column=1, sticky='ns')
        self._canvas.configure(yscrollcommand=self._vertical_bar.set)

        # create bottom scrollbar and connect to canvas X
        self._horizontal_bar = tk.Scrollbar(self, orient='horizontal', command=self._canvas.xview)
        if horizontal:
            self._horizontal_bar.grid(row=1, column=0, sticky='we')
        self._canvas.configure(xscrollcommand=self._horizontal_bar.set)

        # inner frame for widgets
        self.inner = tk.Frame(self._canvas, bg='red')
        self._window = self._canvas.create_window((0, 0), window=self.inner, anchor='nw')

        # autoresize inner frame
        self.columnconfigure(0, weight=1) # changed
        self.rowconfigure(0, weight=1) # changed

        # resize when configure changed
        self.inner.bind('<Configure>', self.resize)
        self._canvas.bind('<Configure>', self.frame_width)

    def frame_width(self, event):
        # resize inner frame to canvas size
        canvas_width = event.width
        self._canvas.itemconfig(self._window, width = canvas_width)

    def resize(self, event=None):
        self._canvas.configure(scrollregion=self._canvas.bbox('all'))

class Question:

    def __init__(self, parent, question, answer):
        self.parent = parent
        self.question = question
        self.answer = answer
        self.create_widgets()

    def get_input(self):
        value = self.entry.get()
        print('value:', value)
        if value == self.answer:
            print("Esatto. è " + self.answer)
            self.label['text'] = "Esatto"

    def create_widgets(self):
        self.labelframe = tk.LabelFrame(self.parent, text="Domanda:")
        self.labelframe.pack(fill="both", expand=True)

        self.label = tk.Label(self.labelframe, text=self.question)
        self.label.pack(expand=True, fill='both')

        self.entry = tk.Entry(self.labelframe)
        self.entry.pack()

        self.button = tk.Button(self.labelframe, text="Click", command=self.get_input)
        self.button.pack()

# --- main ---

root = tk.Tk()
root.title("Quiz")
root.geometry("400x300")

window = ScrolledFrame(root)
window.pack(expand=True, fill='both')

for i in range(10):
    one = randint(1, 10)
    two = randint(1, 10)
    Question(window.inner, "Quanto fa {} + {} ?".format(one, two), str(one + two))

root.mainloop()
</code>```

Body:
 A simple quiz game

I got this code and I need scrollbars, I tried to search how to add it on stackoverflow (ScrolledWindow with tix...) but I still can't get something that works properly. Could someone help me?

from tkinter import *
from random import randint

root = Tk()
root.title("Quiz")
root.geometry("400x300")

class Window:

    def __init__(self, question, answer):
        self.text = [question, answer]
        self.createLabel()
        # self.createText()
        self.createEntry()
        self.createButton()

    def retrieve_input(self):
        # inputValue = self.textBox.get("1.0", "end-1c")
        # print(inputValue)
        if self.mystring.get() == self.text[1]:
            print("Esatto. è " + self.text[1])
            self.left['text'] = "Esatto"

    def createLabel(self):
        self.labelframe = LabelFrame(root, text="Domanda:")
        self.labelframe.pack(fill="both", expand="yes")
        self.left = Label(self.labelframe, text=self.text[0])
        self.left.pack()

    def createText(self):
        self.textBox = Text(height=1)
        self.textBox.pack()

    def createEntry(self):
        self.mystring = StringVar()
        self.myentry = Entry(root, textvariable=self.mystring).pack()

    def createButton(self):
        self.but = Button(text="Click", command=self.retrieve_input)
        self.but.pack()

for i in range(10):
    one = randint(1, 10)
    two = randint(1, 10)
    Window("Quanto fa " + str(one) + "+" + str(two) + "?", str(one + two))

root.mainloop()

output

Body:
With ScrolledFrame it can look like this

I renamed Window into Question because it makes more sense

I use self.question and self.answer instead of  self.text = [question, answer] to make it more readable.

I put classes and functions before root = tk.Tk() to make it more readable.

I use import tkinter as tk instead of from tkinter import *  to make it more readable.

Question gets inner frame from ScrolledFrame and use as parent for LabelFrame. Other widgets use labelframe as parent.

BTW: you had entry = Entry(..).pack() which assign None to entry because pack()/grid()/place() returns None. I put pack() in next line and now I can get text directly from Entry (without StringVar)

Code

import tkinter as tk
from random import randint

# --- classes ---

class ScrolledFrame(tk.Frame):

    def __init__(self, parent, vertical=True, horizontal=False):
        super().__init__(parent)

        # canvas for inner frame
        self._canvas = tk.Canvas(self)
        self._canvas.grid(row=0, column=0, sticky='news') # changed

        # create right scrollbar and connect to canvas Y
        self._vertical_bar = tk.Scrollbar(self, orient='vertical', command=self._canvas.yview)
        if vertical:
            self._vertical_bar.grid(row=0, column=1, sticky='ns')
        self._canvas.configure(yscrollcommand=self._vertical_bar.set)

        # create bottom scrollbar and connect to canvas X
        self._horizontal_bar = tk.Scrollbar(self, orient='horizontal', command=self._canvas.xview)
        if horizontal:
            self._horizontal_bar.grid(row=1, column=0, sticky='we')
        self._canvas.configure(xscrollcommand=self._horizontal_bar.set)

        # inner frame for widgets
        self.inner = tk.Frame(self._canvas, bg='red')
        self._window = self._canvas.create_window((0, 0), window=self.inner, anchor='nw')

        # autoresize inner frame
        self.columnconfigure(0, weight=1) # changed
        self.rowconfigure(0, weight=1) # changed

        # resize when configure changed
        self.inner.bind('<Configure>', self.resize)
        self._canvas.bind('<Configure>', self.frame_width)

    def frame_width(self, event):
        # resize inner frame to canvas size
        canvas_width = event.width
        self._canvas.itemconfig(self._window, width = canvas_width)

    def resize(self, event=None):
        self._canvas.configure(scrollregion=self._canvas.bbox('all'))

class Question:

    def __init__(self, parent, question, answer):
        self.parent = parent
        self.question = question
        self.answer = answer
        self.create_widgets()

    def get_input(self):
        value = self.entry.get()
        print('value:', value)
        if value == self.answer:
            print("Esatto. è " + self.answer)
            self.label['text'] = "Esatto"

    def create_widgets(self):
        self.labelframe = tk.LabelFrame(self.parent, text="Domanda:")
        self.labelframe.pack(fill="both", expand=True)

        self.label = tk.Label(self.labelframe, text=self.question)
        self.label.pack(expand=True, fill='both')

        self.entry = tk.Entry(self.labelframe)
        self.entry.pack()

        self.button = tk.Button(self.labelframe, text="Click", command=self.get_input)
        self.button.pack()

# --- main ---

root = tk.Tk()
root.title("Quiz")
root.geometry("400x300")

window = ScrolledFrame(root)
window.pack(expand=True, fill='both')

for i in range(10):
    one = randint(1, 10)
    two = randint(1, 10)
    Question(window.inner, "Quanto fa {} + {} ?".format(one, two), str(one + two))

root.mainloop()


问:
jQuery ".on('click')" event works only once. Image Slider
I've been looking for a solution that I couldn't find.

I built a simple image slider where every time you click on the picture this should change with the follow one. Specifically, on-click event move the css property z-index to the next picture using addClass and removeClass.

The problem is that it works only the first time you press on and never again, this means I can show only the first and the second picture. I cannot find solution, what I'm looking for is just how to get the on-click event work every time I click on the picture?

var currentImg = $(".active");
var nextImg = currentImg.next();

$(".imageSlider").on("click", function() {
 alert("ciao");
 currentImg.removeClass(".active").css("z-index", 0);
 nextImg.addClass(".active").css("z-index", 10);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active  {z-index: 10;}</code>```

```

答:
currentImg = $(".active"); nextImg = currentImg.next(); should be placed in function

removeClass(".active") => removeClass("active").  addClass(".active") => addClass("active")

next() is a problem.

Except z-index, you can try another attribute -- opacity.

Body:
I've been looking for a solution that I couldn't find.

I built a simple image slider where every time you click on the picture this should change with the follow one. Specifically, on-click event move the css property z-index to the next picture using addClass and removeClass.

The problem is that it works only the first time you press on and never again, this means I can show only the first and the second picture. I cannot find solution, what I'm looking for is just how to get the on-click event work every time I click on the picture?

var currentImg = $(".active");
var nextImg = currentImg.next();

$(".imageSlider").on("click", function() {
 alert("ciao");
 currentImg.removeClass(".active").css("z-index", 0);
 nextImg.addClass(".active").css("z-index", 10);
});

.active  {z-index: 10;}


问:
AppCompatRadioButton not shown
Since I want to use buttonTint on versions < 21, I need to switch from RadioButton to AppCompatRadioButton. Unfortunately the button is not shown on the device (Android 5.1). It's strange because the android:text of the AppCompatRadioButton works, so that means that the button basically works. Only the circle is not shown. Any ideas why? I also tried to set other color attributes which come with AppCompatRadioButton. It didn't work either. I also updated to the latest compatibility package, I moved the button inside the xml to another position, but nothing works.

This is the xml definition:

```<code><android.support.v7.widget.AppCompatRadioButton
    android:id="@+id/radio_bronze_monthly"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:onClick="onBillingRadioButtonClicked"
    android:text="@string/bronze_monthly"
    android:textColor="@color/black"
    android:textSize="@dimen/default_text_size"
    app:buttonTint="@color/black"
    app:colorAccent="@color/black"
    app:colorPrimary="@color/black"
    app:colorPrimaryDark="@color/black"/>
</code>```

答:
I have Android 5.1 and quickly tried it out, it is working fine for me like this. I just put it inside the default constraint layout, but that should not make a difference.</p>

```<code><android.support.v7.widget.AppCompatRadioButton
    android:id="@+id/radio_bronze_monthly"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:buttonTint="@android:color/black"
    android:text="asdf"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />
</code>```

Title: AppCompatRadioButton not shown

Body:
Since I want to use buttonTint on versions < 21, I need to switch from RadioButton to AppCompatRadioButton. Unfortunately the button is not shown on the device (Android 5.1). It's strange because the android:text of the AppCompatRadioButton works, so that means that the button basically works. Only the circle is not shown. Any ideas why? I also tried to set other color attributes which come with AppCompatRadioButton. It didn't work either. I also updated to the latest compatibility package, I moved the button inside the xml to another position, but nothing works.

This is the xml definition:

<android.support.v7.widget.AppCompatRadioButton
    android:id="@+id/radio_bronze_monthly"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:onClick="onBillingRadioButtonClicked"
    android:text="@string/bronze_monthly"
    android:textColor="@color/black"
    android:textSize="@dimen/default_text_size"
    app:buttonTint="@color/black"
    app:colorAccent="@color/black"
    app:colorPrimary="@color/black"
    app:colorPrimaryDark="@color/black"/>

Body:
I have Android 5.1 and quickly tried it out, it is working fine for me like this. I just put it inside the default constraint layout, but that should not make a difference.

<android.support.v7.widget.AppCompatRadioButton
    android:id="@+id/radio_bronze_monthly"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:buttonTint="@android:color/black"
    android:text="asdf"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />


问:
Sufficient API Response for Mobile App
I'm creating an API for my mobile app with Laravel - Lumen and i have the following scenario which i don't know what is the most sufficient way to return the response to my Android / IOS App,

lets assume that the user is trying to sign in (same end point):

Case 1 :  the user provide the correct data for the sign in.

Case 2 :  the user sign in with wrong password.

Case 3 :  the user is not exist and have to sign up first.

My question is what should my API response look like in order i can differentiate those cases in my App logic and to move forward accordingly (I need to know which case is occurred ) ?

答:
Your response would be below - </p>

```<code>Use this response if request validated successfully.
{"status":"OK", "message":"success"}

Use this response if user not exist.
{"status":"FAIL", "message":"not_register"}

Use this response for invalid credentials.
{"status":"FAIL", "message":"invalid_credentials"}
</code>```

Title: Sufficient API Response for Mobile App

Body:
Your response would be below -

Use this response if request validated successfully.
{"status":"OK", "message":"success"}

Use this response if user not exist.
{"status":"FAIL", "message":"not_register"}

Use this response for invalid credentials.
{"status":"FAIL", "message":"invalid_credentials"}


问:
Is it possible to remove specific tool from bokeh toolbar specially bokeh logo and help icon?
I have been doing a small project on plotting graph for my school on bokeh but bokeh toolbar is coming with unnecessary logos.is it possible to remove specific tools?
I have tried this but it's removing the entire toolbar</p>

```<code>p.toolbar.logo = None
p.toolbar_location = None
</code>```

答:
If I understand you right you want to configure the toolbar to have only certain tools. So i rather add the tools that i want instead of removing them. And remove the logo:</p>

```<code>from bokeh.plotting import show
from bokeh.models.tools import PanTool, SaveTool

p = figure()
p.line([1, 2, 3, 4],[1, 4, 3, 0])
p.toolbar.logo = None
p.tools = [SaveTool(), PanTool()]
show(p)
</code>```

Body:
I have been doing a small project on plotting graph for my school on bokeh but bokeh toolbar is coming with unnecessary logos.is it possible to remove specific tools?
I have tried this but it's removing the entire toolbar

p.toolbar.logo = None
p.toolbar_location = None

Body:
If I understand you right you want to configure the toolbar to have only certain tools. So i rather add the tools that i want instead of removing them. And remove the logo:

from bokeh.plotting import show
from bokeh.models.tools import PanTool, SaveTool

p = figure()
p.line([1, 2, 3, 4],[1, 4, 3, 0])
p.toolbar.logo = None
p.tools = [SaveTool(), PanTool()]
show(p)


问:
Instantiating objects in the constructor
Is there any benefit to doing the following:

```<code>public class Foo
{
    private Bar bar;

    public Foo()
    {
        bar = new Bar();
    }
}
</code>```

Instead of doing it like so:

```<code>public class Foo
{
    private Bar bar = new Bar();

    public Foo()
    {
    }
}
</code>```

Given that at instantiation, the private member variable in either example will be instantiated, I don't believe there is a difference, but I've seen it enough times to where I'm curious.

答:
In your case, there's no real difference in the functionality.  There is the problem of figuring out where and how everything gets initialized, though.  If i put the initialization in the constructor, i have two big benefits:

Everything's initialized in one place; i don't have to go hunting for whether and where it gets set.

If i want, i can pass arguments to the Bar constructor based on how i'm setting stuff up.  If the initializer's outside the constructor, i'm a lot more limited in how i can initialize stuff.

Frankly, the IDE helps a bit with #1...though it does yank me away from the code i was just looking at, my classes are rarely so huge as to make re-finding stuff an issue.  So if i don't need #2, i'm just as likely to do it either way depending on the project and my mood.  For bigger projects, though, i'd want to have all my init code in one place.

Edit:

OK, apparently there is a difference between the two.  But the case where it matters is rare.

I've created the following classes:

```<code>class Program
{
    public Program() { Console.WriteLine(this); }

    static void Main(string[] args)
    {
        other p = new other();
        Console.WriteLine(p);
        Console.ReadLine();
    }
}

class other : Program
{
    string s1 = "Hello";
    string s2;

    public other() { s2 = "World"; }
    public override string ToString() { return s1 + s2; }
}
</code>```

Now, what i found was a bit surprising, and unexpected (if you haven't read the C# spec).

This is what the other class's constructor compiled to:

```<code>.method public hidebysig specialname rtspecialname
        instance void  .ctor() cil managed
{
  // Code size       29 (0x1d)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldstr      "Hello"
  IL_0006:  stfld      string ConsoleApplication1.other::s1
  IL_000b:  ldarg.0
  IL_000c:  call       instance void ConsoleApplication1.Program::.ctor()
  IL_0011:  ldarg.0
  IL_0012:  ldstr      "World"
  IL_0017:  stfld      string ConsoleApplication1.other::s2
  IL_001c:  ret
} // end of method other::.ctor
</code>```

Note the call to Program::.ctor (the base class's constructor) sandwiched between the two ldstr/stfld pairs (those are what set s1 and s2).  Meaning, when the base constructor is running, s2 has not been set yet.

The program, for reference, outputs the following:

```<code>Hello
HelloWorld
</code>```

because in Program's constructor,  Console.WriteLine(obj) called obj.ToString(), which (since the object is already an other) was other::ToString().  Since s2 wasn't set yet, we didn't get a "World" the first time.  If we were doing something more error prone than just printing stuff, this could cause real problems.

Now, this is an ugly example, designed to be a pathological case.  But it's an excellent argument against calling virtual functions in your constructor.  Without doing just that, this breakage would not have been possible.  That's the only time you really have to worry about the difference: when your base class's constructor is calling virtual methods that you've overridden, that rely on the values of any fields that are being set in the constructor.  A pretty narrow window of breakability, but yeah.

Body:
Is there any benefit to doing the following:

public class Foo
{
    private Bar bar;

    public Foo()
    {
        bar = new Bar();
    }
}

Instead of doing it like so:

public class Foo
{
    private Bar bar = new Bar();

    public Foo()
    {
    }
}

Given that at instantiation, the private member variable in either example will be instantiated, I don't believe there is a difference, but I've seen it enough times to where I'm curious.

Body:
In your case, there's no real difference in the functionality.  There is the problem of figuring out where and how everything gets initialized, though.  If i put the initialization in the constructor, i have two big benefits:

Everything's initialized in one place; i don't have to go hunting for whether and where it gets set.

If i want, i can pass arguments to the Bar constructor based on how i'm setting stuff up.  If the initializer's outside the constructor, i'm a lot more limited in how i can initialize stuff.

Frankly, the IDE helps a bit with #1...though it does yank me away from the code i was just looking at, my classes are rarely so huge as to make re-finding stuff an issue.  So if i don't need #2, i'm just as likely to do it either way depending on the project and my mood.  For bigger projects, though, i'd want to have all my init code in one place.

Edit:

OK, apparently there is a difference between the two.  But the case where it matters is rare.

I've created the following classes:

class Program
{
    public Program() { Console.WriteLine(this); }

    static void Main(string[] args)
    {
        other p = new other();
        Console.WriteLine(p);
        Console.ReadLine();
    }
}

class other : Program
{
    string s1 = "Hello";
    string s2;

    public other() { s2 = "World"; }
    public override string ToString() { return s1 + s2; }
}

Now, what i found was a bit surprising, and unexpected (if you haven't read the C# spec).

This is what the other class's constructor compiled to:

.method public hidebysig specialname rtspecialname
        instance void  .ctor() cil managed
{
  // Code size       29 (0x1d)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldstr      "Hello"
  IL_0006:  stfld      string ConsoleApplication1.other::s1
  IL_000b:  ldarg.0
  IL_000c:  call       instance void ConsoleApplication1.Program::.ctor()
  IL_0011:  ldarg.0
  IL_0012:  ldstr      "World"
  IL_0017:  stfld      string ConsoleApplication1.other::s2
  IL_001c:  ret
} // end of method other::.ctor

Note the call to Program::.ctor (the base class's constructor) sandwiched between the two ldstr/stfld pairs (those are what set s1 and s2).  Meaning, when the base constructor is running, s2 has not been set yet.

The program, for reference, outputs the following:

Hello
HelloWorld

because in Program's constructor,  Console.WriteLine(obj) called obj.ToString(), which (since the object is already an other) was other::ToString().  Since s2 wasn't set yet, we didn't get a "World" the first time.  If we were doing something more error prone than just printing stuff, this could cause real problems.

Now, this is an ugly example, designed to be a pathological case.  But it's an excellent argument against calling virtual functions in your constructor.  Without doing just that, this breakage would not have been possible.  That's the only time you really have to worry about the difference: when your base class's constructor is calling virtual methods that you've overridden, that rely on the values of any fields that are being set in the constructor.  A pretty narrow window of breakability, but yeah.


问:
MSAL js to show login in webpage than popup & custom redirect uri configuration
I am using Azure AD B2C UI customization feature to have my own custom login and signup pages. I could get it work from portal by cicking "Run Now" button. But i am not sure how to achieve it with Angular SPA.  I think i can use msal.js but it is opening login page in popup.

Is it possible to have full page redirect for login ?

Also, msal.js is taking client host url as default redirect uri.

Is it possible to set custom redirect_uri in the MSAL configuration ?

for e.g  this sample web app kind of UX i am looking for.

答:
You can use msal library with the sample application provided. The policy url will auto load the custom UI.

  var applicationConfig = {
            clientID: _clientId,
            authority: "https://login.microsoftonline.com/tfp/{tenant}/B2C_1A_signup_signin_usingAAD",
            b2cScopes: ["https://{tenant}/api/read", "offline_access"],
            webApi: 'https://localhost:44332/api/tasks',
        };

var clientApplication = new Msal.UserAgentApplication(applicationConfig.clientID, applicationConfig.authority, authCallback, { cacheLocation: 'localStorage'});
clientApplication.loginRedirect(applicationConfig.b2cScopes)```

Body:
I am using Azure AD B2C UI customization feature to have my own custom login and signup pages. I could get it work from portal by cicking "Run Now" button. But i am not sure how to achieve it with Angular SPA.  I think i can use msal.js but it is opening login page in popup.

Is it possible to have full page redirect for login ?

Also, msal.js is taking client host url as default redirect uri.

Is it possible to set custom redirect_uri in the MSAL configuration ?

for e.g  this sample <a href="https://login.microsoftonline.com/b2ctechready.onmicrosoft.com/oauth2/v2.0/authorize?p=b2c_1a_sign_up_sign_in_games&client_id=f327751f-477c-4df8-a174-f59786d99d9f&redirect_uri=https%3A%2F%2Fwingtipgamesb2c.azurewebsites.net%2Fb2c_1a_sign_up_sign_in_games-callback&response_type=code%20id_token%20token&scope=openid%20profile%20https%3A%2F%2Fb2ctechready.onmicrosoft.com%2Fwingtipb2c%2FBilling.Read%20https%3A%2F%2Fb2ctechready.onmicrosoft.com%2Fwingtipb2c%2FMusic.Read&response_mode=form_post&nonce=636483580989775419.ZWFjMTM2MWItZWM0Mi00YThmLTg1YTktM2VkYjVjZTNmMWE2MTA2M2YwY2ItYWRhZC00ZmFmLWE5NmYtOWM0OTg3YTU3Mzk3&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer&client_assertion=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJicmFuZCI6IldpbmdUaXAgR2FtZXMiLCJwbGF5ZXJfcHJvZmlsZV9yZWdpc3RyYXRpb25fbW9kZSI6IkJhc2ljIiwibmJmIjoxNTEyNzYxMjk4LCJleHAiOjE1MTI3NjE1OTgsImlhdCI6MTUxMjc2MTI5OCwiaXNzIjoiaHR0cHM6Ly9sb2dpbi5taWNyb3NvZnRvbmxpbmUuY29tL2VjMGUyOTcyLTM0MDMtNDY4NS05ODNhLTdjMGI4ZmJmN2Y4Ni92Mi4wLyIsImF1ZCI6Imh0dHBzOi8vd2luZ3RpcGdhbWVzYjJjLmF6dXJld2Vic2l0ZXMubmV0L2IyY18xYV9zaWduX3VwX3NpZ25faW5fZ2FtZXMtY2FsbGJhY2sifQ.tWrElj1r_xYoyp6BMPrw2Bc85G1f6PoMlle37rZkVYQ&state=CfDJ8J2_kzTit_lKm8PaAMPLdfCl-2AKUCyyw5Q_3o6o-h2M18tTwpoWDDPvz6Ob6BDHepaaWJztgpiAcykHaP84WCSTCLfQUb8G2qn3NEBj4yT4ep2KQQbUJ2r5sRVWHyFdBeFpSEFVesCAtEF0Bfbf2Vn2PIOuJNCj_q68_fr2oEc0OWDeMof1M6AGVFOlytNo7Ht5wYnI1LYyAwasWzOt2B_fGb-wzbH-vGJXMmh4cB3mkaAAPg0y1MKI1cGYR4l8sEGVtiGkrCt80mNQilpavz49oZpbNQ9-Re5-UYgI8EO82wE_yokLCdCRRWG1kaAKSBwFt_UewnhIjzzGeZBcYQSkqKfMhCxlXcoxC5T7MYLGcZsRPdhQfjD8eaFqc0xJh-VMtlhxPxF88tTl_imizHI" rel="nofollow noreferrer">web app kind of UX i am looking for.


问:
Python design pattern for many conditions
What is the recommended structure to write validate functions with many conditions? See these two examples. The first looks ugly, the second isn't very common, perhaps because assert is generally used to rule out unexpected behaviour. Are there better alternatives?

```<code>def validate(val):
  if cond1(val):
    return False
  if cond2(val):
    return False
  if cond3(val)
    return False
  return True
</code>```

Or

```<code>def validate(val):
  try:
    assert cond1(val)
    assert cond2(val)
    assert cond3(val)
    return True
  except AssertionError:
    return False
</code>```

答:
The first way is much better. It can be prettified a little bit using any():

```<code>def validate_conditions(value):
    return not any((condition(value) for condition in conditions))
</code>```

Body:
What is the recommended structure to write validate functions with many conditions? See these two examples. The first looks ugly, the second isn't very common, perhaps because assert is generally used to rule out unexpected behaviour. Are there better alternatives?

def validate(val):
  if cond1(val):
    return False
  if cond2(val):
    return False
  if cond3(val)
    return False
  return True

Or

def validate(val):
  try:
    assert cond1(val)
    assert cond2(val)
    assert cond3(val)
    return True
  except AssertionError:
    return False

Body:
The first way is much better. It can be prettified a little bit using any():

def validate_conditions(value):
    return not any((condition(value) for condition in conditions))


问:
Execution order of anonymous function
```<code>(function() {
  f();
  f = function() {
    console.log(8);
  }
})()

function f() {
  console.log(9)
}

f();
</code>```

prints 9, 8.

Why isn't it 8, 9?

Why doesn't the anonymous function execute first?

答:
Please see the numbers for order of execution.

Basically you have 4 parts,

The function declaration with a hoisted function,

an IIFE calling the function

a new assignment of f and

the last call of the new function.

(function() {
  f();                 // calling hoisted function      2
  f = function() {     // assigning new function to f   3
    console.log(8);
  }
})()
function f() {         // hoisted function              1
  console.log(9)
}
f();                   // calling new function          4```

Title: Execution order of anonymous function

Body:
(function() {
  f();
  f = function() {
    console.log(8);
  }
})()

function f() {
  console.log(9)
}

f();

prints 9, 8.

Why isn't it 8, 9?

Why doesn't the anonymous function execute first?


问:
What does a weighted word embedding mean?
In the paper that I am trying to implement, it says,

In this work, tweets were modeled using three types of text
  representation. The first one is a bag-of-words model weighted by
  tf-idf (term frequency
  - inverse document frequency) (Section
  2.1.1). The second represents a sentence by averaging the word embeddings of all words (in the sentence) and the third represents a
  sentence by averaging the weighted word embeddings of all words, the
  weight of a word is given by tf-idf (Section
  2.1.2).

I am not sure about the third representation which is mentioned as the weighted word embeddings which is using the weight of a word is given by tf-idf. I am not even sure if they can used together.

答:
Averaging (possibly weighted) of word embeddings makes sense, though depending on the main algorithm and the training data this sentence representation may not be the best. The intuition is the following:

You might want to handle sentences of different length, hence the averaging (better than plain sum).

Some words in a sentence are usually much more valuable than others. TF-IDF is the simplest measure of the word value. Note that the scale of the result doesn't change.

See also this paper by Kenter et al. There is a nice post that performs the comparison of these two approaches in different algorithms, and concludes that none is significantly better than the other: some algorithms favor simple averaging, some algorithms perform better with TF-IDF weighting.


问:
Angularjs : How to display float number to nearst rounded number
I have an angularjs variable bill_amount which store 500.44. How can I display it to 501 without using controller function.
I use{{bill_amount | number: 0}} but it show 500 when the amount is greater than .5 then it adds +1 on the amount but I need to add +1  on the amount if the amount is greater then .0 like if the amount is 500.1 than I want to show 501.

答:
You can use

```<code>Math.ceil()
</code>```

Example Math.ceil(1.4) results '2'

Body:
You can use

Math.ceil()

Example Math.ceil(1.4) results '2'


问:
Explain this snippet which finds the maximum of two integers without using if-else or any other comparison operator?
Find the maximum of two numbers. You should not use if-else or any other comparison operator. I found this question on online bulletin board, so i thought i should ask in StackOverflow

EXAMPLE
Input: 5, 10
Output: 10

I found this solution, can someone help me understand these lines of code

```<code>int getMax(int a, int b) {
    int c = a - b;
    int k = (c >> 31) & 0x1;
    int max = a - k * c;
    return max;
}
</code>```

答:
Here's what those lines are doing:

c is a-b.  if c is negative, a=b, so max is a - 0 * c = a.  If c is 1, this means that a<b and then a - 1 * c = a - (a - b) = a - a + b = b.

In the overall, it's just using the sign bit of the difference to avoid using greater than or less than operations.  It's honestly a little silly to say that this code doesn't use a comparison.  c is the result of comparing a and b.  The code just doesn't use a comparison operator.  You could do a similar thing in many assembly codes by just subtracting the numbers and then jumping based on the values set in the status register.

I should also add that all of these solutions are assuming that the two numbers are integers.  If they are floats, doubles, or something more complicated (BigInts, Rational numbers, etc.) then you really have to use a comparison operator.  Bit-tricks will not generally do for those.

Body:
Find the maximum of two numbers. You should not use if-else or any other comparison operator. I found this question on online bulletin board, so i thought i should ask in StackOverflow

EXAMPLE
Input: 5, 10
Output: 10

I found this solution, can someone help me understand these lines of code

int getMax(int a, int b) {
    int c = a - b;
    int k = (c >> 31) & 0x1;
    int max = a - k * c;
    return max;
}

Body:
Here's what those lines are doing:

c is a-b.  if c is negative, a<b.

k is 32nd bit of c which is the sign bit of c (assuming 32 bit integers.  If done on a platform with 64 bit integers, this code will not work).  It's shifted 31 bits to the right to remove the rightmost 31 bits leaving the sign bit in the right most place and then anding it with 1 to remove all the bits to the left (which will be filled with 1s if c is negative).  So k will be 1 if c is negative and 0 if c is positive.

Then max = a - k * c.  If c is 0, this means a>=b, so max is a - 0 * c = a.  If c is 1, this means that a<b and then a - 1 * c = a - (a - b) = a - a + b = b.

In the overall, it's just using the sign bit of the difference to avoid using greater than or less than operations.  It's honestly a little silly to say that this code doesn't use a comparison.  c is the result of comparing a and b.  The code just doesn't use a comparison operator.  You could do a similar thing in many assembly codes by just subtracting the numbers and then jumping based on the values set in the status register.

I should also add that all of these solutions are assuming that the two numbers are integers.  If they are floats, doubles, or something more complicated (BigInts, Rational numbers, etc.) then you really have to use a comparison operator.  Bit-tricks will not generally do for those.


问:
Error type 3 Error: Activity class {} does not exist
I have an IntelliJ Android project, that I successfully imported to Android Studio 0.4.0. It works perfectly if I don't change anything in manifest. However, when I want to change the launcher activity and run, it fails with this error:

```<code>Launching application: com.trackingeng/LandingActivity.
DEVICE SHELL COMMAND: am start -D -n "com.trackingeng/LandingActivity"
    -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Starting: Intent { act=android.intent.action.MAIN
    cat=[android.intent.category.LAUNCHER] cmp=com.trackingeng/LandingActivity }
Error type 3
Error: Activity class {com.trackingeng/LandingActivity} does not exist.
</code>```

When I click Sync Project with Gradle files, it outputs:

```<code>Project Sync
The project 'TrackingEng' is not a Gradle-based project
</code>```

Run settings:

答:
If your app has only two word package name like[com.example] then all your class must be mentioned with full path in manifest like [com.example.SplashActivity] instead of relative path like[.SplashActivity]
change this and delete all your build folder and re-run app.

Body:
I have an IntelliJ Android project, that I successfully imported to Android Studio 0.4.0. It works perfectly if I don't change anything in manifest. However, when I want to change the launcher activity and run, it fails with this error:

Launching application: com.trackingeng/LandingActivity.
DEVICE SHELL COMMAND: am start -D -n "com.trackingeng/LandingActivity"
    -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Starting: Intent { act=android.intent.action.MAIN
    cat=[android.intent.category.LAUNCHER] cmp=com.trackingeng/LandingActivity }
Error type 3
Error: Activity class {com.trackingeng/LandingActivity} does not exist.

When I click Sync Project with Gradle files, it outputs:

Project Sync
The project 'TrackingEng' is not a Gradle-based project

Run settings:


答:
A compact way to write that function is to use any and a generator expression:

```<code>def validate(val):
    conditions = (cond1, cond2, cond3)
    return not any(cond(val) for cond in conditions)
</code>```

The any and all functions short-circuit, so they'll stop testing as soon as they have a definite result, i.e., any stops as soon as it hits a True-ish value, all stops as soon as it hits a False-ish value, so this form of testing is quite efficient.

I should also mention that it's much more efficient to pass a generator expression like this to all / any than a list comprehension. Because all / any stop testing as soon as they get a valid result, if you feed them from a generator then the generator will stop too, thus in the above code if cond(val) evaluates to a True-ish value no further conditions will be tested. But if you pass all / any  a list comprehension, eg any([cond(val) for cond in conditions]) the whole list has to be be built before all / any can even start testing.

You haven't shown us the internal structure of your cond functions, but you did mention assert in your question, so I feel that the following remarks are in order here.

As I mentioned in the comments, assert should not be used to validate data, it's used to validate program logic. (Also, assertion-handling can be disabled via an -O command line option). The correct Exception to use for data with invalid values is ValueError, and for objects that are the wrong type, use TypeError. But bear in mind that exceptions are designed to handle situations that are exceptional.

If you expect a lot of malformed data then it's generally more efficient to use if based logic than exceptions. Python exception-handling is quite fast if the exception isn't actually raised, in fact it's faster than the equivalent if based code. However, if the exception is raised say more than 5-10% of the time, then the try...except based code will be noticeably slower than the if based equivalent.

Of course, sometimes using exceptions is the only sensible option, even though the situation isn't all that exceptional. A classic example is when you're converting a collection of numeric strings to actual numeric objects, so that strings that represent integers get converted to integer objects, other numeric strings get converted to floats, and other strings get left as strings. The standard way to do this in Python involves using exceptions. For example:

```<code>def convert(s):
    ''' Convert s to int or float, if possible '''
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            return s

data = ['42', 'spam', '2.99792458E8']
out = [convert(u) for u in data]
print(out)
print([type(u) for u in out])
</code>```

output

```<code>[42, 'spam', 299792458.0]
[<class 'int'>, <class 'str'>, <class 'float'>]
</code>```

Using "Look Before You Leap" logic here is possible here, but it makes the code more complicated because you need to deal with possible minus signs and scientific notation.

Title: Python design pattern for many conditions

Body:
A compact way to write that function is to use any and a generator expression:

def validate(val):
    conditions = (cond1, cond2, cond3)
    return not any(cond(val) for cond in conditions)

The any and all functions short-circuit, so they'll stop testing as soon as they have a definite result, i.e., any stops as soon as it hits a True-ish value, all stops as soon as it hits a False-ish value, so this form of testing is quite efficient.

I should also mention that it's much more efficient to pass a generator expression like this to all / any than a list comprehension. Because all / any stop testing as soon as they get a valid result, if you feed them from a generator then the generator will stop too, thus in the above code if cond(val) evaluates to a True-ish value no further conditions will be tested. But if you pass all / any  a list comprehension, eg any([cond(val) for cond in conditions]) the whole list has to be be built before all / any can even start testing.

You haven't shown us the internal structure of your cond functions, but you did mention assert in your question, so I feel that the following remarks are in order here.

As I mentioned in the comments, assert should not be used to validate data, it's used to validate program logic. (Also, assertion-handling can be disabled via an -O command line option). The correct Exception to use for data with invalid values is ValueError, and for objects that are the wrong type, use TypeError. But bear in mind that exceptions are designed to handle situations that are exceptional.

If you expect a lot of malformed data then it's generally more efficient to use if based logic than exceptions. Python exception-handling is quite fast if the exception isn't actually raised, in fact it's faster than the equivalent if based code. However, if the exception is raised say more than 5-10% of the time, then the try...except based code will be noticeably slower than the if based equivalent.

Of course, sometimes using exceptions is the only sensible option, even though the situation isn't all that exceptional. A classic example is when you're converting a collection of numeric strings to actual numeric objects, so that strings that represent integers get converted to integer objects, other numeric strings get converted to floats, and other strings get left as strings. The standard way to do this in Python involves using exceptions. For example:

def convert(s):
    ''' Convert s to int or float, if possible '''
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            return s

data = ['42', 'spam', '2.99792458E8']
out = [convert(u) for u in data]
print(out)
print([type(u) for u in out])

output

[42, 'spam', 299792458.0]
[<class 'int'>, <class 'str'>, <class 'float'>]

Using "Look Before You Leap" logic here is possible here, but it makes the code more complicated because you need to deal with possible minus signs and scientific notation.


问:
Why Rendering Components Directly To The Body Of The HTML Not Advisable?
In ReactJS, it is not allowed, or rather discouraged to render a react component directly to the body of the HTML.

For instance, this:

```<code>...
render(<MyComponent />, document.body);
</code>```

Would log a warning about how it is not encouraged to render a component the way I did. Why is that?

答: This is because the Component's children are often manipulated by third-party scripts and browser extensions and this may lead to reconciliation issues. As a result, the recommended pattern to follow is to render your main component in the container element created in the app.</p>

Body:
In ReactJS, it is not allowed, or rather discouraged to render a react component directly to the body of the HTML.

For instance, this:

...
render(<MyComponent />, document.body);

Would log a warning about how it is not encouraged to render a component the way I did. Why is that?


问:
Reading a string with fgets into a char array from a filestream. [C]
I am trying to make a programm which decrypts a series of letters from a file.
Sadly, I am failing to read the letters into a char array (string) because I do not really know how the fgets() function works.
So my actual code looks like this:

```<code>#define stringlength 80

int main(void)
{
   FILE *source;
   char puffer[stringlength], name[20];

   printf("Which file do you want to read: ");
   scanf("%s",name);
   if( (source=fopen(name,"r")) == NULL)
   {
      fprintf(stderr, "Can not open %s\n", name);
      return EXIT_FAILURE;
   }
   while(fgets(puffer, stringlength, source))
   {
     fputs(puffer, stdout);
   }
   return EXIT_SUCCESS;
}
</code>```

So actually this kinda works. It opens the command prompt and writes the the sequence of letters in that window.
But now I have to use every single letter and compare it with the key's letters.
It just compares the right four bits with a XOR to keep the result letter in the same column of the ASCII chart.
I have already written a algorithm which works for single letters:

```<code>saveLeftFourBits = letterOfFile >> 4;
saveLeftFourBits = saveLeftFourBits << 4;
letterOfFile = letterOfFile & 0x0F;
letterOfKey = letterOfKey & 0x0F;
temp = letterOfFile ^ letterOfKey;
temp |= saveLeftFourBits;
</code>```

temp should be the resulting letter.
So now I am struggling with how to read a single letter from the fgets function into a variable (in letterOfFile) and compare it with the letterOfKey.
Or is there maybe a string-function which does that is a lot easier way?
I hope someone can help me. :)

答:
The program is fine.
However the shifting and masking looks suspicious to me. I think you've fallen for the common confusion between binary and hex. Binary numbers are the format in which integers are represented natively, and the bitwise operators only make sense on them. Hex number are ASCII strings of characters like "F2E0", the first character is "F", as in "Fred" and needs to be treated as text. You can write a little function to take a character and return an number 0-15, or -1 on error (passed a letter like "K" which doesn't have  a hex value").

So like this

```<code>int hextobinary(char hex)
{
    /* logic here */
}

int hexstringtobinary(char *hexstr)
{
   int i;
   int answer = 0;
   for(i=0;hextr[i] != '\0';i+++)
   {
      answer *= 16;
      answer += hextobinary(hexstr[i]);
   }
   return answer;
}
</code>```

As an exercise, put in the error handling if passed a string with non-hex characters in it.

Body:
I am trying to make a programm which decrypts a series of letters from a file.
Sadly, I am failing to read the letters into a char array (string) because I do not really know how the fgets() function works.
So my actual code looks like this:

#define stringlength 80

int main(void)
{
   FILE *source;
   char puffer[stringlength], name[20];

   printf("Which file do you want to read: ");
   scanf("%s",name);
   if( (source=fopen(name,"r")) == NULL)
   {
      fprintf(stderr, "Can not open %s\n", name);
      return EXIT_FAILURE;
   }
   while(fgets(puffer, stringlength, source))
   {
     fputs(puffer, stdout);
   }
   return EXIT_SUCCESS;
}

So actually this kinda works. It opens the command prompt and writes the the sequence of letters in that window.
But now I have to use every single letter and compare it with the key's letters.
It just compares the right four bits with a XOR to keep the result letter in the same column of the ASCII chart.
I have already written a algorithm which works for single letters:

saveLeftFourBits = letterOfFile >> 4;
saveLeftFourBits = saveLeftFourBits << 4;
letterOfFile = letterOfFile & 0x0F;
letterOfKey = letterOfKey & 0x0F;
temp = letterOfFile ^ letterOfKey;
temp |= saveLeftFourBits;

temp should be the resulting letter.
So now I am struggling with how to read a single letter from the fgets function into a variable (in letterOfFile) and compare it with the letterOfKey.
Or is there maybe a string-function which does that is a lot easier way?
I hope someone can help me. :)

Body:
The program is fine.
However the shifting and masking looks suspicious to me. I think you've fallen for the common confusion between binary and hex. Binary numbers are the format in which integers are represented natively, and the bitwise operators only make sense on them. Hex number are ASCII strings of characters like "F2E0", the first character is "F", as in "Fred" and needs to be treated as text. You can write a little function to take a character and return an number 0-15, or -1 on error (passed a letter like "K" which doesn't have  a hex value").

So like this

int hextobinary(char hex)
{
    /* logic here */
}

int hexstringtobinary(char *hexstr)
{
   int i;
   int answer = 0;
   for(i=0;hextr[i] != '\0';i+++)
   {
      answer *= 16;
      answer += hextobinary(hexstr[i]);
   }
   return answer;
}

As an exercise, put in the error handling if passed a string with non-hex characters in it.


问:
How to return boolean in if else statement and the return value will link to anothe if else statement in Matlab?
I have the following if else statement that created by myself in order to link to the if else statement given in second part:

```<code>m=4
if m==3
   disp(true)
else
   disp(false)
</code>```

Second part ( this code is fix cannot be change):

```<code>if (true)
   A=Hello World
else
   A=Bye
</code>```

If using the first part code, my output will be

```<code>A=Hello World
</code>```

but my desire output is

```<code>A=Bye
</code>```

Anyone one have idea to edit the first part, because now my return value in first part not able to link to my second part.

答:
You don't need two if statements in order to accomplish this task. One is more than enough to perform all what you need:

```<code>m = 4;

if (m == 3)
   A = 'Hello World';
else
   A = 'Bye';
end

disp(A);
</code>```

A few comments concerning your code:

if statements need to be closed with an end

if (true) will always pass into the statement

the disp function doesn't assign a value, its only goal is to display it in the Command Window

in order to work with text, you have to enclose it within single quotes ' (char array) or double quotes " (string), more info here

If you posted only small excerpts of your code and you need to perform those two checks sequentially, in different parts of your script, then:

```<code>m = 4;

if (m == 3)
   m_equals_3 = true;
   disp('M == 3');
else
   m_equals_3 = false;
   disp('M ~= 3');
end

% then, somewhere else...

if (m_equals_3)
   A = 'Hello World';
else
   A = 'Bye';
end

% ...
</code>```

Body:
I have the following if else statement that created by myself in order to link to the if else statement given in second part:

m=4
if m==3
   disp(true)
else
   disp(false)

Second part ( this code is fix cannot be change):

if (true)
   A=Hello World
else
   A=Bye

If using the first part code, my output will be

A=Hello World

but my desire output is

A=Bye

Anyone one have idea to edit the first part, because now my return value in first part not able to link to my second part.

Body:
You don't need two if statements in order to accomplish this task. One is more than enough to perform all what you need:

m = 4;

if (m == 3)
   A = 'Hello World';
else
   A = 'Bye';
end

disp(A);

A few comments concerning your code:

if statements need to be closed with an end

if (true) will always pass into the statement

the disp function doesn't assign a value, its only goal is to display it in the Command Window

in order to work with text, you have to enclose it within single quotes ' (char array) or double quotes " (string), more info here

If you posted only small excerpts of your code and you need to perform those two checks sequentially, in different parts of your script, then:

m = 4;

if (m == 3)
   m_equals_3 = true;
   disp('M == 3');
else
   m_equals_3 = false;
   disp('M ~= 3');
end

% then, somewhere else...

if (m_equals_3)
   A = 'Hello World';
else
   A = 'Bye';
end

% ...


问:
Ruby On Rails @gym.All API Isn't Returning All Values
I have a postgresql database with a table called gyms.

It has several fields and a one to one relationship with another table. Its migration file looks like this:

```<code>class CreateGyms < ActiveRecord::Migration[5.1]
  def change
    create_table :gyms do |t|
      t.string :name
      t.string :address
      t.string :city
      t.string :country

      t.timestamps
    end
  end
end
</code>```

I have created several rows for the table and according to my postgresql table they are fine. However, when I try to GET the json the name, city, address and country variables are not being returned.

The controller looks like this:

```<code>class GymsController < ApplicationController
  before_action :set_gym, only: [:show, :update, :destroy]
  # GET /gyms
  # GET /gyms.json
  def index
    @gyms = Gym.all
  end

  # GET /gyms/1
  # GET /gyms/1.json
  def show
  end
</code>```

Why are only these values being returned?

```<code>{"id":1,"created_at":"2017-12-09T09:18:48.993Z","updated_at":"2017-12-09T09:18:48.993Z","url":"https://okuapp.com/gyms/1.json"}
</code>```

And how can i make it so that all values are returned? (name, city, etc)

Before when i only had one table and there were no associations, this was not a problem.

答:
I had changed my schema for the gyms table but i had not updated the json builder files.

Updated those and fixed the problem.

Body:
I have a postgresql database with a table called gyms.

It has several fields and a one to one relationship with another table. Its migration file looks like this:

class CreateGyms < ActiveRecord::Migration[5.1]
  def change
    create_table :gyms do |t|
      t.string :name
      t.string :address
      t.string :city
      t.string :country

      t.timestamps
    end
  end
end

I have created several rows for the table and according to my postgresql table they are fine. However, when I try to GET the json the name, city, address and country variables are not being returned.

The controller looks like this:

class GymsController < ApplicationController
  before_action :set_gym, only: [:show, :update, :destroy]
  # GET /gyms
  # GET /gyms.json
  def index
    @gyms = Gym.all
  end

  # GET /gyms/1
  # GET /gyms/1.json
  def show
  end

Why are only these values being returned?

{"id":1,"created_at":"2017-12-09T09:18:48.993Z","updated_at":"2017-12-09T09:18:48.993Z","url":"https://okuapp.com/gyms/1.json"}

And how can i make it so that all values are returned? (name, city, etc)

Before when i only had one table and there were no associations, this was not a problem.


问:
Checking if the class exists on Page using Jquery
I'm trying to check if a class exists using jquery. But something is not going well!
for example here's an HTML

```<code><div id="door">
  <!-- change this class to something else to test -->
  <div class="test alfa">
    <h1>Class "Test" Does Exist</h1>
  </div>
</div>
</code>```

How can I check that the class test exists

I'm trying the following if statement by not working for some reason. it may be something wrong with my code that I can't spot for some reason!

```<code>if ($('test')[0]) {
    $('h1').show();
} else {
  $('h1').text('Class "Test" Does NOT Exist');
}
</code>```

I would appreciate it if you can test this for me or let me know what's going wrong with the above statement!?

答:
You forgot a "." :</p>

```<code>if ($('.test')[0]) {
    $('h1').show();
} else {
  $('h1').text('Class "Test" Does NOT Exist');
}
</code>```

Body:
I'm trying to check if a class exists using jquery. But something is not going well!
for example here's an HTML

Class "Test" Does Exist

How can I check that the class test exists

I'm trying the following if statement by not working for some reason. it may be something wrong with my code that I can't spot for some reason!

if ($('test')[0]) {
    $('h1').show();
} else {
  $('h1').text('Class "Test" Does NOT Exist');
}

I would appreciate it if you can test this for me or let me know what's going wrong with the above statement!?

Body:
You forgot a "." :

if ($('.test')[0]) {
    $('h1').show();
} else {
  $('h1').text('Class "Test" Does NOT Exist');
}


答:
Because you defined f() after the invocation of it.

So it doesn't invoke the  f() function defined in the IIFE but the outter f() :

by reversing the order :

```<code>(function () {
    f = function () {
        console.log(8);
    }
    f();
})()
</code>```

you could have 8 and 8 as output as in both cases it invokes the overridden f() function.

Title: Execution order of anonymous function

Body:
Because you defined f() after the invocation of it.

So it doesn't invoke the  f() function defined in the IIFE but the outter f() :

by reversing the order :

(function () {
    f = function () {
        console.log(8);
    }
    f();
})()

you could have 8 and 8 as output as in both cases it invokes the overridden f() function.


答:
You need to add a dot to the test class</p>

```<code>if ($('.test')[0]) {
    $('h1').show();
} else {
  $('h1').text('Class "Test" Does NOT Exist');
}
</code>```

Title: Checking if the class exists on Page using Jquery

Body:
You need to add a dot to the test class

if ($('.test')[0]) {
    $('h1').show();
} else {
  $('h1').text('Class "Test" Does NOT Exist');
}


答:
You forgot putting . on selector

if ($('.test')[0]) {
    $('h1').show();
} else {
  $('h1').text('Class "Test" Does NOT Exist');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="door">
  <!-- change this class to something else to test -->
  <div class="test alfa">
    <h1>Class "Test" Does Exist</h1>
  </div>
</div></code>```

Body:
You forgot putting . on selector

if ($('.test')[0]) {
    $('h1').show();
} else {
  $('h1').text('Class "Test" Does NOT Exist');
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="door">
  <!-- change this class to something else to test -->
  <div class="test alfa">
    <h1>Class "Test" Does Exist</h1>
  </div>
</div>