问:
Creating a Dropdown Menu with CSS Not Working
The dropdown menu (sub) does not appear right below the element it is supposed to when I hover on the navbar. How can I get it to appear below it instead of to the right of it? Also, how can I get the extra spacing on the left side of each menu to disappear? I tried setting the padding to 0, but that did not change anything.

a {
    text-decoration: none;
    color: #000;
}

.navbar {
    background-color: #f2f2f2;
    position: fixed;
    top: 0;
    width: 100%;
    text-align: center;
    font-family: "Raleway";
    font-size: 93%;
    border-width:1px 0;
    list-style:none;
    margin:0;
    padding:0;
    left: 0;

}

.navbar > li{
    display:inline-block;

}

.navbar li {
    list-style-type: none;
    padding-left: none;
}

.navbar a {
    float: center;
    display:inline-block;
    color: #000000;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

.navbar a:hover {
    background-color: #ddd;

}

.navbar li:hover ul.sub {
display: inline-block;
}

.dropdown {
    position: relative;
    display: inline-block;
}

ul.sub {
    padding-left: none;
    position: absolute;
    background-color: #f9f9f9;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

ul.sub a {
    color: #000000;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <ul class = "navbar">
    <!--add dropdown menu links for everything except collaboration-->
    <li class = "dropdown">
        <li>About FRES(H)
        <ul class = "sub">
            <li>Safety</li>
            <li>Sense</li>
            <li>Express</li>
            <li>Keep Fresh</li>
            <li>Notebook</li>
            <li>Interlab</li>
            <li>Protocols</li>
        </ul>
        </li>
        </li>
    <li class = "dropdown">
        <li>Models
        <ul class = "sub">
            <li>Protein Modelling Etnr1</li>
            <li>Protein Modelling Etnr2</li>
            <li>Internal Cellular Model</li>
            <li>Macroscopic Diffusion Model</li>
            </ul>
            </li>
            </li>
    <li class = "dropdown">
        <li>Technology
        <ul class = "sub">
            <li>Primer Design App</li>
            <li>SmartPhone App</li>
            </ul>
            </li>
            </li>
    <li class = "dropdown">
        <li>Human-Centered Design
        <ul class = "sub">
            <li>Integrated Human Practices</li>
            <li>Outreach</li>
            <li>Theory of Knowledge</li>
            </ul>
            </li>
            </li>
    <li>Engagement</li>
    <li class = "dropdown">
        <li>Meet the Team
        <ul class = "sub">
            <li>About Us</li>
            <li>Attributions</li>
            </ul>
            </li>
            </li>
    <li class = "dropdown">
        <li>Awards
        <ul class = "sub">
            <li>Parts</li>
            <li>Medals</li>
            </ul>
            </li>
            </li>
    </ul></code>```

答:
You were almost there! You just added the :hover to the wrong div.

Make the following changes:
display:none to ul.sub and .navbar li:hover ul.sub instead of .navbar:hover ul.sub

UPDATE: to centre the ul.sub, use display: block. To remove padding, assign value of 0, instead of 'none'. See example below:

a {
    text-decoration: none;
    color: #000;
}

.navbar {
    background-color: #f2f2f2;
    position: fixed;
    top: 0;
    width: 100%;
    text-align: center;
    font-family: "Raleway";
    font-size: 93%;
    border-width:1px 0;
    list-style:none;
    margin:0;
    padding:0;
    left: 0;

}

.navbar > li{
    display:inline-block;

}

.navbar li {
    list-style-type: none;
    padding-left: none;
}

.navbar a {
    float: center;
    display:inline-block;
    color: #000000;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

.navbar a:hover {
    background-color: #ddd;

}

.navbar li:hover ul.sub {
display: block;
}

.dropdown {
    position: relative;
    display: inline-block;
}

ul.sub {
    padding-left: 0;
    position: absolute;
    background-color: #f9f9f9;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    display:none;
}

ul.sub a {
    color: #000000;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <ul class = "navbar">
    <!--add dropdown menu links for everything except collaboration-->
    <li class = "dropdown">
        <li>About FRES(H)
        <ul class = "sub">
            <li>Safety</li>
            <li>Sense</li>
            <li>Express</li>
            <li>Keep Fresh</li>
            <li>Notebook</li>
            <li>Interlab</li>
            <li>Protocols</li>
        </ul>
        </li>
        </li>
    <li class = "dropdown">
        <li>Models
        <ul class = "sub">
            <li>Protein Modelling Etnr1</li>
            <li>Protein Modelling Etnr2</li>
            <li>Internal Cellular Model</li>
            <li>Macroscopic Diffusion Model</li>
            </ul>
            </li>
            </li>
    <li class = "dropdown">
        <li>Technology
        <ul class = "sub">
            <li>Primer Design App</li>
            <li>SmartPhone App</li>
            </ul>
            </li>
            </li>
    <li class = "dropdown">
        <li>Human-Centered Design
        <ul class = "sub">
            <li>Integrated Human Practices</li>
            <li>Outreach</li>
            <li>Theory of Knowledge</li>
            </ul>
            </li>
            </li>
    <li>Engagement</li>
    <li class = "dropdown">
        <li>Meet the Team
        <ul class = "sub">
            <li>About Us</li>
            <li>Attributions</li>
            </ul>
            </li>
            </li>
    <li class = "dropdown">
        <li>Awards
        <ul class = "sub">
            <li>Parts</li>
            <li>Medals</li>
            </ul>
            </li>
            </li>
    </ul></code>```

Body:
The dropdown menu (sub) does not appear right below the element it is supposed to when I hover on the navbar. How can I get it to appear below it instead of to the right of it? Also, how can I get the extra spacing on the left side of each menu to disappear? I tried setting the padding to 0, but that did not change anything.

a {
    text-decoration: none;
    color: #000;
}

.navbar {
    background-color: #f2f2f2;
    position: fixed;
    top: 0;
    width: 100%;
    text-align: center;
    font-family: "Raleway";
    font-size: 93%;
    border-width:1px 0;
    list-style:none;
    margin:0;
    padding:0;
    left: 0;

}

.navbar > li{
    display:inline-block;

}

.navbar li {
    list-style-type: none;
    padding-left: none;
}

.navbar a {
    float: center;
    display:inline-block;
    color: #000000;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

.navbar a:hover {
    background-color: #ddd;

}

.navbar li:hover ul.sub {
display: inline-block;
}

.dropdown {
    position: relative;
    display: inline-block;
}

ul.sub {
    padding-left: none;
    position: absolute;
    background-color: #f9f9f9;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

ul.sub a {
    color: #000000;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

About FRES(H)

Safety

Sense

Express

Keep Fresh

Notebook

Interlab

Protocols

Models

Protein Modelling Etnr1

Protein Modelling Etnr2

Internal Cellular Model

Macroscopic Diffusion Model

Technology

Primer Design App

SmartPhone App

Human-Centered Design

Integrated Human Practices

Outreach

Theory of Knowledge

Engagement

Meet the Team

About Us

Attributions

Awards

Parts

Medals

Body:
You were almost there! You just added the :hover to the wrong div.

Make the following changes:
display:none to ul.sub and .navbar li:hover ul.sub instead of .navbar:hover ul.sub

UPDATE: to centre the ul.sub, use display: block. To remove padding, assign value of 0, instead of 'none'. See example below:

a {
    text-decoration: none;
    color: #000;
}

.navbar {
    background-color: #f2f2f2;
    position: fixed;
    top: 0;
    width: 100%;
    text-align: center;
    font-family: "Raleway";
    font-size: 93%;
    border-width:1px 0;
    list-style:none;
    margin:0;
    padding:0;
    left: 0;

}

.navbar > li{
    display:inline-block;

}

.navbar li {
    list-style-type: none;
    padding-left: none;
}

.navbar a {
    float: center;
    display:inline-block;
    color: #000000;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

.navbar a:hover {
    background-color: #ddd;

}

.navbar li:hover ul.sub {
display: block;
}

.dropdown {
    position: relative;
    display: inline-block;
}

ul.sub {
    padding-left: 0;
    position: absolute;
    background-color: #f9f9f9;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    display:none;
}

ul.sub a {
    color: #000000;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

 <ul class = "navbar">
    <!--add dropdown menu links for everything except collaboration-->
    <li class = "dropdown">
        <li><a href ="project.html">About FRES(H)</a>
        <ul class = "sub">
            <li><a href = "safety.html">Safety</a></li>
            <li><a href = "sense.html">Sense</a></li>
            <li><a href = "express.html">Express</a></li>
            <li><a href = "fresh.html">Keep Fresh</a></li>
            <li><a href = "notebook.html">Notebook</a></li>
            <li><a href = "interlab.html">Interlab</a></li>
            <li><a href = "protocols.html">Protocols</a></li>
        </ul>
        </li>
        </li>
    <li class = "dropdown">
        <li><a href ="modelling.html">Models</a>
        <ul class = "sub">
            <li><a href = "etnr1.html">Protein Modelling Etnr1</a></li>
            <li><a href = "etnr2.html">Protein Modelling Etnr2</a></li>
            <li><a href = "internal.html">Internal Cellular Model</a></li>
            <li><a href = "diffusion.html">Macroscopic Diffusion Model</a></li>
            </ul>
            </li>
            </li>
    <li class = "dropdown">
        <li><a href ="software.html">Technology</a>
        <ul class = "sub">
            <li><a href = "primer.html">Primer Design App</a></li>
            <li><a href = "smartphone.html">SmartPhone App</a></li>
            </ul>
            </li>
            </li>
    <li class = "dropdown">
        <li><a href ="humanpractices.html">Human-Centered Design</a>
        <ul class = "sub">
            <li><a href = "human.html">Integrated Human Practices</a></li>
            <li><a href = "outreach.html">Outreach</a></li>
            <li><a href = "knowledgetheory.html">Theory of Knowledge</a></li>
            </ul>
            </li>
            </li>
    <li><a href ="http://2016.igem.org/Team:Sydney_Australia/Collaboration">Engagement</a></li>
    <li class = "dropdown">
        <li><a href ="team.html">Meet the Team</a>
        <ul class = "sub">
            <li><a href = "about.html">About Us</a></li>
            <li><a href = "attributions.html">Attributions</a></li>
            </ul>
            </li>
            </li>
    <li class = "dropdown">
        <li><a href ="achievements.html">Awards</a>
        <ul class = "sub">
            <li><a href = "parts.html">Parts</a></li>
            <li><a href = "medals.html">Medals</a></li>
            </ul>
            </li>
            </li>
    </ul>


来源: stackexchange

问:
tan inverse in matlab not giving correct values
As a part of a longer code, I get a quantity phi1 and phi2 (matrices of size 128x128) which are the arguments of a complex quantity. Now I define the following quantities in MATLAB:

```<code>alpha=phi1-phi2;
S1=cos(alpha);
S2=sin(alpha);
K=atan2(S2,S1);
</code>```

Now, K should be equal to alpha. Therefore, the matrix B defined as:

```<code>B=K-alpha;
</code>```

should be zero.But the result is coming out to be different. Though several elements of B are zero, a lot of them have the value 6.2832 (i.e 2pi).
Why this could be happening?

答:
The atan2 function always returns values between -pi and pi. So, for example, for alpha = 4 your code

```<code>S1=cos(alpha);
S2=sin(alpha);
K=atan2(S2,S1)
</code>```

gives

```<code>K =
  -2.2832
</code>```

which is alpha but moved (modulo 2*pi) to the interval between -pi and pi.

This shouldn't be a problem, because two angles that differ by 2*pi are actually the same. So a possible solution is to compare the angles by doing the subtraction modulo 2*pi:

```<code>>> mod(alpha-K, 2*pi)
ans =
     0
</code>```

Note also that, due to numerical rounding errors, you should not rely on the difference modulo 2*pi being exactly 0. Instead, compare its absolute value to a given tolerance.

ContentLicense: CC BY-SA 3.0

Body:
As a part of a longer code, I get a quantity phi1 and phi2 (matrices of size 128x128) which are the arguments of a complex quantity. Now I define the following quantities in MATLAB:

alpha=phi1-phi2;
S1=cos(alpha);
S2=sin(alpha);
K=atan2(S2,S1);

Now, K should be equal to alpha. Therefore, the matrix B defined as:

B=K-alpha;

should be zero.But the result is coming out to be different. Though several elements of B are zero, a lot of them have the value 6.2832 (i.e 2pi).
Why this could be happening?

Body:
The atan2 function always returns values between -pi and pi. So, for example, for alpha = 4 your code

S1=cos(alpha);
S2=sin(alpha);
K=atan2(S2,S1)

gives

K =
  -2.2832

which is alpha but moved (modulo 2*pi) to the interval between -pi and pi.

This shouldn't be a problem, because two angles that differ by 2*pi are actually the same. So a possible solution is to compare the angles by doing the subtraction modulo 2*pi:

>> mod(alpha-K, 2*pi)
ans =
     0

Note also that, due to numerical rounding errors, you should not rely on the difference modulo 2*pi being exactly 0. Instead, compare its absolute value to a given tolerance.


问:
XCode: comment out code in javascript file
I normally comment and uncomment code with XCode using this command:
(command+slash)

This works just fine for swift file, but it does NOT work for javascript files. Is there way I can configure XCode to do this for all files?

答:
I don't think it's possible to extend the standard comment out command to Javascript as well, sorry :-(

Having said that, you could try adding a custom shortcut following these steps. (But might be tricky to completely reproduce the native comment out behavior.)


问:
Django CSRF when backend and frontend are separated
After searching the internet, people normally deal with this situation---the front-end is generated by django view function which can send user the cookie of csrf token. When user has a request to server using ajax, people can rewrite the ajaxSend behavior which send the csrf to server.

However, my situation is that my front-end is totally separated from back-end, ie, my front-end is in a dedicated server running nginx, and I only have one html providing all of the different pages using hashbang. My back-end is running in different server using different domain name, and in this case, how does client obtain the csrf cookie? My back-end only provided json api return.

Thank you.

答:
Lets say, frontend has the domain frontend.example.com, and backend domain backend.example.com. (If you are something like Django rest framework)
If you can use there are two ways you can enable security layer i.e.,. CSRF Protection or CORS

For CORS,

```<code>pip install django-cors-headers
</code>```

and then configuring this to INSTALLED_APPS, MIDDLEWARE_CLASSES and add the frontend domain to CORS_ORIGIN_WHITELIST.

```<code>CORS_ORIGIN_WHITELIST = (
    'frontend.example.com'
)
</code>```

CORS will block any http request arising from any domains other than frontend.example.com

For CSRF,

```<code>CSRF_COOKIE_DOMAIN = ".mydomain.com"
</code>```

and if you are using an Angular App, do like below,

```<code>$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$httpProvider.defaults.withCredentials = true;
</code>```

and then add headers while make a http request.

```<code>headers : {
    "x-csrftoken" : $cookies.csrftoken
}
</code>```

Body:
Lets say, frontend has the domain frontend.example.com, and backend domain backend.example.com. (If you are something like Django rest framework)
If you can use there are two ways you can enable security layer i.e.,. CSRF Protection or CORS

For CORS,

pip install django-cors-headers

and then configuring this to INSTALLED_APPS, MIDDLEWARE_CLASSES and add the frontend domain to CORS_ORIGIN_WHITELIST.

CORS_ORIGIN_WHITELIST = (
    'frontend.example.com'
)

CORS will block any http request arising from any domains other than frontend.example.com

For CSRF,

CSRF_COOKIE_DOMAIN = ".mydomain.com"

and if you are using an Angular App, do like below,

$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$httpProvider.defaults.withCredentials = true;

and then add headers while make a http request.

headers : {
    "x-csrftoken" : $cookies.csrftoken
}


问:
How to change SQL-SERVER table column name encoding?
I'm in a project of creating a Japanese website using Laravel 5.4.

The database is SQL-SERVER 2014,
and the name of columns in almost all tables are in Japanese.

The problem is
in the result Laravel retrieves from those tables in SQL-SERVER,
the column names are in SJIS while the table contents is in UTF-8.

Is it possible for Laravel to serialize those SJIS column names to model properties without hurting the UTF-8 contents?

Or is it possible to change the encoding of the column name in SQL-SERVER?

Thank you.

[UPDATED]
I am sorry. Here is part of the returned.

```<code>object(Illuminate\Database\Eloquent\Collection)#226 (1) {
  ["items":protected]=>
  array(1) {
    [0]=>
    object(App\Foo)#233 (24) {
      ["table":protected]=>
      string(7) "Foo"
      ["fillable":protected]=>
      array(2) {
        [0]=>
        string(9) "コード"
        [1]=>
        string(6) "部門"
      }
      ["connection":protected]=>
      NULL
      ["primaryKey":protected]=>
      string(2) "id"
      ["keyType":protected]=>
      string(3) "int"
      ["incrementing"]=>
      bool(true)
      ["with":protected]=>
      array(0) {
      }
      ["perPage":protected]=>
      int(15)
      ["exists"]=>
      bool(true)
      ["wasRecentlyCreated"]=>
      bool(false)
      ["attributes":protected]=>
      array(8) {
        ["�R�[�h"]=>
        string(2) "11"
        ["����"]=>
        string(15) "日本語テスト"
        ["����"]=>
        string(24) "ﾃｽﾄ"
        ["������"]=>
        string(4) "70.0"
        ["�啪��"]=>
        string(2) "01"
        ["������"]=>
        string(2) "01"
        ["����"]=>
        string(2) "01"
        ["�ŗ�"]=>
        string(1) "8"
      }
      ["original":protected]=>
      array(8) {
        ["�R�[�h"]=>
        string(2) "11"
        ["����"]=>
        string(15) "日本語test"
        ["����"]=>
        string(24) "ｱｲｳｴｵ"
        ["������"]=>
        string(4) "70.0"
        ["�啪��"]=>
        string(2) "01"
        ["������"]=>
        string(2) "01"
        ["����"]=>
        string(2) "01"
        ["�ŗ�"]=>
        string(1) "8"
      }
      ["casts":protected]=>
      array(0) {
      }
      ["dates":protected]=>
      array(0) {
      }
      ["dateFormat":protected]=>
      NULL
      ["appends":protected]=>
      array(0) {
      }
      ["events":protected]=>
      array(0) {
      }
      ["observables":protected]=>
      array(0) {
      }
      ["relations":protected]=>
      array(0) {
      }
      ["touches":protected]=>
      array(0) {
      }
      ["timestamps"]=>
      bool(true)
      ["hidden":protected]=>
      array(0) {
      }
      ["visible":protected]=>
      array(0) {
      }
      ["guarded":protected]=>
      array(1) {
        [0]=>
        string(1) "*"
      }
    }
  }
}
</code>```

In the attributes like

```<code>["����"]=>
string(15) "日本語テスト"
</code>```

"����"

is in SJIS and cannot be converted to propery.

"日本語テスト"

is in UTF-8 and is readable.

答:
Look at collations, you can apply it per database and per column
https://learn.microsoft.com/en-us/sql/t-sql/statements/collations</p>

Body:
I'm in a project of creating a Japanese website using Laravel 5.4.

The database is SQL-SERVER 2014,
and the name of columns in almost all tables are in Japanese.

The problem is
in the result Laravel retrieves from those tables in SQL-SERVER,
the column names are in SJIS while the table contents is in UTF-8.

Is it possible for Laravel to serialize those SJIS column names to model properties without hurting the UTF-8 contents?

Or is it possible to change the encoding of the column name in SQL-SERVER?

Thank you.

[UPDATED]
I am sorry. Here is part of the returned.

object(Illuminate\Database\Eloquent\Collection)#226 (1) {
  ["items":protected]=>
  array(1) {
    [0]=>
    object(App\Foo)#233 (24) {
      ["table":protected]=>
      string(7) "Foo"
      ["fillable":protected]=>
      array(2) {
        [0]=>
        string(9) "コード"
        [1]=>
        string(6) "部門"
      }
      ["connection":protected]=>
      NULL
      ["primaryKey":protected]=>
      string(2) "id"
      ["keyType":protected]=>
      string(3) "int"
      ["incrementing"]=>
      bool(true)
      ["with":protected]=>
      array(0) {
      }
      ["perPage":protected]=>
      int(15)
      ["exists"]=>
      bool(true)
      ["wasRecentlyCreated"]=>
      bool(false)
      ["attributes":protected]=>
      array(8) {
        ["�R�[�h"]=>
        string(2) "11"
        ["����"]=>
        string(15) "日本語テスト"
        ["����"]=>
        string(24) "ﾃｽﾄ"
        ["������"]=>
        string(4) "70.0"
        ["�啪��"]=>
        string(2) "01"
        ["������"]=>
        string(2) "01"
        ["����"]=>
        string(2) "01"
        ["�ŗ�"]=>
        string(1) "8"
      }
      ["original":protected]=>
      array(8) {
        ["�R�[�h"]=>
        string(2) "11"
        ["����"]=>
        string(15) "日本語test"
        ["����"]=>
        string(24) "ｱｲｳｴｵ"
        ["������"]=>
        string(4) "70.0"
        ["�啪��"]=>
        string(2) "01"
        ["������"]=>
        string(2) "01"
        ["����"]=>
        string(2) "01"
        ["�ŗ�"]=>
        string(1) "8"
      }
      ["casts":protected]=>
      array(0) {
      }
      ["dates":protected]=>
      array(0) {
      }
      ["dateFormat":protected]=>
      NULL
      ["appends":protected]=>
      array(0) {
      }
      ["events":protected]=>
      array(0) {
      }
      ["observables":protected]=>
      array(0) {
      }
      ["relations":protected]=>
      array(0) {
      }
      ["touches":protected]=>
      array(0) {
      }
      ["timestamps"]=>
      bool(true)
      ["hidden":protected]=>
      array(0) {
      }
      ["visible":protected]=>
      array(0) {
      }
      ["guarded":protected]=>
      array(1) {
        [0]=>
        string(1) "*"
      }
    }
  }
}

In the attributes like

["����"]=>
string(15) "日本語テスト"

"����"

is in SJIS and cannot be converted to propery.

"日本語テスト"

is in UTF-8 and is readable.


问:
How to stop an animation onBackPressed?
In my MainActivity I have 2 animations (FAB and a TAB title) and I would like to stop them onBackPressed.

```<code>@Bind(R.id.fab_text) Button mFAB;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_drawer);

    Animation animation = loadAnimation(MainDrawerActivity.this, R.anim.fab_scale_up_down);
    animation.setRepeatCount(Animation.INFINITE);
    animation.setAnimationListener(new SimpleAnimationListener() {
        private long offset;
        private long startTime;

        @Override
        public void onAnimationStart(Animation animation) {
            startTime = System.currentTimeMillis();
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            final long now = System.currentTimeMillis();
            Timber.i("onAnimationRepeatFAB: elapeed seconds: %d", (now - startTime) / 1000);
            if ((now - startTime > 7000) && (offset % 4 == 0)) { // stop animation after X seconds
                animation.setRepeatCount(0);
            } else {
                offset++;
                animation.setStartOffset(offset % 4 == 0 ? 700 : 0);
            }
        }
    });
    mFAB.startAnimation(animation);
</code>```

About the FAB it's easy.

```<code>public void onBackPressed() {
    mFAB.clearAnimation();
</code>```

But how do I stop the other animation defined like this? I don't know how to access the animation of the TAB below.

```<code>private void populateViewPager(List<Tab> tabs) {
    // clear all listeners before populating new tabs
    mTabLayout.setOnTabSelectedListener(null);
    mViewPager.clearOnPageChangeListeners();

    if (mPagerAdapter == null) {
        mPagerAdapter = new TabsPagerAdapter(this, getSupportFragmentManager());
        mViewPager.setAdapter(mPagerAdapter);
    }

    // populate tabs
    mPagerAdapter.setTabs(tabs);
    if (mPagerAdapter.getCount() > DEFAULT_TAB_POSITION)
        mViewPager.setCurrentItem(DEFAULT_TAB_POSITION);
    mTabLayout.setupWithViewPager(mViewPager);

    // set animation on corresponding tabs
    List<Tab> pagerTabs = mPagerAdapter.getTabs();
    for (int i = 0; i < pagerTabs.size(); i++) {
        Tab pagerTab = pagerTabs.get(i);
        if (pagerTab.isAnimated()) {
            Timber.i("Animating tab: %s", pagerTab.getId());
            TabLayout.Tab tab = mTabLayout.getTabAt(i);
            if (tab != null) {
                // set custom view in order to get it back then
                tab.setCustomView(R.layout.partial_tab_view);

                // set animation on the custom view
                Animation animation = loadAnimation(MainDrawerActivity.this, R.anim.tab_scale_up_down);
                animation.setRepeatCount(Animation.INFINITE);
                animation.setAnimationListener(new SimpleAnimationListener() {
                    private long offset;
                    private long startTime;

                    @Override
                    public void onAnimationStart(Animation animation) {
                        startTime = System.currentTimeMillis();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                        final long now = System.currentTimeMillis();
                        Timber.i("onAnimationRepeat: elapeed seconds: %d", (now - startTime) / 1000);
                        if ((now - startTime > 7000) && (offset % 4 == 0)) { // stop animation after X seconds
                            animation.setRepeatCount(0);
                        } else {
                            offset++;
                            animation.setStartOffset(offset % 4 == 0 ? 700 : 0);
                        }
                    }
                });
                //noinspection ConstantConditions
                tab.getCustomView().setAnimation(animation);
            } else {
                Timber.w("tab!=null");
            }
        }
    }
}
</code>```

答: Store a reference to your Animation, then call cancel() on the Animation.

Title: How to stop an animation onBackPressed?

Body:
In my MainActivity I have 2 animations (FAB and a TAB title) and I would like to stop them onBackPressed.

@Bind(R.id.fab_text) Button mFAB;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_drawer);

    Animation animation = loadAnimation(MainDrawerActivity.this, R.anim.fab_scale_up_down);
    animation.setRepeatCount(Animation.INFINITE);
    animation.setAnimationListener(new SimpleAnimationListener() {
        private long offset;
        private long startTime;

        @Override
        public void onAnimationStart(Animation animation) {
            startTime = System.currentTimeMillis();
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            final long now = System.currentTimeMillis();
            Timber.i("onAnimationRepeatFAB: elapeed seconds: %d", (now - startTime) / 1000);
            if ((now - startTime > 7000) && (offset % 4 == 0)) { // stop animation after X seconds
                animation.setRepeatCount(0);
            } else {
                offset++;
                animation.setStartOffset(offset % 4 == 0 ? 700 : 0);
            }
        }
    });
    mFAB.startAnimation(animation);

About the FAB it's easy.

public void onBackPressed() {
    mFAB.clearAnimation();

But how do I stop the other animation defined like this? I don't know how to access the animation of the TAB below.

private void populateViewPager(List<Tab> tabs) {
    // clear all listeners before populating new tabs
    mTabLayout.setOnTabSelectedListener(null);
    mViewPager.clearOnPageChangeListeners();

    if (mPagerAdapter == null) {
        mPagerAdapter = new TabsPagerAdapter(this, getSupportFragmentManager());
        mViewPager.setAdapter(mPagerAdapter);
    }

    // populate tabs
    mPagerAdapter.setTabs(tabs);
    if (mPagerAdapter.getCount() > DEFAULT_TAB_POSITION)
        mViewPager.setCurrentItem(DEFAULT_TAB_POSITION);
    mTabLayout.setupWithViewPager(mViewPager);

    // set animation on corresponding tabs
    List<Tab> pagerTabs = mPagerAdapter.getTabs();
    for (int i = 0; i < pagerTabs.size(); i++) {
        Tab pagerTab = pagerTabs.get(i);
        if (pagerTab.isAnimated()) {
            Timber.i("Animating tab: %s", pagerTab.getId());
            TabLayout.Tab tab = mTabLayout.getTabAt(i);
            if (tab != null) {
                // set custom view in order to get it back then
                tab.setCustomView(R.layout.partial_tab_view);

                // set animation on the custom view
                Animation animation = loadAnimation(MainDrawerActivity.this, R.anim.tab_scale_up_down);
                animation.setRepeatCount(Animation.INFINITE);
                animation.setAnimationListener(new SimpleAnimationListener() {
                    private long offset;
                    private long startTime;

                    @Override
                    public void onAnimationStart(Animation animation) {
                        startTime = System.currentTimeMillis();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                        final long now = System.currentTimeMillis();
                        Timber.i("onAnimationRepeat: elapeed seconds: %d", (now - startTime) / 1000);
                        if ((now - startTime > 7000) && (offset % 4 == 0)) { // stop animation after X seconds
                            animation.setRepeatCount(0);
                        } else {
                            offset++;
                            animation.setStartOffset(offset % 4 == 0 ? 700 : 0);
                        }
                    }
                });
                //noinspection ConstantConditions
                tab.getCustomView().setAnimation(animation);
            } else {
                Timber.w("tab!=null");
            }
        }
    }
}


问:
Null pointer exception while trying to display a listview in a fragment inside a tab
I want to show a list view that contains images,text,numbers in a fragment in a

tab. The name of the fragment is "home1.java" .

I have a method displaydatabaseinfo() in mainactivity.java which serves the purpose.

There is also a class named "TabFragment.java" which controls the flow.

The line " ListView lvlogItems = (ListView)  findViewById(R.id.listView);" is returning a null and hence the data is not being shown.

This is the following error

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.chven.swipeviewtest/com.example.chven.swipeviewtest.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
</code>```

Below is the code for method mainactivity.java

```<code>public class MainActivity extends AppCompatActivity {

LogReader LogReader1 = new LogReader(this);
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTrasaction;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {
        get();
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    mNavigationView = (NavigationView) findViewById(R.id.shitstuff);
    mFragmentManager = getSupportFragmentManager();
    mFragmentTrasaction = mFragmentManager.beginTransaction();
    mFragmentTrasaction.replace(R.id.containerView, new TabFragment()).commit();
   displayDatabaseInfo();
}

public void displayDatabaseInfo() {
    // To access our database, we instantiate our subclass of SQLiteOpenHelper
    // and pass the context, which is the current activity.
    SQLiteDatabase db = LogReader1.getReadableDatabase();
    Cursor logCursor = db.rawQuery("SELECT rowid _id,name,Time_Used,app_Image FROM logs ORDER BY Time_Used DESC", null);
    LogCursorAdapter logAdapter = new LogCursorAdapter(this, logCursor);
    ListView lvlogItems = (ListView)  findViewById(R.id.listView);
    lvlogItems.setAdapter((logAdapter));
}
</code>```

This is the code for the fragment "home1.java"

```<code>public class home1 extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

public home1() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment home1.
 */
// TODO: Rename and change types and number of parameters
public static home1 newInstance(String param1, String param2) {
    home1 fragment = new home1();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    return inflater.inflate(R.layout.fragment_home1, container, false);

}
</code>```

}

This is the code for "TabFragment.java"

```<code>public class TabFragment extends Fragment {

public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 1;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View x = inflater.inflate(R.layout.tab_layout, null);
    tabLayout = (TabLayout) x.findViewById(R.id.tabs);
    viewPager = (ViewPager) x.findViewById(R.id.viewpager);

    viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
    tabLayout.post(new Runnable() {
        @Override
        public void run() {
            tabLayout.setupWithViewPager(viewPager);
        }
    });
    return x;
}
class MyAdapter extends FragmentPagerAdapter{

    public MyAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position)
    {
        switch (position) {
            case 0 : return new home1();

        }
        return null;
    }

    @Override
    public int getCount() {

        return int_items;
    }

    @Override
    public CharSequence getPageTitle(int position) {

        switch (position){
            case 0 :
                return "Home";

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

}

答: I'd suggest moving your call to displayDatabaseInfo() into the onResume() of the Activity: you're probably getting a null pointer because onCreateView in the fragment hasn't yet been called.

Body:
I want to show a list view that contains images,text,numbers in a fragment in a

tab. The name of the fragment is "home1.java" .

I have a method displaydatabaseinfo() in mainactivity.java which serves the purpose.

There is also a class named "TabFragment.java" which controls the flow.

The line " ListView lvlogItems = (ListView)  findViewById(R.id.listView);" is returning a null and hence the data is not being shown.

This is the following error

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.chven.swipeviewtest/com.example.chven.swipeviewtest.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

Below is the code for method mainactivity.java

public class MainActivity extends AppCompatActivity {

LogReader LogReader1 = new LogReader(this);
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTrasaction;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {
        get();
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    mNavigationView = (NavigationView) findViewById(R.id.shitstuff);
    mFragmentManager = getSupportFragmentManager();
    mFragmentTrasaction = mFragmentManager.beginTransaction();
    mFragmentTrasaction.replace(R.id.containerView, new TabFragment()).commit();
   displayDatabaseInfo();
}

public void displayDatabaseInfo() {
    // To access our database, we instantiate our subclass of SQLiteOpenHelper
    // and pass the context, which is the current activity.
    SQLiteDatabase db = LogReader1.getReadableDatabase();
    Cursor logCursor = db.rawQuery("SELECT rowid _id,name,Time_Used,app_Image FROM logs ORDER BY Time_Used DESC", null);
    LogCursorAdapter logAdapter = new LogCursorAdapter(this, logCursor);
    ListView lvlogItems = (ListView)  findViewById(R.id.listView);
    lvlogItems.setAdapter((logAdapter));
}

This is the code for the fragment "home1.java"

public class home1 extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

public home1() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment home1.
 */
// TODO: Rename and change types and number of parameters
public static home1 newInstance(String param1, String param2) {
    home1 fragment = new home1();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    return inflater.inflate(R.layout.fragment_home1, container, false);

}

}

This is the code for "TabFragment.java"

public class TabFragment extends Fragment {

public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 1;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View x = inflater.inflate(R.layout.tab_layout, null);
    tabLayout = (TabLayout) x.findViewById(R.id.tabs);
    viewPager = (ViewPager) x.findViewById(R.id.viewpager);

    viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
    tabLayout.post(new Runnable() {
        @Override
        public void run() {
            tabLayout.setupWithViewPager(viewPager);
        }
    });
    return x;
}
class MyAdapter extends FragmentPagerAdapter{

    public MyAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position)
    {
        switch (position) {
            case 0 : return new home1();

        }
        return null;
    }

    @Override
    public int getCount() {

        return int_items;
    }

    @Override
    public CharSequence getPageTitle(int position) {

        switch (position){
            case 0 :
                return "Home";

        }
        return null;
    }
}

}


问:
extract specific data from numpy ndarray
New to pandas any help is appreciated

```<code>def csv_reader(fileName):
    reqcols=['_id__$oid','payload','channel']
    io = pd.read_csv(fileName,sep=",",usecols=reqcols)
    print(io['payload'].values)
    return io
</code>```

Output row of io['payload']:

```<code>{
    "destination_ip": "172.31.14.66",
    "date": "2014-10-19T01:32:36.669861",
    "classification": "Potentially Bad Traffic",
    "proto": "UDP",
    "source_ip": "172.31.0.2",
    "priority": "`2",
    "header": "1:2003195:5",
    "signature": "ET POLICY Unusual number of DNS No Such Name Responses ",
    "source_port": "53",
    "destination_port": "34638",
    "sensor": "5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"
}
</code>```

I am trying to extract specific data from the ndarray object. What is the method that can be used to extract from the dataframe

```<code>"destination_ip": "172.31.13.124",
"proto": "ICMP",
"source_ip": "201.158.32.1",
"date": "2014-09-28T14:49:43.391463",
"sensor": "139cfdf2-471e-11e4-9ee4-0a0b6e7c3e9e"
</code>```

答:
It is fairly straight forward to access columns in pandas.  Simply pass a list of the columns you need:

Code:

```<code>columns = ["destination_ip", "proto", "source_ip", "date", "sensor"]
extracted_data = df[columns]
</code>```

Test Code:

```<code>data = {
    "destination_ip": "172.31.14.66",
    "date": "2014-10-19T01:32:36.669861",
    "classification": "Potentially Bad Traffic",
    "proto": "UDP",
    "source_ip": "172.31.0.2",
    "priority": "`2",
    "header": "1:2003195:5",
    "signature": "ET POLICY Unusual number of DNS No Such Name Responses ",
    "source_port": "53",
    "destination_port": "34638",
    "sensor": "5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"
}
df = pd.DataFrame([data, data])

columns = ["destination_ip", "proto", "source_ip", "date", "sensor"]
print(df[columns])
</code>```

Results:

```<code>  destination_ip proto   source_ip                        date  \
0   172.31.14.66   UDP  172.31.0.2  2014-10-19T01:32:36.669861
1   172.31.14.66   UDP  172.31.0.2  2014-10-19T01:32:36.669861

                                 sensor
0  5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e
1  5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e
</code>```

Body:
New to pandas any help is appreciated

def csv_reader(fileName):
    reqcols=['_id__$oid','payload','channel']
    io = pd.read_csv(fileName,sep=",",usecols=reqcols)
    print(io['payload'].values)
    return io

Output row of io['payload']:

{
    "destination_ip": "172.31.14.66",
    "date": "2014-10-19T01:32:36.669861",
    "classification": "Potentially Bad Traffic",
    "proto": "UDP",
    "source_ip": "172.31.0.2",
    "priority": "`2",
    "header": "1:2003195:5",
    "signature": "ET POLICY Unusual number of DNS No Such Name Responses ",
    "source_port": "53",
    "destination_port": "34638",
    "sensor": "5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"
}

I am trying to extract specific data from the ndarray object. What is the method that can be used to extract from the dataframe

"destination_ip": "172.31.13.124",
"proto": "ICMP",
"source_ip": "201.158.32.1",
"date": "2014-09-28T14:49:43.391463",
"sensor": "139cfdf2-471e-11e4-9ee4-0a0b6e7c3e9e"

Body:
It is fairly straight forward to access columns in pandas.  Simply pass a list of the columns you need:

Code:

columns = ["destination_ip", "proto", "source_ip", "date", "sensor"]
extracted_data = df[columns]

Test Code:

data = {
    "destination_ip": "172.31.14.66",
    "date": "2014-10-19T01:32:36.669861",
    "classification": "Potentially Bad Traffic",
    "proto": "UDP",
    "source_ip": "172.31.0.2",
    "priority": "`2",
    "header": "1:2003195:5",
    "signature": "ET POLICY Unusual number of DNS No Such Name Responses ",
    "source_port": "53",
    "destination_port": "34638",
    "sensor": "5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"
}
df = pd.DataFrame([data, data])

columns = ["destination_ip", "proto", "source_ip", "date", "sensor"]
print(df[columns])

Results:

  destination_ip proto   source_ip                        date  \
0   172.31.14.66   UDP  172.31.0.2  2014-10-19T01:32:36.669861
1   172.31.14.66   UDP  172.31.0.2  2014-10-19T01:32:36.669861

                                 sensor
0  5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e
1  5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e


问:
JQuery Tabs & cookie plugins - 2 tabs highlighted
I'm using jquery with tabs plugin and the cookie plugin to remember the previously selected tab.
However, when the page is opened again it successfully remembers the last tab selected but then when a new tab is chosen both the new and the old one are highlighted.
When another is selected then it just highlights that one.

```<code>$("#tabs").tabs({ cookie: { name: 'selectedTab', expires: 300 }});
</code>```

Can anyone suggest a solution please?
Thanks

答:
As I commented, I would need to see more of you code to be sure, but my initial guess would be that you're probably highlighting the selected tabs using a CSS class.  You have to make sure that you are also REMOVING that class from anywhere that it's already applied before applying it.

Similar to this:

```<code>$('.tab').click(function() {
    // First remove your highlight class from any tabs already highlighted
    $('.selectedTabHighlightClass').removeClass('selectedTabHighlightClass');

    // Then add the class to the newly selected tab
    $(this).addClass('selectedTabHighlightClass');
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm using jquery with tabs plugin and the cookie plugin to remember the previously selected tab.
However, when the page is opened again it successfully remembers the last tab selected but then when a new tab is chosen both the new and the old one are highlighted.
When another is selected then it just highlights that one.

$("#tabs").tabs({ cookie: { name: 'selectedTab', expires: 300 }});

Can anyone suggest a solution please?
Thanks

Body:
As I commented, I would need to see more of you code to be sure, but my initial guess would be that you're probably highlighting the selected tabs using a CSS class.  You have to make sure that you are also REMOVING that class from anywhere that it's already applied before applying it.

Similar to this:

$('.tab').click(function() {
    // First remove your highlight class from any tabs already highlighted
    $('.selectedTabHighlightClass').removeClass('selectedTabHighlightClass');

    // Then add the class to the newly selected tab
    $(this).addClass('selectedTabHighlightClass');
});


问:
Why do we still need parser like BeautifulSoup if we can use Selenium?
I am currently using Selenium to crawl data from some websites. Unlike urllib, it seems that I do not really need a parser like BeautifulSoup to parse the HTML. I can simply find an element with Selenium and use Webelement.text to get the data that I need. As I saw there are some people using Selenium and BeautifulSoup together in web crawling. Is it really necessary? Any special features that bs4 can offer to improve the crawling process? Thank you.</p>

答:
Selenium itself is quite powerful in terms of locating elements and, it basically has everything you need for extracting data from HTML. The problem is, it is slow. Every single selenium command goes through the JSON wire HTTP protocol and there is a substantial overhead.

In order to improve the performance of the HTML parsing part, it is usually much faster to let BeautifulSoup or lxml parse the page source retrieved from .page_source.

In other words, a common workflow for a dynamic web page is something like:

open the page in a browser controlled by selenium

make the necessary browser actions

once the desired data is on the page, get the driver.page_source and close the browser

pass the page source to an HTML parser for further parsing

ContentLicense: CC BY-SA 4.0


问:
Fatal error: Class 'Magento_Db_Adapter_Pdo_Mysql' not found in /home/xxxx/public_html/xx/xx/includes/src/__default.php on line 29313
i just did all these solution but failed to get solution

777 permission to your magento folder.

chmod 775 lib/Magento/Db/Adapter/Pdo/Mysql.php

答:
Please check this and also this

Also enable pdo extension on your server

You need to enable the PDO and PDO_MYSQL extensions in your php.ini file.
go to your  php.ini file Which is located inside the directory where PHP was installed and remove the comments (;) in the lines bellow so

```<code>;extension=php_pdo.dll to  extension=php_pdo.dll
</code>```

On a windows server you can add the following lines in your php.ini

```<code>extension=php_pdo.dll
extension=php_pdo_mysql.dll
</code>```

On a Linux server you can compile php with the following option --with-pdo-mysql In your php.ini, add the following lines

```<code>extension=pdo.so
extension=pdo_mysql.so
</code>```

some webhosts don't allow to edit the php ini directly so you need to talk to them to give you this permission, or them uncomment these lines I posted in php.ini file

Body:
Please check this and also this

Also enable pdo extension on your server

You need to enable the PDO and PDO_MYSQL extensions in your php.ini file.
go to your  php.ini file Which is located inside the directory where PHP was installed and remove the comments (;) in the lines bellow so

;extension=php_pdo.dll to  extension=php_pdo.dll

On a windows server you can add the following lines in your php.ini

extension=php_pdo.dll
extension=php_pdo_mysql.dll

On a Linux server you can compile php with the following option --with-pdo-mysql In your php.ini, add the following lines

extension=pdo.so
extension=pdo_mysql.so

some webhosts don't allow to edit the php ini directly so you need to talk to them to give you this permission, or them uncomment these lines I posted in php.ini file


问:
Using a numpy array of length less than pandas dataframe to fill in pandas dataframe
```<code>df = pd.DataFrame(index=pd.date_range('2017-01-01', '2017-01-10', freq='D'), columns=['test'])

vals = np.array([1.0, 2.0])

df['test'] = vals
</code>```

I get this error:
ValueError: Length of values does not match length of index

Any way I can fix it? This error is arising because lenght of vals is less than length of df. I want to insert numpy NaNs for the places where I have no values.

答:
You can assign to just the first rows like this:</p>

```<code>df['test'][:len(vals)] = vals
</code>```

Body:
df = pd.DataFrame(index=pd.date_range('2017-01-01', '2017-01-10', freq='D'), columns=['test'])

vals = np.array([1.0, 2.0])

df['test'] = vals

I get this error:
ValueError: Length of values does not match length of index

Any way I can fix it? This error is arising because lenght of vals is less than length of df. I want to insert numpy NaNs for the places where I have no values.

Body:
You can assign to just the first rows like this:

df['test'][:len(vals)] = vals


问:
How to hide cursor in a Swing application?
Is there a way to hide cursor (other than using transparent image as a cursor)?

I want to hide the cursor, when the user point the mouse outside JPanel in JFrame.

答:
I solve this problem much easier:</p>

```<code>final Timer cursorTimer = new Timer(2000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        getContentPane().setCursor(null);
    }
});
cursorTimer.start();

addMouseMotionListener(new MouseMotionAdapter() {
    @Override
    public void mouseMoved(MouseEvent e) {
        getGlassPane().setCursor(Cursor.getDefaultCursor());
        cursorTimer.restart();
    }
});
</code>```

Body:
I solve this problem much easier:

final Timer cursorTimer = new Timer(2000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        getContentPane().setCursor(null);
    }
});
cursorTimer.start();

addMouseMotionListener(new MouseMotionAdapter() {
    @Override
    public void mouseMoved(MouseEvent e) {
        getGlassPane().setCursor(Cursor.getDefaultCursor());
        cursorTimer.restart();
    }
});


问:
Converting Java 1.8 lambdas to Java 1.7 on gs-uploading-files Spring Boot example
I am running through some exercises on https://spring.io/ Spring Boot.

Doing example https://spring.io/guides/gs/uploading-files/ and it works fine when I use Java 8, but unfortunately the code I am wrapping in a web service requires Java 7.  I have listed all of the erroring code, can someone help me convert the lambdas to 1.7 compliant code and replace the new libraries (java.util.stream.Stream and java.util.stream.Collectors).

Application.java

```<code>@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    CommandLineRunner init(StorageService storageService) {
        return (args) -> {
            storageService.deleteAll();
            storageService.init();
        };
    }
}
</code>```

return (args) -> errors out saying "use source -8 or higher to enable
  lambda expressions"

FileUploadController.java

```<code>import java.util.stream.Collectors

//..

@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {

    model.addAttribute("files", storageService
            .loadAll()
            .map(path ->
                    MvcUriComponentsBuilder
                            .fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
                            .build().toString())
            .collect(Collectors.toList()));

    return "uploadForm";
}
</code>```

package java.util.stream does not exist

type loadAll() is erroneous

errors out saying "use source -8 or higher to enable
  lambda expressions"

FileSystemStorageService.java

```<code>@Override
public Stream<Path> loadAll() {
    try {
        return Files.walk(this.rootLocation, 1)
                .filter(path -> !path.equals(this.rootLocation))
                .map(path -> this.rootLocation.relativize(path));
    } catch (IOException e) {
        throw new StorageException("Failed to read stored files", e);
    }

}
</code>```

cannot find symbol walk

errors out saying "use source -8 or higher to enable
  lambda expressions"

StorageService.java

```<code>import java.util.stream.Stream;

public interface StorageService {

    void init();

    void store(MultipartFile file);

    Stream<Path> loadAll();

    Path load(String filename);

    Resource loadAsResource(String filename);

    void deleteAll();

}
</code>```

package java.util.stream does not exist

答:
You can update your methods like below to Java 7 variant. All the test cases are passing.

Application.java

```<code>@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    CommandLineRunner init(StorageService storageService) {
        return new CommandLineRunner() {
          @Override
           public void run(String... args) throws Exception {
            storageService.deleteAll();
            storageService.init();
           }
       };
    }
}
</code>```

FileUploadController.java

```<code>@GetMapping("/")
    public String listUploadedFiles(Model model) throws IOException {
        List<Path> paths = storageService.loadAll();
        List<String> sPaths = new ArrayList<>(paths.size());
        for (Path path : paths) {
            sPaths.add(MvcUriComponentsBuilder
                        .fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
                        .build().toString());
        }
        model.addAttribute("files", sPaths);
        return "uploadForm";
    }
</code>```

Updated the method implementation to use DirectoryStream to simple listing all the files.

FileSystemStorageService.java

```<code>@Override
public List<Path> loadAll() {
   List<Path> rPaths = new ArrayList<>();
   try (DirectoryStream<Path> stream = Files.newDirectoryStream(this.rootLocation)) {
       for (Path entry: stream) {
             rPaths.add(rootLocation.relativize(entry));
        }
    } catch (IOException e) {
       throw new StorageException("Failed to read stored files", e);
    }
    return rPaths;
}
</code>```

StorageService.java

```<code>public interface StorageService {

    void init();

    void store(MultipartFile file);

    List<Path> loadAll();

    Path load(String filename);

    Resource loadAsResource(String filename);

    void deleteAll();

}
</code>```

FileUploadTests

```<code> @Test
    public void shouldListAllFiles() throws Exception {
        given(this.storageService.loadAll())
                .willReturn(Arrays.asList(Paths.get("first.txt"), Paths.get("second.txt")));

        this.mvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(model().attribute("files",
                        Matchers.contains("http://localhost/files/first.txt", "http://localhost/files/second.txt")));
    }
</code>```

FileSystemStorageServiceTest

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
public class FileSystemStorageServiceTest {

    @Autowired
    private StorageService storageService;

    @Test
    public void loadAll() throws Exception {
        MockMultipartFile multipartFile =
                new MockMultipartFile("file", "test.txt", "text/plain", "Spring Framework".getBytes());
        storageService.store(multipartFile);
        List<Path> paths = storageService.loadAll();
        assertThat(paths.size()).isEqualTo(1);
    }

}
</code>```

Update TestCompare with rootLocation set to FileSystems.getDefault().getPath(".")

```<code>@RunWith(SpringRunner.class)
public class TestCompare {

    @Configuration
    @ComponentScan(basePackages = {"hello.storage"})
    @EnableConfigurationProperties(StorageProperties.class)
    static class ContextConfiguration{}

    @Autowired
    private StorageService storageService;

    @Test
    public void loadAllDirectoryStreamVsloadAllWalkFileWithDepth1() throws Exception {
        List<Path> paths1 = storageService.loadAllDirectoryStream();
        List<Path> paths2 = storageService.loadAllWalkFileWithDepth1();
        assertThat(paths1.size()).isEqualTo(paths2.size());

    }

}
</code>```

I've added two methods just for testing purposes. One using DirectoryStream and another using  WalkFileTree with maxDepth set to 1. Both of them works the same.

```<code>   @Override
    public List<Path> loadAllDirectoryStream() {
        List<Path> rPaths = new ArrayList<>();
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(this.rootLocation)) {
            for (Path entry: stream) {
                //if(!Files.isDirectory(entry))
                    rPaths.add(rootLocation.relativize(entry));
            }
        } catch (IOException e) {
            throw new StorageException("Failed to read stored files", e);
        }
        return rPaths;
    }

    @Override
    public List<Path> loadAllWalkFileWithDepth1() {
        List<Path> rPaths = new ArrayList<>();
        try {
            Files.walkFileTree(rootLocation, EnumSet.noneOf(FileVisitOption.class), 1, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (!rootLocation.equals(file)) {
                        rPaths.add(rootLocation.relativize(file));
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
            return rPaths;
        } catch (IOException e) {
            throw new StorageException("Failed to read stored files", e);
        }
    }
</code>```

Body:
I am running through some exercises on https://spring.io/ Spring Boot.

Doing example https://spring.io/guides/gs/uploading-files/ and it works fine when I use Java 8, but unfortunately the code I am wrapping in a web service requires Java 7.  I have listed all of the erroring code, can someone help me convert the lambdas to 1.7 compliant code and replace the new libraries (java.util.stream.Stream and java.util.stream.Collectors).

Application.java

@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    CommandLineRunner init(StorageService storageService) {
        return (args) -> {
            storageService.deleteAll();
            storageService.init();
        };
    }
}

return (args) -> errors out saying "use source -8 or higher to enable
  lambda expressions"

FileUploadController.java

import java.util.stream.Collectors

//..

@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {

    model.addAttribute("files", storageService
            .loadAll()
            .map(path ->
                    MvcUriComponentsBuilder
                            .fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
                            .build().toString())
            .collect(Collectors.toList()));

    return "uploadForm";
}

package java.util.stream does not exist

type loadAll() is erroneous

errors out saying "use source -8 or higher to enable
  lambda expressions"

FileSystemStorageService.java

@Override
public Stream<Path> loadAll() {
    try {
        return Files.walk(this.rootLocation, 1)
                .filter(path -> !path.equals(this.rootLocation))
                .map(path -> this.rootLocation.relativize(path));
    } catch (IOException e) {
        throw new StorageException("Failed to read stored files", e);
    }

}

cannot find symbol walk

errors out saying "use source -8 or higher to enable
  lambda expressions"

StorageService.java

import java.util.stream.Stream;

public interface StorageService {

    void init();

    void store(MultipartFile file);

    Stream<Path> loadAll();

    Path load(String filename);

    Resource loadAsResource(String filename);

    void deleteAll();

}

package java.util.stream does not exist

Body:
You can update your methods like below to Java 7 variant. All the test cases are passing.

Application.java

@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    CommandLineRunner init(StorageService storageService) {
        return new CommandLineRunner() {
          @Override
           public void run(String... args) throws Exception {
            storageService.deleteAll();
            storageService.init();
           }
       };
    }
}

FileUploadController.java

@GetMapping("/")
    public String listUploadedFiles(Model model) throws IOException {
        List<Path> paths = storageService.loadAll();
        List<String> sPaths = new ArrayList<>(paths.size());
        for (Path path : paths) {
            sPaths.add(MvcUriComponentsBuilder
                        .fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
                        .build().toString());
        }
        model.addAttribute("files", sPaths);
        return "uploadForm";
    }

Updated the method implementation to use DirectoryStream to simple listing all the files.

FileSystemStorageService.java

@Override
public List<Path> loadAll() {
   List<Path> rPaths = new ArrayList<>();
   try (DirectoryStream<Path> stream = Files.newDirectoryStream(this.rootLocation)) {
       for (Path entry: stream) {
             rPaths.add(rootLocation.relativize(entry));
        }
    } catch (IOException e) {
       throw new StorageException("Failed to read stored files", e);
    }
    return rPaths;
}

StorageService.java

public interface StorageService {

    void init();

    void store(MultipartFile file);

    List<Path> loadAll();

    Path load(String filename);

    Resource loadAsResource(String filename);

    void deleteAll();

}

FileUploadTests

 @Test
    public void shouldListAllFiles() throws Exception {
        given(this.storageService.loadAll())
                .willReturn(Arrays.asList(Paths.get("first.txt"), Paths.get("second.txt")));

        this.mvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(model().attribute("files",
                        Matchers.contains("http://localhost/files/first.txt", "http://localhost/files/second.txt")));
    }

FileSystemStorageServiceTest

@RunWith(SpringRunner.class)
@SpringBootTest
public class FileSystemStorageServiceTest {

    @Autowired
    private StorageService storageService;

    @Test
    public void loadAll() throws Exception {
        MockMultipartFile multipartFile =
                new MockMultipartFile("file", "test.txt", "text/plain", "Spring Framework".getBytes());
        storageService.store(multipartFile);
        List<Path> paths = storageService.loadAll();
        assertThat(paths.size()).isEqualTo(1);
    }

}

Update TestCompare with rootLocation set to FileSystems.getDefault().getPath(".")

@RunWith(SpringRunner.class)
public class TestCompare {

    @Configuration
    @ComponentScan(basePackages = {"hello.storage"})
    @EnableConfigurationProperties(StorageProperties.class)
    static class ContextConfiguration{}

    @Autowired
    private StorageService storageService;

    @Test
    public void loadAllDirectoryStreamVsloadAllWalkFileWithDepth1() throws Exception {
        List<Path> paths1 = storageService.loadAllDirectoryStream();
        List<Path> paths2 = storageService.loadAllWalkFileWithDepth1();
        assertThat(paths1.size()).isEqualTo(paths2.size());

    }

}

I've added two methods just for testing purposes. One using DirectoryStream and another using  WalkFileTree with maxDepth set to 1. Both of them works the same.

   @Override
    public List<Path> loadAllDirectoryStream() {
        List<Path> rPaths = new ArrayList<>();
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(this.rootLocation)) {
            for (Path entry: stream) {
                //if(!Files.isDirectory(entry))
                    rPaths.add(rootLocation.relativize(entry));
            }
        } catch (IOException e) {
            throw new StorageException("Failed to read stored files", e);
        }
        return rPaths;
    }

    @Override
    public List<Path> loadAllWalkFileWithDepth1() {
        List<Path> rPaths = new ArrayList<>();
        try {
            Files.walkFileTree(rootLocation, EnumSet.noneOf(FileVisitOption.class), 1, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (!rootLocation.equals(file)) {
                        rPaths.add(rootLocation.relativize(file));
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
            return rPaths;
        } catch (IOException e) {
            throw new StorageException("Failed to read stored files", e);
        }
    }


问:
Use of " for(string str: tmp) " in c++?
I came accross this for(string str: tmp) s.insert(str) in a C++ code for LCS and I don't know what it means. I saw it used in Java. Can it be written in any other way in C++?

答:
The latest C++ version has a similar for-each loop. You would need to compile your program with the latest version of C++ for it to function correctly.

http://en.cppreference.com/w/cpp/language/range-for

Title: Use of " for(string str: tmp) " in c++?


问:
Is there an advantange/disadvantage to creating multiple FormViews in a single .aspx page?
I am developing an asp.net web application in c# for asset management.  Currently, I'm working on the functionality to insert records to 18 different tables.  Example: Adding a new Manufacturer to the Manufacturer table, or adding a new building to the building table.

I'm thinking of two options, having 18 different FormViews in one page, each with insert/edit templates, or having 18 different pages, a page with a form for each table.

Is there any advantage or disadvantage to having that many FormViews in one page?

Thank You!

答: You have to think about the performance of the page because if you put 18 page controls in one single page using FormViews it is not a recommended way to do.</p>


问:
How to conditionally extract lines from a file, edit them, and insert them back
I have created a simple command line game in python.
The user begins by inputting their nickname which is stored as name

At the end of the game the user's score is stored in a file like so:

```<code>wins = str(wins)
losses = str(losses)

file = open('scores.py','a')
file.write(name + ": wins = " + wins + "  losses = " + losses + "\n\n")
file.close
</code>```

( I converted the 'wins' and 'losses' variables to strings as I couldn't seem to write integers to a file, I don't know if this is possible (i'm sure it is) but I just didn't know how to do it. )

I want the user playing the game to have a cumulative score, i.e. if they were to play 1 game and win 6 rounds, play another game and win 2 rounds, I don't want there to by 2 entries in the 'scores.py' file, I would like it to say:

```<code>*User*: wins = 8 losses = 0
</code>```

The only way I could think of doing this is that after each game finishes, the user's name and score would be appended to the 'scores.py' file, but before that, the file is scanned line-by-line to check whether or not the user's nickname already has an entered score. IF the name inputted at the start of the game is the same name as the one being read on the particular line in the 'scores.py' file, extract the line, convert the string values for wins and for losses to integers, add the current score in the game to the stored score, and then write it back into the file.

Any and all help would be greatly appreciated, and excuse me if the code is terrible and the solution is simple, I am extremely new to python and am not very well-versed in code in general either.

答:
You can use the built-in json module. I think it fits nicely with your use case.

```<code>import json

def update_scores(name, wins, losses, scores_file='scores.json'):
    try:
        with open(scores_file, 'r') as f:
            scores = json.load(f)
    except (IOError, ValueError):
        # Non existing or empty file.
        scores = {}
    try:
        scores[name]['wins'] += wins
        scores[name]['losses'] += losses
    except KeyError:
        # Initialize user score
        scores[name] = {'wins': wins, 'losses': losses}
    with open(scores_file, 'w') as f:
        json.dump(scores, f)

# Use:
update_scores('foo', 3, 8)  # {"foo": {"wins": 3, "losses": 8}}
update_scores('foo', 3, 2)  # {"foo": {"wins": 6, "losses": 10}}
update_scores('bar', 8, 0)  # {"foo": {"wins": 6, "losses": 10}, "bar": {"wins": 8, "losses": 0}}
</code>```

Body:
I have created a simple command line game in python.
The user begins by inputting their nickname which is stored as name

At the end of the game the user's score is stored in a file like so:

wins = str(wins)
losses = str(losses)

file = open('scores.py','a')
file.write(name + ": wins = " + wins + "  losses = " + losses + "\n\n")
file.close

( I converted the 'wins' and 'losses' variables to strings as I couldn't seem to write integers to a file, I don't know if this is possible (i'm sure it is) but I just didn't know how to do it. )

I want the user playing the game to have a cumulative score, i.e. if they were to play 1 game and win 6 rounds, play another game and win 2 rounds, I don't want there to by 2 entries in the 'scores.py' file, I would like it to say:

*User*: wins = 8 losses = 0

The only way I could think of doing this is that after each game finishes, the user's name and score would be appended to the 'scores.py' file, but before that, the file is scanned line-by-line to check whether or not the user's nickname already has an entered score. IF the name inputted at the start of the game is the same name as the one being read on the particular line in the 'scores.py' file, extract the line, convert the string values for wins and for losses to integers, add the current score in the game to the stored score, and then write it back into the file.

Any and all help would be greatly appreciated, and excuse me if the code is terrible and the solution is simple, I am extremely new to python and am not very well-versed in code in general either.

Body:
You can use the built-in json module. I think it fits nicely with your use case.

import json

def update_scores(name, wins, losses, scores_file='scores.json'):
    try:
        with open(scores_file, 'r') as f:
            scores = json.load(f)
    except (IOError, ValueError):
        # Non existing or empty file.
        scores = {}
    try:
        scores[name]['wins'] += wins
        scores[name]['losses'] += losses
    except KeyError:
        # Initialize user score
        scores[name] = {'wins': wins, 'losses': losses}
    with open(scores_file, 'w') as f:
        json.dump(scores, f)

# Use:
update_scores('foo', 3, 8)  # {"foo": {"wins": 3, "losses": 8}}
update_scores('foo', 3, 2)  # {"foo": {"wins": 6, "losses": 10}}
update_scores('bar', 8, 0)  # {"foo": {"wins": 6, "losses": 10}, "bar": {"wins": 8, "losses": 0}}


问:
Easy way to handle nested transactions
Suppose there is an "addUser" function, inside we need to insert a record to "Account" table and "User" table, so the two steps have to be within a transaction too, so we will write the following code:

```<code>function addUser (userName, password) {
    sequelize.transaction(function () {
        return AccountModel.create(...)
        .then(UserModel.create(...))
    })
}
</code>```

However, in another "addTeam" function, inside we need to insert a record to "Team" table and create a admin user using the above function. The function also need to be wrapped inside a transaction.

So the problem comes, the "addUser" function sometimes need to begin a new transaction, and sometimes need to use the transaction passed in. The most obvious ways is below:

```<code>function addUser (userName, password, transaction) {
       let func = function (t) {
           return  AccountModel.create(..., t)
           .then(()=>UserModel.create(..., t)));
       if (transaction) func(t);
       else sequelize.transaction(x=>func(t));
}

function addTeam() {
     sequelize.transaction(x=> {
         TeamModel.create(..., x)
         .then(y=>addUser(x));
     });
}
</code>```

Obviously, it is awful. How to deal with it easily, which let transaction totally transparent to the caller like below:

```<code>@Transaction
async function addUser(userName, password) {
    await AccountModel.create(...);
    await UserModel.create(...);
}

@Transaction
async function addTeam(...) {
    await TeamModel.create(...);
    await addUser(...);
}
</code>```

答:
If you use CLS, a very simple helper function will do the work.

const cls = require('continuation-local-storage');
const Sequelize = require('sequelize');
const NAMESPACE = 'your-namespace';

// Use CLS for Sequelize
Sequelize.cls = cls.createNamespace(NAMESPACE);
const sequelize = new Sequelize(...);

/* * * * * * * * * * * * * * * * * * * * *
 * THE MAGIC: Create a transaction wrapper
 * * * * * * * * * * * * * * * * * * * * */

function transaction(task) {
  return cls.getNamespace(NAMESPACE).get('transaction') ? task() : sequelize.transaction(task);
};

/* * * * * * * * * * * * * * * * * * * * *
 * Your code below
 * * * * * * * * * * * * * * * * * * * * */

function addUser(userName, password) {
  return transaction(function() {
    return AccountModel
      .create(...)
      .then(() => UserModel.create(...));
  });
}

function addTeam() {
  return transaction(function() {
    return TeamModel
      .create(...)
      .then(() => addUser(...));
  });
}```

Title: Easy way to handle nested transactions

Body:
Suppose there is an "addUser" function, inside we need to insert a record to "Account" table and "User" table, so the two steps have to be within a transaction too, so we will write the following code:

function addUser (userName, password) {
    sequelize.transaction(function () {
        return AccountModel.create(...)
        .then(UserModel.create(...))
    })
}

However, in another "addTeam" function, inside we need to insert a record to "Team" table and create a admin user using the above function. The function also need to be wrapped inside a transaction.

So the problem comes, the "addUser" function sometimes need to begin a new transaction, and sometimes need to use the transaction passed in. The most obvious ways is below:

function addUser (userName, password, transaction) {
       let func = function (t) {
           return  AccountModel.create(..., t)
           .then(()=>UserModel.create(..., t)));
       if (transaction) func(t);
       else sequelize.transaction(x=>func(t));
}

function addTeam() {
     sequelize.transaction(x=> {
         TeamModel.create(..., x)
         .then(y=>addUser(x));
     });
}

Obviously, it is awful. How to deal with it easily, which let transaction totally transparent to the caller like below:

@Transaction
async function addUser(userName, password) {
    await AccountModel.create(...);
    await UserModel.create(...);
}

@Transaction
async function addTeam(...) {
    await TeamModel.create(...);
    await addUser(...);
}


问:
Searching an ArrayList for a string and returning another associated string
```<code>private ArrayList<SocialMediaAccount> socialMediaAccounts;

public void addSocialMediaAccount(String userID, String websiteName, String websiteURL, int activityLevel)
{
    SocialMediaAccount object = new SocialMediaAccount(userID, websiteName, websiteURL, activityLevel);
    socialMediaAccounts.add(object);
}
</code>```

I have this ArrayList and I need to search for a particular websiteName and return the userID associated with the object.
Getting confused a lot and would like some help on getting started with this problem.
Thanks!

答:
This should work.</p>

```<code>//This method will return the userID associated with the given target websiteName.
//Insert it where you need it.
public String search(String targetWebsiteName){
    //loop through each account in your list.
    For(SocialMediaAccount acc: socialMediaAccounts){
      SocialMediaAccount tempObject = acc;
       //check for websiteName
       if(tempObject.getWebsiteName().equals(targetWebsiteName)) return tempObject.getUserID();
    }
return null;
}

//Add these methods to your SocialMediaAccount class
class SocialMediaAccount{

       //Getters for object variables
       String getWebsiteName(){
            return websiteName;
       }

       String getUserID(){
           return userID;
       }
}
</code>```

Body:
private ArrayList<SocialMediaAccount> socialMediaAccounts;

public void addSocialMediaAccount(String userID, String websiteName, String websiteURL, int activityLevel)
{
    SocialMediaAccount object = new SocialMediaAccount(userID, websiteName, websiteURL, activityLevel);
    socialMediaAccounts.add(object);
}

I have this ArrayList and I need to search for a particular websiteName and return the userID associated with the object.
Getting confused a lot and would like some help on getting started with this problem.
Thanks!

Body:
This should work.

//This method will return the userID associated with the given target websiteName.
//Insert it where you need it.
public String search(String targetWebsiteName){
    //loop through each account in your list.
    For(SocialMediaAccount acc: socialMediaAccounts){
      SocialMediaAccount tempObject = acc;
       //check for websiteName
       if(tempObject.getWebsiteName().equals(targetWebsiteName)) return tempObject.getUserID();
    }
return null;
}

//Add these methods to your SocialMediaAccount class
class SocialMediaAccount{

       //Getters for object variables
       String getWebsiteName(){
            return websiteName;
       }

       String getUserID(){
           return userID;
       }
}


答: If you have a lot of items in your list and you're doing a lot of searches, a HashMap using the the website name as the key will be much faster.

Title: Searching an ArrayList for a string and returning another associated string


问:
Hibernate Projections.sum() over an enum
I need some help with Hibernate Projections.

I have a class called Activity with a property "duration" which is an Enum. Duration is a Integer field on the Oracle Database. I have annotated the enum.

```<code>
@TypeDefs({
    @TypeDef(
        name = "Duration",
        typeClass = GenericEnumUserType.class,
        parameters = {
            @Parameter(name = "enumClass", value = "myproject.Duration"),
            @Parameter(name = "identifierMethod", value = "getValue"),
            @Parameter(name = "valueOfMethod", value = "getInstanceByValue") })
})
@Entity
@Table(name = "activity")
public class Activity {
...
private Duration duration;
...
}
</code>```

The enum Duration has methods getValue() and getInstanceByValue(). The Value is an Integer.

I need to sum up the dutation of some Acitivities, that match my criterias. My DetachedCriteria looks something like this:

```<code>
DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Activity.class);
...
detachedCriteria.setProjection(Projections.sum("duration"));
</code>```

When I execute this detachedCriteria I get the following ClassCastException:

myproject.Duration cannot be cast to java.lang.Integer

How can I sum over an enumeration field? It works on the database with pure SQL, therefore it should work with hibernate too somhow I assume.

Thanks for any help.

答:
I would map the map the column to an additional field that is of type int. This field needs to be mapped as readonly to avoid ambiguity:

```<code>@Entity
@Table(name = "activity")
public class Activity {
  ...
  private Duration duration;

  @Column(name = "duration", updatable = false, insertable = false) //mapped to the same columnn!
  private int durationNumeric
   ...
}
</code>```

Then you rewrite your aggregate query along these lines:

```<code>detachedCriteria.setProjection(Projections.sum("durationNumeric"));
</code>```

Body:
I need some help with Hibernate Projections.

I have a class called Activity with a property "duration" which is an Enum. Duration is a Integer field on the Oracle Database. I have annotated the enum.

@TypeDefs({
    @TypeDef(
        name = "Duration",
        typeClass = GenericEnumUserType.class,
        parameters = {
            @Parameter(name = "enumClass", value = "myproject.Duration"),
            @Parameter(name = "identifierMethod", value = "getValue"),
            @Parameter(name = "valueOfMethod", value = "getInstanceByValue") })
})
@Entity
@Table(name = "activity")
public class Activity {
...
private Duration duration;
...
}

The enum Duration has methods getValue() and getInstanceByValue(). The Value is an Integer.

I need to sum up the dutation of some Acitivities, that match my criterias. My DetachedCriteria looks something like this:

DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Activity.class);
...
detachedCriteria.setProjection(Projections.sum("duration"));

When I execute this detachedCriteria I get the following ClassCastException:

myproject.Duration cannot be cast to java.lang.Integer

How can I sum over an enumeration field? It works on the database with pure SQL, therefore it should work with hibernate too somhow I assume.

Thanks for any help.

Body:
I would map the map the column to an additional field that is of type int. This field needs to be mapped as readonly to avoid ambiguity:

@Entity
@Table(name = "activity")
public class Activity {
  ...
  private Duration duration;

  @Column(name = "duration", updatable = false, insertable = false) //mapped to the same columnn!
  private int durationNumeric
   ...
}

Then you rewrite your aggregate query along these lines:

detachedCriteria.setProjection(Projections.sum("durationNumeric"));


问:
SQL - Row sum with condition from 2 tables
I have 2 tables and want to get the row sum from 2 tables with conditions.
Here are my tables:

tabale1,
tabale2

i want the row sum from 2 tables, like:

```<code>if sk not null sum sk but if it is null sk = ss
</code>```

For example, the total sum of sh2 is: 19 + 5 + 11 + 5 = 40

I really need that, please help!

Table1:

Table2:

答:
Next sql will return the sum over the tables, grouping by name:

```<code>select name, sum(total) total from
(select name, sum(coalesce(sk,ss)) total
 from table1
 group by name
 union all
 select name, sum(coalesce(sk,ss)) total
 from table2
 group by name
) t
group by name
</code>```

The clause "group by" inside of the subqueries is very important because whether the tables return a lot of lines, they will reduce the number of lines for the "group by" on the query, optimizing time and using less memory.

Body:
I have 2 tables and want to get the row sum from 2 tables with conditions.
Here are my tables:

tabale1,
tabale2

i want the row sum from 2 tables, like:

if sk not null sum sk but if it is null sk = ss

For example, the total sum of sh2 is: 19 + 5 + 11 + 5 = 40

I really need that, please help!

Table1:

Table2:

Body:
Next sql will return the sum over the tables, grouping by name:

select name, sum(total) total from
(select name, sum(coalesce(sk,ss)) total
 from table1
 group by name
 union all
 select name, sum(coalesce(sk,ss)) total
 from table2
 group by name
) t
group by name

The clause "group by" inside of the subqueries is very important because whether the tables return a lot of lines, they will reduce the number of lines for the "group by" on the query, optimizing time and using less memory.


问:
Anyone uses backtrader? How can I keep a reference in a method?
I'm trying to use backtrader module(https://www.backtrader.com/).

My purpose is just to compare the current price and the price of the last buy execution and execute sell() if the current price is lower than the last execution price.

I asked the same question to its community and the administrator said "You need to keep a reference to the order notified in notify_order, to later use it in next." However, I'm afraid I still don't understand how to do it, after reading through my python textbooks. (https://community.backtrader.com/topic/298/how-can-i-get-the-price-at-which-buy-executed/5)

In short, I want to refer to order.executed.price inside def next(self):

I'd appreciate it if I could get some hints on this problem. Thank you!

```<code>import datetime  # For datetime objects
import os.path  # To manage paths
import sys  # To find out the script name (in argv[0])

# Import the backtrader platform
import backtrader as bt

# Create a Stratey
class TestStrategy(bt.Strategy):
params = (
    ('maperiod', 15),
)

def log(self, txt, dt=None):
    ''' Logging function fot this strategy'''
    dt = dt or self.datas[0].datetime.date(0)
    print('%s, %s' % (dt.isoformat(), txt))

def __init__(self):
    # Keep a reference to the "close" line in the data[0] dataseries
    self.dataclose = self.datas[0].close

    # To keep track of pending orders and buy price/commission
    self.order = None
    self.buyprice = None
    self.buycomm = None

    # Add a MovingAverageSimple indicator
    self.sma = bt.indicators.SimpleMovingAverage(
        self.datas[0], period=self.params.maperiod)

    self.atr = bt.indicators.ATR(self.datas[0])
    self.stoch = bt.indicators.StochasticSlow(self.datas[0])
    self.ema14 = bt.indicators.ExponentialMovingAverage(self.datas[0], period=14)
    self.ema28 = bt.indicators.ExponentialMovingAverage(self.datas[0], period=28)
    self.rsi = bt.indicators.RSI(self.datas[0])

    # Indicators for the plotting show
    bt.indicators.ExponentialMovingAverage(self.datas[0], period=25)
    bt.indicators.WeightedMovingAverage(self.datas[0], period=25,
                                        subplot=True)
    bt.indicators.StochasticSlow(self.datas[0])
    bt.indicators.MACDHisto(self.datas[0])
    rsi = bt.indicators.RSI(self.datas[0])
    bt.indicators.SmoothedMovingAverage(rsi, period=10)
    bt.indicators.ATR(self.datas[0], plot=False)

def notify_order(self, order):
    if order.status in [order.Submitted, order.Accepted]:
        # Buy/Sell order submitted/accepted to/by broker - Nothing to do
        return

    # Check if an order has been completed
    # Attention: broker could reject order if not enougth cash
    if order.status in [order.Completed, order.Canceled, order.Margin]:
        if order.isbuy():
            self.log(
                'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                (order.executed.price,
                 order.executed.value,
                 order.executed.comm))

            self.buyprice = order.executed.price
            self.buycomm = order.executed.comm
        else:  # Sell
            self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                     (order.executed.price,
                      order.executed.value,
                      order.executed.comm))

        self.bar_executed = len(self)

    # Write down: no pending order
    self.order = None

def notify_trade(self, trade):
    if not trade.isclosed:
        return

    self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
             (trade.pnl, trade.pnlcomm))

def next(self):
    # Simply log the closing price of the series from the reference
    self.log('Close, %.2f' % self.dataclose[0])

    # Check if an order is pending ... if yes, we cannot send a 2nd one
    if self.order:
        return

    # Check if we are in the market
    if not self.position:

        # Not yet ... we MIGHT BUY if ...
        if self.stoch[0] > 80:

            # BUY, BUY, BUY!!! (with all possible default parameters)
            self.log('BUY CREATE, %.2f' % self.dataclose[0])

            # Keep track of the created order to avoid a 2nd order
            self.order = self.buy()

    else:
        if self.position.price < self.dataclose[0]:
            # SELL, SELL, SELL!!! (with all possible default parameters)
            self.log('SELL CREATE, %.2f' % self.dataclose[0])

            # Keep track of the created order to avoid a 2nd order
            self.order = self.sell()
</code>```

答:
In notify_order() you can say something like this:

```<code>self.last_executed_price = order.executed.price
</code>```

Then you can use that variable inside other functions.

Body:
I'm trying to use backtrader module(https://www.backtrader.com/).

My purpose is just to compare the current price and the price of the last buy execution and execute sell() if the current price is lower than the last execution price.

I asked the same question to its community and the administrator said "You need to keep a reference to the order notified in notify_order, to later use it in next." However, I'm afraid I still don't understand how to do it, after reading through my python textbooks. (https://community.backtrader.com/topic/298/how-can-i-get-the-price-at-which-buy-executed/5)

In short, I want to refer to order.executed.price inside def next(self):

I'd appreciate it if I could get some hints on this problem. Thank you!

import datetime  # For datetime objects
import os.path  # To manage paths
import sys  # To find out the script name (in argv[0])

# Import the backtrader platform
import backtrader as bt

# Create a Stratey
class TestStrategy(bt.Strategy):
params = (
    ('maperiod', 15),
)

def log(self, txt, dt=None):
    ''' Logging function fot this strategy'''
    dt = dt or self.datas[0].datetime.date(0)
    print('%s, %s' % (dt.isoformat(), txt))

def __init__(self):
    # Keep a reference to the "close" line in the data[0] dataseries
    self.dataclose = self.datas[0].close

    # To keep track of pending orders and buy price/commission
    self.order = None
    self.buyprice = None
    self.buycomm = None

    # Add a MovingAverageSimple indicator
    self.sma = bt.indicators.SimpleMovingAverage(
        self.datas[0], period=self.params.maperiod)

    self.atr = bt.indicators.ATR(self.datas[0])
    self.stoch = bt.indicators.StochasticSlow(self.datas[0])
    self.ema14 = bt.indicators.ExponentialMovingAverage(self.datas[0], period=14)
    self.ema28 = bt.indicators.ExponentialMovingAverage(self.datas[0], period=28)
    self.rsi = bt.indicators.RSI(self.datas[0])

    # Indicators for the plotting show
    bt.indicators.ExponentialMovingAverage(self.datas[0], period=25)
    bt.indicators.WeightedMovingAverage(self.datas[0], period=25,
                                        subplot=True)
    bt.indicators.StochasticSlow(self.datas[0])
    bt.indicators.MACDHisto(self.datas[0])
    rsi = bt.indicators.RSI(self.datas[0])
    bt.indicators.SmoothedMovingAverage(rsi, period=10)
    bt.indicators.ATR(self.datas[0], plot=False)

def notify_order(self, order):
    if order.status in [order.Submitted, order.Accepted]:
        # Buy/Sell order submitted/accepted to/by broker - Nothing to do
        return

    # Check if an order has been completed
    # Attention: broker could reject order if not enougth cash
    if order.status in [order.Completed, order.Canceled, order.Margin]:
        if order.isbuy():
            self.log(
                'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                (order.executed.price,
                 order.executed.value,
                 order.executed.comm))

            self.buyprice = order.executed.price
            self.buycomm = order.executed.comm
        else:  # Sell
            self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                     (order.executed.price,
                      order.executed.value,
                      order.executed.comm))

        self.bar_executed = len(self)

    # Write down: no pending order
    self.order = None

def notify_trade(self, trade):
    if not trade.isclosed:
        return

    self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
             (trade.pnl, trade.pnlcomm))

def next(self):
    # Simply log the closing price of the series from the reference
    self.log('Close, %.2f' % self.dataclose[0])

    # Check if an order is pending ... if yes, we cannot send a 2nd one
    if self.order:
        return

    # Check if we are in the market
    if not self.position:

        # Not yet ... we MIGHT BUY if ...
        if self.stoch[0] > 80:

            # BUY, BUY, BUY!!! (with all possible default parameters)
            self.log('BUY CREATE, %.2f' % self.dataclose[0])

            # Keep track of the created order to avoid a 2nd order
            self.order = self.buy()

    else:
        if self.position.price < self.dataclose[0]:
            # SELL, SELL, SELL!!! (with all possible default parameters)
            self.log('SELL CREATE, %.2f' % self.dataclose[0])

            # Keep track of the created order to avoid a 2nd order
            self.order = self.sell()

Body:
In notify_order() you can say something like this:

self.last_executed_price = order.executed.price

Then you can use that variable inside other functions.


问:
Optomised Algorithm for keeping track of network packets (replay attack prevention)
I'm implementing a network server that processes udp packets. I want to  avoid replay attacks, where an attacker could copy udp packets, and replay them later in time. I way toying with idea that i could hash packet and store this value in a hash table. I can then do the same process everytime a packet is received then look it up in the hash table. If it's already exists then we reject the packet, however if we never seen it (the entry does not exist) we store it for future use.

Now, what hash algorithm would be suitable for this? Do i need something other than hash table? As there are a lot of udp packets being received i want this to work in O(1)!!!!!! ;-), is this possible?

Obviously the longer i 'remember' hashes, the more storage (state) i will need to allocate, can a hash table grow and shrink dynamically over time?

I maybe way off here, i may not need a hash table at all! i'm open to idea's!!

答:
Using a hash table for packets can be expensive because you will have to rehash your hash table,  which is O(n).

In this situation you should negotiate a shared secret between the server and each client. This secret key K is then used to construct a Message Authentication Code.  The Message being authenticated should be the data you are transmitting in the UDP packet along with a time stamp. Sequence ID's are unfavorable because there is no guarantee a UDP packet will arrive at all,  and its possible for packets to arrive out of order.

It should be noted that this attack is impossible with TCP due to the three way handshake and sequence ids.   In this case the security provided by TCP may in fact be lighter than this proposed security system.