问:
python database application try except block
this is a login function in an application interacting with a database in postresql. I'm new to python and currently both print statements in the except blocks are being executed.
The error is in: cur.execute(mtype, (member_id, )) Any ideas about why much appreciated.  </p>

```<code>def check_login(member_id, password):

    conn = database_connect()
    if(conn is None):
        return None
    cur = conn.cursor()
    try:
        mtype = """SELECT 'athlete' FROM athlete
                        WHERE member_id=%s
                        UNION
                        SELECT 'official' FROM official
                        WHERE member_id=%s
                        UNION
                        SELECT 'staff' FROM staff
                        WHERE member_id=%s"""
        cur.execute(mtype, (member_id, ))
        user_type = cur.fetchone()
    except:
        print("Error retrieving member type")

    try:
        sql = """SELECT member_id, title, given_names AS first_name, family_name, country_name, place_name AS residence
                 FROM public.country JOIN public.member USING (country_code) JOIN public.place ON (accommodation = place_id)
                 WHERE member_id=%s AND pass_word=%s"""

        cur.execute(sql, (member_id, password))
        user_data = cur.fetchone()

        tuples = {
            'member_id': user_data[0],
            'title': user_data[1],
            'first_name': user_data[2],
            'family_name': user_data[3],
            'country_name': user_data[4],
            'residence': user_data[5],
            'member_type': user_type[0]
        }
        cur.close()
        conn.close()
        return tuples
    except:
        print("Error Invalid Login")
        cur.close()
        conn.close()
        return None
</code>```

答:
You have multiple %s in your initial mtype assignment, yet your execute provides a tuple with only a single parameter. This will fail. This can be fixed by providing the correct number of parameters in execute:

```<code>mtype = """SELECT... member_id=%s UNION ... member_id=%s UNION ... member_id=%s"""
cur.execute(mtype, (member_id, member_id, member_id))
</code>```

Of course, there may be other errors in the code: one shouldn't catch Exceptions blindly unless, really, you don't care what the error is.

Body:
this is a login function in an application interacting with a database in postresql. I'm new to python and currently both print statements in the except blocks are being executed.
The error is in: cur.execute(mtype, (member_id, )) Any ideas about why much appreciated.

def check_login(member_id, password):

    conn = database_connect()
    if(conn is None):
        return None
    cur = conn.cursor()
    try:
        mtype = """SELECT 'athlete' FROM athlete
                        WHERE member_id=%s
                        UNION
                        SELECT 'official' FROM official
                        WHERE member_id=%s
                        UNION
                        SELECT 'staff' FROM staff
                        WHERE member_id=%s"""
        cur.execute(mtype, (member_id, ))
        user_type = cur.fetchone()
    except:
        print("Error retrieving member type")

    try:
        sql = """SELECT member_id, title, given_names AS first_name, family_name, country_name, place_name AS residence
                 FROM public.country JOIN public.member USING (country_code) JOIN public.place ON (accommodation = place_id)
                 WHERE member_id=%s AND pass_word=%s"""

        cur.execute(sql, (member_id, password))
        user_data = cur.fetchone()

        tuples = {
            'member_id': user_data[0],
            'title': user_data[1],
            'first_name': user_data[2],
            'family_name': user_data[3],
            'country_name': user_data[4],
            'residence': user_data[5],
            'member_type': user_type[0]
        }
        cur.close()
        conn.close()
        return tuples
    except:
        print("Error Invalid Login")
        cur.close()
        conn.close()
        return None

Body:
You have multiple %s in your initial mtype assignment, yet your execute provides a tuple with only a single parameter. This will fail. This can be fixed by providing the correct number of parameters in execute:

mtype = """SELECT... member_id=%s UNION ... member_id=%s UNION ... member_id=%s"""
cur.execute(mtype, (member_id, member_id, member_id))

Of course, there may be other errors in the code: one shouldn't catch Exceptions blindly unless, really, you don't care what the error is.


来源: stackexchange

问:
Create Facebook Dialog Popup with Link
I am trying to create a Facebook Dialog using the new improvements that were released last week.

http://developers.facebook.com/blog/post/437

What I want is to be able to have a link so when it's clicked a popup is generated, or have it show up in the page. I've tried putting it in a DIV and then showing with JQuery but it won't center on the page. I've gotten the code to work for posting to the users wall... just don't know how to either format the JS code and or create the link for the popup.
Thanks in advance!

答:
As long as you have the Facebook js on your page, it's as easy as this to create a friend invitation:

```<code><script>
    FB.ui(
     {
      method: 'friends.add',
      id: fbid // assuming you set this variable previously...
     },
     function(param){

      // If you have FireFox + FireBug or Chrome + developer tools:
      console.log(param); // log response to javascript console

            // If they cancel params will show:
            //    {action:false, ...}
            // and if they send the friend request it'll have:
            //    {action:true, ...}
            // and if they closed the pop-up window then:
            //    param is undefined
     }
    );
</script>
</code>```

You can test this by using the javascript console app on Facebook:

http://developers.facebook.com/tools/console

Paste in the script above, including the tags, or click the "Examples" button on the bottom of the text area and find the "fb.ui — friends.add" example.

ContentLicense: CC BY-SA 2.5

Title: Create Facebook Dialog Popup with Link

Body:
As long as you have the Facebook js on your page, it's as easy as this to create a friend invitation:

<script>
    FB.ui(
     {
      method: 'friends.add',
      id: fbid // assuming you set this variable previously...
     },
     function(param){

      // If you have FireFox + FireBug or Chrome + developer tools:
      console.log(param); // log response to javascript console

            // If they cancel params will show:
            //    {action:false, ...}
            // and if they send the friend request it'll have:
            //    {action:true, ...}
            // and if they closed the pop-up window then:
            //    param is undefined
     }
    );
</script>

You can test this by using the javascript console app on Facebook:

http://developers.facebook.com/tools/console

Paste in the script above, including the tags, or click the "Examples" button on the bottom of the text area and find the "fb.ui — friends.add" example.


问:
pandas dataframe select row by full multiindex entry and some column entry
I have a multi indexed DataFrame in pandas and i would like to select a row by the following condition:

Let's say we have columns 'a','b','c' and indicies 'i1','i2'

```<code>print(df)

           a   b   c
i1  i2
10 2.0    10  34   ..
   2.0    11  45   ..
   2.0    12  36   ..
20 2.0    10  15   ..
   2.0    18  34   ..
   2.0    16  46   ..
</code>```

Now I would like to select for each unique muliindex entry the row where column 'a' becomes maximal. So I wrote

```<code>for entry in df.index.unique():
    max_a = df.loc[entry,'a'].max()
</code>```

and now I would like to select that row and append it to another dataframe, let's say dfout

```<code>dfout=dfout.append(df[(df.index.values == entry) & (df['fi'] == max_a)])
</code>```

This raises invalid type comparison, probably because I try to compare tuples, not sure...
Can anyone explain to me, how I would be able to select exactly that row the correct way? Maybe there is even a much nicer way to select all these max('a') rows for all unique entries of df.index.

edit:

df.index.values is of type numpy.ndarray

entry is of type tuple

Maybe this helps for answering my question.

答:
This seems to work

```<code>import pandas as pd

dfout = pd.DataFrame()

for entry in df.index.unique():
    max_a = df.loc[entry,'a'].max()
    dftemp = df.loc[entry,:].copy() # not sure if the copy is necessary
    dftemp = dftemp[dftemp['a'] == max_a]
    dfout = dfout.append(dftemp)
</code>```

But this really feels more like a work around than a solution how to select a row with a

```<code># pseudo code:
multiindex entry == (1,2,...,n)
</code>```

and a

```<code># pseudo code:
column 'keyword' entry == max_a
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a multi indexed DataFrame in pandas and i would like to select a row by the following condition:

Let's say we have columns 'a','b','c' and indicies 'i1','i2'

print(df)

           a   b   c
i1  i2
10 2.0    10  34   ..
   2.0    11  45   ..
   2.0    12  36   ..
20 2.0    10  15   ..
   2.0    18  34   ..
   2.0    16  46   ..

Now I would like to select for each unique muliindex entry the row where column 'a' becomes maximal. So I wrote

for entry in df.index.unique():
    max_a = df.loc[entry,'a'].max()

and now I would like to select that row and append it to another dataframe, let's say dfout

dfout=dfout.append(df[(df.index.values == entry) & (df['fi'] == max_a)])

This raises invalid type comparison, probably because I try to compare tuples, not sure...
Can anyone explain to me, how I would be able to select exactly that row the correct way? Maybe there is even a much nicer way to select all these max('a') rows for all unique entries of df.index.

edit:

df.index.values is of type numpy.ndarray

entry is of type tuple

Maybe this helps for answering my question.

Body:
This seems to work

import pandas as pd

dfout = pd.DataFrame()

for entry in df.index.unique():
    max_a = df.loc[entry,'a'].max()
    dftemp = df.loc[entry,:].copy() # not sure if the copy is necessary
    dftemp = dftemp[dftemp['a'] == max_a]
    dfout = dfout.append(dftemp)

But this really feels more like a work around than a solution how to select a row with a

# pseudo code:
multiindex entry == (1,2,...,n)

and a

# pseudo code:
column 'keyword' entry == max_a


问:
ScalatestRouteTest tests time out when run together but run fine individually
I have a spec for my akka-http route with two tests in it. I can run each of these individually just fine -- but when I run the whole spec (including both tests), the 2nd one fails with

Request was neither completed nor rejected within 30 seconds

Does anyone know why this is?

I don't know if it's relevant, but each test seems to be logging events twice whether I run them alone or together. (Sometimes the duplicated events are in different dispatchers and sometimes they are in the same one.) I am hitting breakpoints on the log messages twice so I assume the events are really being called twice. Again, not sure if it's relevant, but maybe a clue.

I'm also mocking out dependencies, but I don't think that's the issue.

Dumbed down version of my test:

```<code>package com.mystuff

import akka.actor.ActorSystem
import com.mystuff._
import org.mockito.Mockito._
import akka.http.scaladsl.model.StatusCodes.{NotFound, OK}
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
import org.scalatest.{BeforeAndAfterEach, FunSpec, Matchers}

import scala.concurrent.Future
import scala.concurrent.duration._

/**
  * Created by bathalh on 6/2/17.
  */
class OAuthClentServiceASpec extends FunSpec with Matchers with BeforeAndAfterEach with Directives with ScalatestRouteTest
{
    implicit def default(implicit system: ActorSystem) = RouteTestTimeout( 30 seconds )

    private var mockDependencyFun: DependencyFun = _
    private var testObject: MyService = _

    override def beforeEach =
    {
        mockDependencyFun = mock(classOf[DependencyFun])
        when( mockDependencyFun( anyString() ) ).thenReturn( Future successful "OK" )

        testObject = new MyService() {
            def getDepFunction = mockDependencyFun
        }

    }

    describe( "OAuthClentService Application" )
    {
        import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
        import com.mystuff.MyJsonProtocol._

        describe( "Get a specific client" )
        {
            it( "Returns 404 with useful message when client does not exist" )
            {
                val clientId = "does not exist client"
                Get( s"/clients/$clientId" ) ~> testObject.routes ~> check {
                    status should be (NotFound)
                    responseAs[ErrorResponse] should be (ErrorResponse(Set(s"Client not found: $clientId")))
                }
            }

            it( "Returns client information when client exists" )
            {
                val clientId = "ValidClient"
                Get( s"/clients/$clientId" ) ~> testObject.routes ~> check {
                    status should be (OK)
                    val clientInfo = responseAs[ClientResponse]
                    clientInfo.id should be (clientId)
                }
            }
        }
    }
}
</code>```

Thanks in advance for any help.

答:
There May be an issue with your connection pool due to which the connection is getting timeout issues.

Try passing timeout explicitly and see if it works out
implicit def default(implicit system: ActorSystem) = RouteTestTimeout(50.second)

Body:
I have a spec for my akka-http route with two tests in it. I can run each of these individually just fine -- but when I run the whole spec (including both tests), the 2nd one fails with

Request was neither completed nor rejected within 30 seconds

Does anyone know why this is?

I don't know if it's relevant, but each test seems to be logging events twice whether I run them alone or together. (Sometimes the duplicated events are in different dispatchers and sometimes they are in the same one.) I am hitting breakpoints on the log messages twice so I assume the events are really being called twice. Again, not sure if it's relevant, but maybe a clue.

I'm also mocking out dependencies, but I don't think that's the issue.

Dumbed down version of my test:

package com.mystuff

import akka.actor.ActorSystem
import com.mystuff._
import org.mockito.Mockito._
import akka.http.scaladsl.model.StatusCodes.{NotFound, OK}
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
import org.scalatest.{BeforeAndAfterEach, FunSpec, Matchers}

import scala.concurrent.Future
import scala.concurrent.duration._

/**
  * Created by bathalh on 6/2/17.
  */
class OAuthClentServiceASpec extends FunSpec with Matchers with BeforeAndAfterEach with Directives with ScalatestRouteTest
{
    implicit def default(implicit system: ActorSystem) = RouteTestTimeout( 30 seconds )

    private var mockDependencyFun: DependencyFun = _
    private var testObject: MyService = _

    override def beforeEach =
    {
        mockDependencyFun = mock(classOf[DependencyFun])
        when( mockDependencyFun( anyString() ) ).thenReturn( Future successful "OK" )

        testObject = new MyService() {
            def getDepFunction = mockDependencyFun
        }

    }

    describe( "OAuthClentService Application" )
    {
        import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
        import com.mystuff.MyJsonProtocol._

        describe( "Get a specific client" )
        {
            it( "Returns 404 with useful message when client does not exist" )
            {
                val clientId = "does not exist client"
                Get( s"/clients/$clientId" ) ~> testObject.routes ~> check {
                    status should be (NotFound)
                    responseAs[ErrorResponse] should be (ErrorResponse(Set(s"Client not found: $clientId")))
                }
            }

            it( "Returns client information when client exists" )
            {
                val clientId = "ValidClient"
                Get( s"/clients/$clientId" ) ~> testObject.routes ~> check {
                    status should be (OK)
                    val clientInfo = responseAs[ClientResponse]
                    clientInfo.id should be (clientId)
                }
            }
        }
    }
}

Thanks in advance for any help.


问:
Asp.Net Core 1.1 failed to use Jwt Token
I'm trying to implement Jwt Token Auth on a Web API ASP.Net Core 1.1 project in Visual Studio 2017. I followed the tutorial from https://samueleresca.net/2016/12/developing-token-authentication-using-asp-net-core/ but when I add the Microsoft.AspNetCore.Authentication.JwtBearer nuget there is no app.UseJwtBearerAuthentication methods available.

Did I missed something?

Thanks.

答: I have a demo project base on ASP.NET Core 1.1, SQL Server and JWT, you can try it: https://github.com/wilsonwu/netcoreauth</p>


问:
regex for php to find all self-closing tags
I've got a system that uses a DomDocumentFragment which is created based on markup from a database or another area of the system (i.e. other XHTML code).

One such tag that may be included is:

```<code><div class="clear"></div>
</code>```

Before the string is added to the DomDocumentFragment, the content is correct - the  class is closing correctly.

However, the DomDocumentFragment transforms this into:

```<code><div class="clear"/>
</code>```

This does not display correctly in browsers due to the incorrect closing of the  tag.

So my thought is to post-process the XML string that the DomDocument returns me (that includes the incorrect div structure, as shown above), and transform self-closing tags back to their correct structure... i.e. turn  back to .

But I'm having trouble with the pattern for preg_match to find these tags - I've seen some patterns that return all tags (i.e. find all  tags), but not just those that are self closing.

I've tried something along the lines of this, but my head gets a little confused with regex (and I start over-complicating things)

```<code>/<div(["\d\w\s])\/>/
</code>```

The aim is for a pattern to match , where the "...." could be any valid XHTML attributes.

Any suggestions or pointers to put me back on track?

答:
Limit the problem domain -- you need to change
 to

 ... so search for the former, and replace it with the latter using a straightforward find and replace operation.  It should be faster and it will definitely be safer

Whatever you do, do not try to parse HTML with a regular expression (which you're trying to do by building a regex that can detect a
 with arbitrary attributes.)

Body:
I've got a system that uses a DomDocumentFragment which is created based on markup from a database or another area of the system (i.e. other XHTML code).

One such tag that may be included is:

Before the string is added to the DomDocumentFragment, the content is correct - the  class is closing correctly.

However, the DomDocumentFragment transforms this into:

This does not display correctly in browsers due to the incorrect closing of the  tag.

So my thought is to post-process the XML string that the DomDocument returns me (that includes the incorrect div structure, as shown above), and transform self-closing tags back to their correct structure... i.e. turn  back to .

But I'm having trouble with the pattern for preg_match to find these tags - I've seen some patterns that return all tags (i.e. find all  tags), but not just those that are self closing.

I've tried something along the lines of this, but my head gets a little confused with regex (and I start over-complicating things)

/
/

The aim is for a pattern to match , where the "...." could be any valid XHTML attributes.

Any suggestions or pointers to put me back on track?

Body:
Limit the problem domain -- you need to change <div class="clear"/> to <div class="clear"></div> ... so search for the former, and replace it with the latter using a straightforward find and replace operation.  It should be faster and it will definitely be safer

Whatever you do, do not try to parse HTML with a regular expression (which you're trying to do by building a regex that can detect a <div> with arbitrary attributes.)


问:
color button C# Xamarin Android
I'm building a trivia application so i want when i press the button it will be Green if correct and will be Red if not.
my main issue is that wehen i color the button he get larger and looses his grpahic shape.

```<code>private void Button2_Click(object sender, EventArgs e)
    {
        if (answer == "ב")
        {
            Button2.SetBackgroundColor(Android.Graphics.Color.Green);
        }
        else
        {
            Button2.SetBackgroundColor(Android.Graphics.Color.Red);
        }
    }
</code>```

thanks for helping!

答:
Try this:

```<code>Button2.Background.SetColorFilter (Android.Graphics.Color.Green, Android.Graphics.PorterDuff.Mode.Multiply);
</code>```

Actually the button is not getting bigger as it seems is just that the default drawable for the button in Android has paddings, once you change the background setting your color you are removing those and the button is showing its full size.

For Android API 21+ you can also use the Button2.Background.SetTint(); method.

UPDATE

To set the previous ColorFilter

```<code>var previous = Button2.Background.ColorFilter;

 // Set new color
Button2.Background.SetColorFilter (Android.Graphics.Color.Green, Android.Graphics.PorterDuff.Mode.Multiply);

...
...
//Do all you need to do and when ready to set it back

Button2.Background.SetColorFilter(previous);
</code>```

UPDATE 2

If you want to set it back after certain time you can use this code:

```<code>private async void Button2_Click (object sender, EventArgs e)
{
    var previous = Button2.Background.ColorFilter;

    if (answer == "ב")
    {
        Button2.Background.SetColorFilter (Android.Graphics.Color.Green, Android.Graphics.PorterDuff.Mode.Multiply);
    }
    else
    {
        Button2.Background.SetColorFilter (Android.Graphics.Color.Red, Android.Graphics.PorterDuff.Mode.Multiply);
    }

    // This will await 2 seconds before setting the original color.
    await Task.Delay (2000);

   // Using this so we are sure it will run in the UI thread.
    RunOnUiThread (() => {
        Button2.Background.SetColorFilter (previous);
        });
}
</code>```

Title: color button C# Xamarin Android

Body:
I'm building a trivia application so i want when i press the button it will be Green if correct and will be Red if not.
my main issue is that wehen i color the button he get larger and looses his grpahic shape.

private void Button2_Click(object sender, EventArgs e)
    {
        if (answer == "ב")
        {
            Button2.SetBackgroundColor(Android.Graphics.Color.Green);
        }
        else
        {
            Button2.SetBackgroundColor(Android.Graphics.Color.Red);
        }
    }

thanks for helping!

Body:
Try this:

Button2.Background.SetColorFilter (Android.Graphics.Color.Green, Android.Graphics.PorterDuff.Mode.Multiply);

Actually the button is not getting bigger as it seems is just that the default drawable for the button in Android has paddings, once you change the background setting your color you are removing those and the button is showing its full size.

For Android API 21+ you can also use the Button2.Background.SetTint(); method.

UPDATE

To set the previous ColorFilter

var previous = Button2.Background.ColorFilter;

 // Set new color
Button2.Background.SetColorFilter (Android.Graphics.Color.Green, Android.Graphics.PorterDuff.Mode.Multiply);

...
...
//Do all you need to do and when ready to set it back

Button2.Background.SetColorFilter(previous);

UPDATE 2

If you want to set it back after certain time you can use this code:

private async void Button2_Click (object sender, EventArgs e)
{
    var previous = Button2.Background.ColorFilter;

    if (answer == "ב")
    {
        Button2.Background.SetColorFilter (Android.Graphics.Color.Green, Android.Graphics.PorterDuff.Mode.Multiply);
    }
    else
    {
        Button2.Background.SetColorFilter (Android.Graphics.Color.Red, Android.Graphics.PorterDuff.Mode.Multiply);
    }

    // This will await 2 seconds before setting the original color.
    await Task.Delay (2000);

   // Using this so we are sure it will run in the UI thread.
    RunOnUiThread (() => {
        Button2.Background.SetColorFilter (previous);
        });
}


问:
What is object serialization?
What is meant by "object serialization"? Can you please explain it with some examples? </p>

答:
|*| Serializing a class : Converting an object to bytes and bytes back to object (Deserialization).

```<code>class NamCls implements Serializable
{
    int NumVar;
    String NamVar;
}
</code>```

|=> Object-Serialization is process of converting the state of an object into steam of bytes.

|-> Implement when you want the object to exist beyond the lifetime of the JVM.

|-> Serialized Object can be stored in Database.

|-> Serializable-objects cannot be read and understood by humans so we can acheive security.

|=> Object-Deserialization is the process of getting the state of an object and store it into an object(java.lang.Object).

|-> Before storing its state it checks whether serialVersionUID form input-file/network and .class file serialVersionUID are same.

&nbsp&nbspIf not throw java.io.InvalidClassException.

|=> A Java object is only serializable, if its class or any of its superclasses

implements either the java.io.Serializable interface or

its subinterface, java.io.Externalizable.

|=> Static fields in a class cannot be serialized.

```<code>class NamCls implements Serializable
{
    int NumVar;
    static String NamVar = "I won't be serializable";;
}
</code>```

|=> If you do not want to serialise a variable of a class use transient keyword

```<code>class NamCls implements Serializable
{
    int NumVar;
    transient String NamVar;
}
</code>```

|=> If a class implements serializable then all its sub classes will also be serializable.

|=> If a class has a reference of another class, all the references must be Serializable otherwise serialization process will not be performed. In such case,
NotSerializableException is thrown at runtime.

OwnerDisplayName: Warrior

Title: What is object serialization?

LastEditorDisplayName: mmyers

Body:
|*| Serializing a class : Converting an object to bytes and bytes back to object (Deserialization).

class NamCls implements Serializable
{
    int NumVar;
    String NamVar;
}

|=> Object-Serialization is process of converting the state of an object into steam of bytes.

|-> Implement when you want the object to exist beyond the lifetime of the JVM.

|-> Serialized Object can be stored in Database.

|-> Serializable-objects cannot be read and understood by humans so we can acheive security.

|=> Object-Deserialization is the process of getting the state of an object and store it into an object(java.lang.Object).

|-> Before storing its state it checks whether serialVersionUID form input-file/network and .class file serialVersionUID are same.

&nbsp&nbspIf not throw java.io.InvalidClassException.

|=> A Java object is only serializable, if its class or any of its superclasses

implements either the java.io.Serializable interface or

its subinterface, java.io.Externalizable.

|=> Static fields in a class cannot be serialized.

class NamCls implements Serializable
{
    int NumVar;
    static String NamVar = "I won't be serializable";;
}

|=> If you do not want to serialise a variable of a class use transient keyword

class NamCls implements Serializable
{
    int NumVar;
    transient String NamVar;
}

|=> If a class implements serializable then all its sub classes will also be serializable.

|=> If a class has a reference of another class, all the references must be Serializable otherwise serialization process will not be performed. In such case,
NotSerializableException is thrown at runtime.

ContentLicense: CC BY-SA 4.0


问:
How to add active class in pagination with PHP
This is my pagination code:

```<code><div class="pagination">
<a href='?page=1'>1</a>
<a href='?page=2'>1</a>
<a href='?page=2'>1</a>

</div>
</code>```

I want to add class active to the active page. How to add it?

You can also help me make a code to add active class with $_GET['page]

答:
Simply add an if statement onto each row checking if $_GET['page'] equals the current page:

```<code><div class="pagination">
    <a href='?page=1'<? if ($_GET['page'] == 1) { echo ' class="active"'; } ?>>1</a>
    <a href='?page=2'<? if ($_GET['page'] == 2) { echo ' class="active"'; } ?>>2</a>
    <a href='?page=3'<? if ($_GET['page'] == 3) { echo ' class="active"'; } ?>>3</a>
</div>
</code>```

Or, alternatively, you could do the whole thing in a loop which would help you when you want to add more rows:

```<code>for ($i = 1; $i <= 3; $i++) {
    echo "<a href='?page=$i'";
    if ($_GET['page'] == $i) {
        echo ' class="active"';
    }
    echo ">$i</a>";
}
</code>```

Body:
This is my pagination code:

1
1
1

I want to add class active to the active page. How to add it?

You can also help me make a code to add active class with $_GET['page]

Body:
Simply add an if statement onto each row checking if $_GET['page'] equals the current page:

<div class="pagination">
    <a href='?page=1'<? if ($_GET['page'] == 1) { echo ' class="active"'; } ?>>1</a>
    <a href='?page=2'<? if ($_GET['page'] == 2) { echo ' class="active"'; } ?>>2</a>
    <a href='?page=3'<? if ($_GET['page'] == 3) { echo ' class="active"'; } ?>>3</a>
</div>

Or, alternatively, you could do the whole thing in a loop which would help you when you want to add more rows:

for ($i = 1; $i <= 3; $i++) {
    echo "<a href='?page=$i'";
    if ($_GET['page'] == $i) {
        echo ' class="active"';
    }
    echo ">$i</a>";
}


问:
Upper Case Table Names Hibernate Version 5
Is there any property in hibernate.cfg.xml to create tables through Hibernate in Upper Case.

I'm using Hibernate version 5 with MariaDB Version 10

答:
Hibernate has different naming strategies : https://docs.jboss.org/hibernate/orm/5.1/userguide/html_single/chapters/domain/naming.html

The PhysicalNamingStrategy seems to be what you need.


问:
String Functions how to count delimiter in string line
I have a string line like the following :

A:B:C:D:E:F:G:H:I:J:K:L:M

It means delimiter ( : ) count is 12 . This line is valid.

Now suppose you have a following line :

A:B:C:D:E:F:G:H:::::

This line is also valid because it contains 12 delimiter . where 8 values are present and 4 values are blank.

Now the following line should be invalid :

A:B:C:D:E:F: -- Invalid - because it contains only 6 values but expected are 12.

how to do this .. ? I tried the following code , but not getting the desired output :

```<code>String strLine = "A:B:C:D:E:F:G:H:::::" ;
int delimiterCount = 12 ;

String[] ValuesArray = strLine.split(":");
 if(ValuesArray.length != delimiterCounter){
 System.out.println(Invalid);
 }else {
 System.out.println("ValidLine");
 }
</code>```

I am getting the output as Invalid where as it sould be Valid.

答:
Concise Java 8 solution:</p>

```<code>private static boolean isValid(String content, char delimiter, int count) {
    return count == content.chars().filter(c -> c == delimiter).count();
}
</code>```

Body:
I have a string line like the following :

A:B:C:D:E:F:G:H:I:J:K:L:M

It means delimiter ( : ) count is 12 . This line is valid.

Now suppose you have a following line :

A:B:C:D:E:F:G:H:::::

This line is also valid because it contains 12 delimiter . where 8 values are present and 4 values are blank.

Now the following line should be invalid :

A:B:C:D:E:F: -- Invalid - because it contains only 6 values but expected are 12.

how to do this .. ? I tried the following code , but not getting the desired output :

String strLine = "A:B:C:D:E:F:G:H:::::" ;
int delimiterCount = 12 ;

String[] ValuesArray = strLine.split(":");
 if(ValuesArray.length != delimiterCounter){
 System.out.println(Invalid);
 }else {
 System.out.println("ValidLine");
 }

I am getting the output as Invalid where as it sould be Valid.

Body:
Concise Java 8 solution:

private static boolean isValid(String content, char delimiter, int count) {
    return count == content.chars().filter(c -> c == delimiter).count();
}


问:
Why is this brute force algorithm producing the incorrect result?
I'm trying to write a brute-force algorithm that minimises the number of journeys of a herd of cows, subject to the conditions in the docstring.

```<code>def brute_force_cow_transport(cows,limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation

    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)

    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    def weight(sub):
        sum = 0
        for e in sub:
            sum += cows[e]
        return sum

    valid_trips = []
    for part in list(get_partitions(cows)):
        if all(weight(sub) <= limit for sub in part):
            valid_trips.append(part)
    return min(valid_trips)
</code>```

(The function get_partitions and the dictionary cows have been given in the question)

Where have I gone wrong? I've checked the weight function (that evaluates the weight of a given spaceship trip), so it must be in the last 5 lines. I've checked the code over and over, and it returns a sub-optimal answer:

```<code>[['Florence', 'Lola'],
 ['Maggie', 'Milkshake', 'Moo Moo'],
 ['Herman'],
 ['Oreo'],
 ['Millie'],
 ['Henrietta'],
 ['Betsy']]
</code>```

The syntax is fine; there are no errors being produced, yet I have a sub-optimal (but valid) answer. Why is this?

答:
The question here is:

How do I find the shortest sublist in a nested list?

To do this, change the last line to:

```<code>min(valid_trips, key=len)
</code>```

Body:
I'm trying to write a brute-force algorithm that minimises the number of journeys of a herd of cows, subject to the conditions in the docstring.

def brute_force_cow_transport(cows,limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation

    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)

    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    def weight(sub):
        sum = 0
        for e in sub:
            sum += cows[e]
        return sum

    valid_trips = []
    for part in list(get_partitions(cows)):
        if all(weight(sub) <= limit for sub in part):
            valid_trips.append(part)
    return min(valid_trips)

(The function get_partitions and the dictionary cows have been given in the question)

Where have I gone wrong? I've checked the weight function (that evaluates the weight of a given spaceship trip), so it must be in the last 5 lines. I've checked the code over and over, and it returns a sub-optimal answer:

[['Florence', 'Lola'],
 ['Maggie', 'Milkshake', 'Moo Moo'],
 ['Herman'],
 ['Oreo'],
 ['Millie'],
 ['Henrietta'],
 ['Betsy']]

The syntax is fine; there are no errors being produced, yet I have a sub-optimal (but valid) answer. Why is this?

Body:
The question here is:

How do I find the shortest sublist in a nested list?

To do this, change the last line to:

min(valid_trips, key=len)


问:
merge 2 vectors using STL algorithm
I've 2 vectors, namely deals_all and deals_new of FXDeal, where FxDeal is a class

```<code>struct FxDeal
{
    int deal_id_; // primary key
    string ccy_pair_;
    double amount_;
}
</code>```

Both vectors are sorted by the primary key field deal_id_.

How could I merge deals_new into deals_all so that

new deals in deals_new are copied or appended to deals_all, and

deals in deals_all that appear also in deal_new (by primary key
deal_id_), will have field ccy_pair_ and amount_ updated

I'm using c++11.

答:
I would try the following (pseudo-code):</p>

```<code>std::set<FxDeal> deal_set{deals_all.cbegin(), deals_all.cend()};

for (auto const& d : deals_new) {
  auto it = deal_set.find(d);
  if (it != deal_set.end()) {
     FxDeal x = *it;
     // update x with d.ccy_pair_ and d.amount_;
     // this allows adding amounts, for e.g. x.amount_ += d.amount_
     deal_set.erase(it);
     deal_set.insert(x);
  }
  else {
    deal_set.insert(d);
  }
}

deals_all.assign(deal_set.cbegin(), deal_set.cend());
</code>```

Title: merge 2 vectors using STL algorithm

Body:
I've 2 vectors, namely deals_all and deals_new of FXDeal, where FxDeal is a class

struct FxDeal
{
    int deal_id_; // primary key
    string ccy_pair_;
    double amount_;
}

Both vectors are sorted by the primary key field deal_id_.

How could I merge deals_new into deals_all so that

new deals in deals_new are copied or appended to deals_all, and

deals in deals_all that appear also in deal_new (by primary key
deal_id_), will have field ccy_pair_ and amount_ updated

I'm using c++11.

Body:
I would try the following (pseudo-code):

std::set<FxDeal> deal_set{deals_all.cbegin(), deals_all.cend()};

for (auto const& d : deals_new) {
  auto it = deal_set.find(d);
  if (it != deal_set.end()) {
     FxDeal x = *it;
     // update x with d.ccy_pair_ and d.amount_;
     // this allows adding amounts, for e.g. x.amount_ += d.amount_
     deal_set.erase(it);
     deal_set.insert(x);
  }
  else {
    deal_set.insert(d);
  }
}

deals_all.assign(deal_set.cbegin(), deal_set.cend());


问:
Update Exception with Entity-Framework?
Hi,

I am using EntityFramework for my ASP.NET MVC website but have some problems with the update.

This is how my update code looka like :

```<code>using (BissEntities context = new BissEntities())
    {

      if (adCategoryFilter.Id < 1)
        context.AddToAdCategoryFilter(adCategoryFilter);
      else
        context.Refresh(System.Data.Objects.RefreshMode.ClientWins, adCategoryFilter);

      if (context.SaveChanges() > 0)
        return true;
    }
    return false;
</code>```

When executing the context.Refresh i get the following exception :

The element at index 0 in the collection of objects to refresh has a null EntityKey property value or is not attached to this ObjectStateManager.

```<code>Stacktrace :    at System.Data.Objects.ObjectContext.RefreshCheck(Dictionary`2 entities, Object entity, EntityKey key)
   at System.Data.Objects.ObjectContext.AddRefreshKey(Object entityLike, Dictionary`2 entities, Dictionary`2 currentKeys)
   at System.Data.Objects.ObjectContext.RefreshEntities(RefreshMode refreshMode, IEnumerable collection)
   at System.Data.Objects.ObjectContext.Refresh(RefreshMode refreshMode, Object entity)
   at Biss.Models.FilterModel.UpdateCategoryFilter(AdCategoryFilter adCategoryFilter) in C:\Users\Snowman\Documents\Visual Studio 2010\Projects\Biss\Biss\Models\FilterModel.cs:line 86
</code>```

This is not the first time I get this problem. First I thought that it might have to do with the relations in the database but after these was removed from the effected table the same exception remained.

Where does the adCategoryFilter come from?

The adCategoryFilter is instansiated(new) and then filled with data from the ViewObject(from the website). It does have the required data like filter Id (to map the filter to correct row in db).

Pleas explain why Im getting this problem and how I could solve it.

BestRegards

答:
Because your using ASP.NET MVC, your working in a stateless environment. That means, once a request has finished processing, there is no more "Entity Framework Memory", or "The Graph".

So, you need to explicitly tell EF you wish to add or update.

Here's how you do it:

```<code>using (BissEntities context = new BissEntities())
{
  if (adCategoryFilter.Id < 1)
    context.AdCategoryFilters.AddObject(adCategoryFilter);
  else {
     var stub = new AdCategoryFilters { Id = adCategoryFilter.Id };
     context.AdCategoryFilters.Attach(stub);
     context.AdCategoryFilters.ApplyCurrentValues(adCategoryFilter);
  }

  context.SaveChanges();
}
</code>```

That is referred to as the stub technique.

In short, you create a new entity with the same entity key as the entity you are trying to UPDATE (in your case, the entity key is "Id").

You then "attach" this stub (so it's tracked by the EF internal graph), then override the values on this stub with your entity to UPDATE, then save changes.

I can't use UpdateModel, as i have a multi-layered architecture and use POCO's, custom viewmodels, etc - so i have created a custom "UpdateModel" method on my service/repository - which does a (more complicated) version of the above.

Also try not to use "if Id < 1, it's an add" with ASP.NET MVC - as if you forget to bind the ID on the view, it will be passed as 0, so even though you could be doing an update, your above code will try and do an add.

Instead be more explicit - have seperate action methods for Add/Update.

HTH.

Title: Update Exception with Entity-Framework?

Body:
Hi,

I am using EntityFramework for my ASP.NET MVC website but have some problems with the update.

This is how my update code looka like :

using (BissEntities context = new BissEntities())
    {

      if (adCategoryFilter.Id < 1)
        context.AddToAdCategoryFilter(adCategoryFilter);
      else
        context.Refresh(System.Data.Objects.RefreshMode.ClientWins, adCategoryFilter);

      if (context.SaveChanges() > 0)
        return true;
    }
    return false;

When executing the context.Refresh i get the following exception :

The element at index 0 in the collection of objects to refresh has a null EntityKey property value or is not attached to this ObjectStateManager.

Stacktrace :    at System.Data.Objects.ObjectContext.RefreshCheck(Dictionary`2 entities, Object entity, EntityKey key)
   at System.Data.Objects.ObjectContext.AddRefreshKey(Object entityLike, Dictionary`2 entities, Dictionary`2 currentKeys)
   at System.Data.Objects.ObjectContext.RefreshEntities(RefreshMode refreshMode, IEnumerable collection)
   at System.Data.Objects.ObjectContext.Refresh(RefreshMode refreshMode, Object entity)
   at Biss.Models.FilterModel.UpdateCategoryFilter(AdCategoryFilter adCategoryFilter) in C:\Users\Snowman\Documents\Visual Studio 2010\Projects\Biss\Biss\Models\FilterModel.cs:line 86

This is not the first time I get this problem. First I thought that it might have to do with the relations in the database but after these was removed from the effected table the same exception remained.

Where does the adCategoryFilter come from?

The adCategoryFilter is instansiated(new) and then filled with data from the ViewObject(from the website). It does have the required data like filter Id (to map the filter to correct row in db).

Pleas explain why Im getting this problem and how I could solve it.

BestRegards

Body:
Because your using ASP.NET MVC, your working in a stateless environment. That means, once a request has finished processing, there is no more "Entity Framework Memory", or "The Graph".

So, you need to explicitly tell EF you wish to add or update.

Here's how you do it:

using (BissEntities context = new BissEntities())
{
  if (adCategoryFilter.Id < 1)
    context.AdCategoryFilters.AddObject(adCategoryFilter);
  else {
     var stub = new AdCategoryFilters { Id = adCategoryFilter.Id };
     context.AdCategoryFilters.Attach(stub);
     context.AdCategoryFilters.ApplyCurrentValues(adCategoryFilter);
  }

  context.SaveChanges();
}

That is referred to as the stub technique.

In short, you create a new entity with the same entity key as the entity you are trying to UPDATE (in your case, the entity key is "Id").

You then "attach" this stub (so it's tracked by the EF internal graph), then override the values on this stub with your entity to UPDATE, then save changes.

I can't use UpdateModel, as i have a multi-layered architecture and use POCO's, custom viewmodels, etc - so i have created a custom "UpdateModel" method on my service/repository - which does a (more complicated) version of the above.

Also try not to use "if Id < 1, it's an add" with ASP.NET MVC - as if you forget to bind the ID on the view, it will be passed as 0, so even though you could be doing an update, your above code will try and do an add.

Instead be more explicit - have seperate action methods for Add/Update.

HTH.


问:
MySQL JOIN tables with COUNT values

I have the following tables in my database.I only listed the important columns which can be used for joining.

I need to get the following output

Currently I'm using two seperate queries for each COUNT value

For assigned licenses

```<code>select
    products.id,products.name,COUNT(assigned_licenses.id)
from
    deployment_users
inner join
    assigned_licenses
on
    deployment_users.id = assigned_licenses.deployment_user_id
inner join
    products
on
    assigned_licenses.id = products.id
and
    deployment_users.customer_id = 10
group by
    assigned_licenses.id
;
</code>```

For total licenses

```<code>select
    products.id,products.name,COUNT(total_licenses.id)
from
    customers
inner join
    total_licenses
on
    customers.iccode = licenses.iccode
inner join
    products
on
    total_licenses.id = products.id
and
    customers.id = 10
group by
    total_licenses.id
;
</code>```

Since there are more than a 1,000 products that need to be listed,I want to combine them into a single query.How can I do that?

答:
Try joining Both of your query </p>

```<code>SELECT * FROM (
   (First Query) as assigned_licn
   INNER JOIN
   (Second Query) as total_licn
   USING (id)
);
</code>```

Title: MySQL JOIN tables with COUNT values

Body:
I have the following tables in my database.I only listed the important columns which can be used for joining.

I need to get the following output

Currently I'm using two seperate queries for each COUNT value

For assigned licenses

select
    products.id,products.name,COUNT(assigned_licenses.id)
from
    deployment_users
inner join
    assigned_licenses
on
    deployment_users.id = assigned_licenses.deployment_user_id
inner join
    products
on
    assigned_licenses.id = products.id
and
    deployment_users.customer_id = 10
group by
    assigned_licenses.id
;

For total licenses

select
    products.id,products.name,COUNT(total_licenses.id)
from
    customers
inner join
    total_licenses
on
    customers.iccode = licenses.iccode
inner join
    products
on
    total_licenses.id = products.id
and
    customers.id = 10
group by
    total_licenses.id
;

Since there are more than a 1,000 products that need to be listed,I want to combine them into a single query.How can I do that?

Body:
Try joining Both of your query

SELECT * FROM (
   (First Query) as assigned_licn
   INNER JOIN
   (Second Query) as total_licn
   USING (id)
);


问:
Promise inside Array.map or loop alternative?
I was wondering how you would solve the following issue. I have an upload component which accepts multiple files. So onDrop gives me accepted and rejected files (based on extension and size).

From those accepted I need to figure out if they have the correct dimensions and I'm would like to use the browser-image-size package.

This package returns a promise, but as you can see below I need to check this for each file in the accepted argument provided. I tried the following but as you can see this always returns an emty array and undefined.

How do I solve this issue?

const checkDimensions = (file) => {
  return Promise.resolve(file);
}

const handleFiles = (accepted, rejected) => {
  const acceptedFiles = [];
  const errors = [];

  accepted.map(file =>
    checkDimensions(file)
    .catch((error) => errors.push(error))
    .then((file) => acceptedFiles.push(file))
  );

  // both log empty array
  console.log(acceptedFiles);
  console.log(errors);
}

// Logs undefined
console.log(handleFiles(['test file']))```

答:
Your console logs are executed before the checkDimensions had a chance to complete it's work.

```<code>const handleFiles = (accepted, rejected) => {
  const acceptedFiles = [];
  const errors = [];

  accepted.map(file => checkDimensions(file)
    .then(file => acceptedFiles.push(file), error => errors.push(error))
    .then(() => {
      console.log(acceptedFiles);
      console.log(errors);
    });
  );
}
</code>```

A then has an optional second parameter. The difference between catch followed by then versus then with 2 arguments is subtle: If checkDimensions decides to reject a file, the acceptedFiles.push(file) will still be executed.

Body:
Your console logs are executed before the checkDimensions had a chance to complete it's work.

const handleFiles = (accepted, rejected) => {
  const acceptedFiles = [];
  const errors = [];

  accepted.map(file => checkDimensions(file)
    .then(file => acceptedFiles.push(file), error => errors.push(error))
    .then(() => {
      console.log(acceptedFiles);
      console.log(errors);
    });
  );
}

A then has an optional second parameter. The difference between catch followed by then versus then with 2 arguments is subtle: If checkDimensions decides to reject a file, the acceptedFiles.push(file) will still be executed.


问:
pygame.draw.line invalid syntax?
So, I'm following a tutorial which currently has me building the following for a quick look at drawing using pygame functions.

```<code>import pygame, sys
from pygame.locals import *

pygame.init() #has to be called before any other pygame functions

#setup the window
DISPLAYSURF = pygame.display.set_mode((500,400), 0, 32)
pygame.display.set_caption('Drawing')

#colors
black = (0, 0, 0, 0)
white = (255, 255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
BLUE = (0, 0, 255)

#draw on the surface object
DISPLAYSURF.fill(white)
pygame.draw.polygon(DISPLAYSURF, green, ((146,0), (291,106), (236,277),
(56,277), (0,106))
pygame.draw.line(DISPLAYSURF, BLUE, (60, 60), (120, 60), 4)
pygame.draw.line(DISPLAYSURF, BLUE,(120,60), (60,120))
pygame.draw.line(DISPLAYSURF, BLUE,(60,120), (120,120), 4)
pygame.draw.circle(DISPLAYSURF, BLUE, (300,500), 20, 0)
pygame.draw.ellipse(DISPLAYSURF, red, (300, 250, 40, 80), 1)
pygame.draw.rect(DISPLAYSURF, red, (200,150,100,50))

pixObj = pygame.pixelarray(DISPLAYSURF)
pixObj[480][380] = black
pixObj[482][382] = black
pixObj[484][384] = black
pixObj[486][386] = black
pixObj[488][388] = black
del pixObj

#run game loop
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()
</code>```

My problem is that in attempting to run this code, I get an invalid syntax error pointing to the first pygame.draw.line. If this is somehow a typo, I'll be kinda surprised, I retyped those lines several times to make sure they were correct, even double checked the docs to make sure that was still the valid syntax. Any ideas?

答:
Focusing on that line:

pygame.draw.polygon(DISPLAYSURF, green, ((146,0), (291,106), (236,277),
(56,277), (0,106))

Let's make some changes to it, that take valid syntax to valid syntax.

pygame.draw.polygon(DISPLAYSURF, green, ((), (), (), (), ())

pygame.draw.polygon(DISPLAYSURF, green, ()

pygame.draw.polygon(

There are more open parentheses than closing.

If the following lines are correct, you should remove an open paren after "green".

Title: pygame.draw.line invalid syntax?

Body:
So, I'm following a tutorial which currently has me building the following for a quick look at drawing using pygame functions.

import pygame, sys
from pygame.locals import *

pygame.init() #has to be called before any other pygame functions

#setup the window
DISPLAYSURF = pygame.display.set_mode((500,400), 0, 32)
pygame.display.set_caption('Drawing')

#colors
black = (0, 0, 0, 0)
white = (255, 255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
BLUE = (0, 0, 255)

#draw on the surface object
DISPLAYSURF.fill(white)
pygame.draw.polygon(DISPLAYSURF, green, ((146,0), (291,106), (236,277),
(56,277), (0,106))
pygame.draw.line(DISPLAYSURF, BLUE, (60, 60), (120, 60), 4)
pygame.draw.line(DISPLAYSURF, BLUE,(120,60), (60,120))
pygame.draw.line(DISPLAYSURF, BLUE,(60,120), (120,120), 4)
pygame.draw.circle(DISPLAYSURF, BLUE, (300,500), 20, 0)
pygame.draw.ellipse(DISPLAYSURF, red, (300, 250, 40, 80), 1)
pygame.draw.rect(DISPLAYSURF, red, (200,150,100,50))

pixObj = pygame.pixelarray(DISPLAYSURF)
pixObj[480][380] = black
pixObj[482][382] = black
pixObj[484][384] = black
pixObj[486][386] = black
pixObj[488][388] = black
del pixObj

#run game loop
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()

My problem is that in attempting to run this code, I get an invalid syntax error pointing to the first pygame.draw.line. If this is somehow a typo, I'll be kinda surprised, I retyped those lines several times to make sure they were correct, even double checked the docs to make sure that was still the valid syntax. Any ideas?


问:
Is it possible to keep same-named global variables unique across different scripts after importing them?
So I have a few Python scripts that I want to run simultaneously, so I made a new empty Python script that just imports all of my scripts so that I can run all of them with a single script. However, most of the scripts have global variable names in them that are the same name across some of the scripts, but I don't want them conflicting with each other. Is there a way without going into the scripts individually one by one to change the names of every single global variable that I can still "load" all the scripts into a single file and share the same global variable names without them conflicting with each other?

答:
You can create a util.py file and define all your global variables in there. Now, you just need to make changes in only one file if you wish to updated a variable name.

Here's some code:

```<code># util.py

def init():
    global myVar
    myVar = []
</code>```

In another file:

```<code># file.py

import util
</code>```

Body:
You can create a util.py file and define all your global variables in there. Now, you just need to make changes in only one file if you wish to updated a variable name.

Here's some code:

# util.py

def init():
    global myVar
    myVar = []

In another file:

# file.py

import util


问:
Python PyKeyboard
How can I press j and f with the module "PyKeyboard"?

I already got this:

```<code>from pykeyboard import PyKeyboard
k = PyKeyboard()

# To Create an Alt+Tab combo
k.press_key(k.alt_key)
k.tap_key(k.tab_key)
k.release_key(k.alt_key)

while True:
        k.press_key(k.j_key)
        k.press_key(k.f_key)
</code>```

But this isn't working.

Thank you

答:
I think this may work,

```<code>from pykeyboard import PyKeyboard
k = PyKeyboard()

# To Create an Alt+Tab combo
k.press_key(k.alt_key)
k.tap_key(k.tab_key)
k.release_key(k.alt_key)

while True:
    k.press_key(k."j")
    k.press_key(k."f")
</code>```

Credit to:
https://stackoverflow.com/a/32582125

Title: Python PyKeyboard

Body:
How can I press j and f with the module "PyKeyboard"?

I already got this:

from pykeyboard import PyKeyboard
k = PyKeyboard()

# To Create an Alt+Tab combo
k.press_key(k.alt_key)
k.tap_key(k.tab_key)
k.release_key(k.alt_key)

while True:
        k.press_key(k.j_key)
        k.press_key(k.f_key)

But this isn't working.

Thank you

Body:
I think this may work,

from pykeyboard import PyKeyboard
k = PyKeyboard()

# To Create an Alt+Tab combo
k.press_key(k.alt_key)
k.tap_key(k.tab_key)
k.release_key(k.alt_key)

while True:
    k.press_key(k."j")
    k.press_key(k."f")

Credit to:
https://stackoverflow.com/a/32582125


问:
How i can delete a java session attribute value from a javascript?
I have a variable, that sends from java to jsp page :

```<code>String message = "Some message";
request.getSession().setAttribute("message", message);
</code>```

this variable, I create to display messages from the server on the client side using the following code in javaScript:

```<code>var msg = "${message}";
if (msg != "") {
  $("#modalAdd").show();
}
</code>```

I need to delete this variable or its value through js, since output message, I check whether it has any value, and in this time it's always show's message because after displaying the message, i can't erase value of variable.

答:
I solved the problem by removing attribute with jstl code.
I insert into div c:remove tag with javascript after showing the message and it's solve my problem.</p>

```<code>var msg = "${message}";
    if(msg != ""){$("#modalAdd").show();
    document.getElementById('modal-message').innerHTML ='<c:remove var="message" scope="session" /> ';
    }
</code>```

Body:
I have a variable, that sends from java to jsp page :

String message = "Some message";
request.getSession().setAttribute("message", message);

this variable, I create to display messages from the server on the client side using the following code in javaScript:

var msg = "${message}";
if (msg != "") {
  $("#modalAdd").show();
}

I need to delete this variable or its value through js, since output message, I check whether it has any value, and in this time it's always show's message because after displaying the message, i can't erase value of variable.

Body:
I solved the problem by removing attribute with jstl code.
I insert into div c:remove tag with javascript after showing the message and it's solve my problem.

var msg = "${message}";
    if(msg != ""){$("#modalAdd").show();
    document.getElementById('modal-message').innerHTML ='<c:remove var="message" scope="session" /> ';
    }


问:
How do you download a website?
Search engine bots crawl the web and download each page they go to for analysis, right?

How exactly do they download a page? What way do they store the pages?

I am asking because I want to run an analysis on a few webpages. I could scrape the page by going to the address but wouldn't it make more sense to download the pages to my computer and work on them from there?

答: wget --mirror

Title: How do you download a website?

Body: wget --mirror


问:
Verify if there are any selected items in a gridview
im developing an app and implementing an onboarding to ask the user to select certain options that will be displayed in a grid view. I want the user to select and unselect and item for this im using a simple toggleSelected(){selected=!selected} declared in my item entry class.
I also have a button at the bottom that will be disabled if all the items in the gridview have isSelected() = false. What is the best way to check this?
Thanks for the help</p>

答:
One way would be to loop over all the elements and check if any is selected.
But that would be quite resource heavy.

I'd rather suggest that you keep a count of selected elements.
If count != 0, then enable your button.


问:
'Array' with php file
I'm having a problem with this php file. When nicknames or addresses are values that i want to display, it appears a error called Array. I want to be able to return all user information on php variables.

```<code><?php
  $str = '{
    "users": [
        {
            "steamid": "[X:X:XXXXXXXXX]",
            "teamspeakid": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
            "nicknames": [
                "XXXXXXXXX"
            ],
            "addresses": [
                "XX.XX.XXX.XX"
            ]
        },
        {
            "steamid": "[Y:Y:YYYYYYYYY]",
            "teamspeakid": "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY",
            "nicknames": [
                "YYYYYYYYY"
            ],
            "addresses": [
                "YY.YY.YYY.YY"
            ]
        },
        {
            "steamid": "[Z:Z:ZZZZZZZZZ]",
            "teamspeakid": "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
            "nicknames": [
                "ZZZZZZZZZ"
            ],
            "addresses": [
                "ZZ.ZZ.ZZZ.ZZ"
            ]
        }

    ]
}';

$json = json_decode($str);
foreach($json->users as $item)
{
    if($item->steamid == "[X:X:XXXXXXXXX]")
    {
        echo $item->addresses;
    }
}

?>
</code>```

答:
addresses is array by one item.
Edit to:

```<code>foreach($json->users as $key=>$item)
{
    if($item->steamid == "[X:X:XXXXXXXXX]")
    {
        echo $item->addresses[0];
    }
}
</code>```

Title: 'Array' with php file

Body:
I'm having a problem with this php file. When nicknames or addresses are values that i want to display, it appears a error called Array. I want to be able to return all user information on php variables.

<?php
  $str = '{
    "users": [
        {
            "steamid": "[X:X:XXXXXXXXX]",
            "teamspeakid": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
            "nicknames": [
                "XXXXXXXXX"
            ],
            "addresses": [
                "XX.XX.XXX.XX"
            ]
        },
        {
            "steamid": "[Y:Y:YYYYYYYYY]",
            "teamspeakid": "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY",
            "nicknames": [
                "YYYYYYYYY"
            ],
            "addresses": [
                "YY.YY.YYY.YY"
            ]
        },
        {
            "steamid": "[Z:Z:ZZZZZZZZZ]",
            "teamspeakid": "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
            "nicknames": [
                "ZZZZZZZZZ"
            ],
            "addresses": [
                "ZZ.ZZ.ZZZ.ZZ"
            ]
        }

    ]
}';

$json = json_decode($str);
foreach($json->users as $item)
{
    if($item->steamid == "[X:X:XXXXXXXXX]")
    {
        echo $item->addresses;
    }
}

?>

Body:
addresses is array by one item.
Edit to:

foreach($json->users as $key=>$item)
{
    if($item->steamid == "[X:X:XXXXXXXXX]")
    {
        echo $item->addresses[0];
    }
}


问:
Apache Kafka order windowed messages based on their value
I'm trying to find a way to re-order messages within a topic partition and send ordered messages to a new topic.

I have Kafka publisher that sends String messages of the following format:
{system_timestamp}-{event_name}?{parameters}

for example:

```<code>1494002667893-client.message?chatName=1c&messageBody=hello
1494002656558-chat.started?chatName=1c&chatPatricipants=3
</code>```

Also, we add some message key for each message, to send them to the corresponding partition.

What I want to do is reorder events based on {system-timestamp} part of the message and within a 1-minute window, cause our publishers doesn't  guarantee that messages will be sent in accordance with {system-timestamp} value.

For example, we can deliver to the topic, a message with a bigger {system-timestamp} value first.

I've investigated Kafka Stream API and found some examples regarding messages windowing and aggregation:

```<code>Properties streamsConfiguration = new Properties();
        streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, "stream-sorter");
        streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        streamsConfiguration.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181");
        streamsConfiguration.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
        streamsConfiguration.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());

 KStreamBuilder builder = new KStreamBuilder();
 KStream<String, String> stream = builder.stream("events");
 KGroupedStream<String>, String> groupedStream = stream.groupByKey();//grouped events within partion.

    /* commented since I think that I don't need any aggregation, but I guess without aggregation I can't use time windowing.
KTable<Windowed<String>, String> windowedEvents = stream.groupByKey().aggregate(
                () -> "",  // initial value
                (aggKey, value, aggregate) -> aggregate + "",   // aggregating value
                TimeWindows.of(1000), // intervals in milliseconds
                Serdes.String(), // serde for aggregated value
                "test-store"
        );*/
</code>```

But what should I do next with this grouped stream? I don't see any 'sort() (e1,e2) -> e1.compareTo(e2)' methods available, also windows could be applied to methods like aggregation(), reduce() ,count() , but I think that I don't need any messages data manipulations.

How can I re-order message in the 1-minute window and send them to another topic?

答:
Here's an outline:

Create a Processor implementation that:

in process() method, for each message:

reads the timestamp from the message value

inserts into a KeyValueStore using (timestamp, message-key) pair as the key and the message-value as the value. NB this also provides de-duplication. You'll need to provide a custom Serde to serialize the key so that the timestamp comes first, byte-wise, so that ranged queries are ordered by timestamp first.

in the punctuate() method:

reads the store using a ranged fetch from 0 to timestamp - 60'000 (=1 minute)

sends the fetched messages in order using context.forward() and deletes them from the store

The problem with this approach is that punctuate() is not triggered if no new msgs arrive to advance the "stream time". If this is a risk in your case, you can create an external scheduler that sends periodic "tick" messages to each(!) partition of your topic, that your processor should just ignore, but they'll cause punctuate to trigger in the absence of "real" msgs.
KIP-138 will address this limitation by adding explicit support for system-time punctuation:
https://cwiki.apache.org/confluence/display/KAFKA/KIP-138%3A+Change+punctuate+semantics

Body:
I'm trying to find a way to re-order messages within a topic partition and send ordered messages to a new topic.

I have Kafka publisher that sends String messages of the following format:
{system_timestamp}-{event_name}?{parameters}

for example:

1494002667893-client.message?chatName=1c&messageBody=hello
1494002656558-chat.started?chatName=1c&chatPatricipants=3

Also, we add some message key for each message, to send them to the corresponding partition.

What I want to do is reorder events based on {system-timestamp} part of the message and within a 1-minute window, cause our publishers doesn't  guarantee that messages will be sent in accordance with {system-timestamp} value.

For example, we can deliver to the topic, a message with a bigger {system-timestamp} value first.

I've investigated Kafka Stream API and found some examples regarding messages windowing and aggregation:

Properties streamsConfiguration = new Properties();
        streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, "stream-sorter");
        streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        streamsConfiguration.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181");
        streamsConfiguration.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
        streamsConfiguration.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());

 KStreamBuilder builder = new KStreamBuilder();
 KStream<String, String> stream = builder.stream("events");
 KGroupedStream<String>, String> groupedStream = stream.groupByKey();//grouped events within partion.

    /* commented since I think that I don't need any aggregation, but I guess without aggregation I can't use time windowing.
KTable<Windowed<String>, String> windowedEvents = stream.groupByKey().aggregate(
                () -> "",  // initial value
                (aggKey, value, aggregate) -> aggregate + "",   // aggregating value
                TimeWindows.of(1000), // intervals in milliseconds
                Serdes.String(), // serde for aggregated value
                "test-store"
        );*/

But what should I do next with this grouped stream? I don't see any 'sort() (e1,e2) -> e1.compareTo(e2)' methods available, also windows could be applied to methods like aggregation(), reduce() ,count() , but I think that I don't need any messages data manipulations.

How can I re-order message in the 1-minute window and send them to another topic?


答:
Crash you observed is not a java issue it is redhat issue "https://bugzilla.redhat.com/show_bug.cgi?id=546158"

What is Problematic Frame:
It is the top frame resulted in the crash, in your case it is native frame (C) resulted in libC.so file.
Please find more details here

Title: Jvm crash :fatal error has been detected by the Java Runtime Environment

Body:
I had a tomcat crash on live server , which generated hs_err_pid file .In this there is a Problematic frame ->   _wordcopy_fwd_dest_aligned+0x54. I searched in all similar cases of jvm crash but couldn't find whats the meaning of this problematic frame.Any suggestions ?

 #
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGBUS (0x7) at pc=0x00007f61087e3cb4, pid=18886, tid=140051814115072
#
# JRE version: 6.0_37-b06
# Java VM: Java HotSpot(TM) 64-Bit Server VM (20.12-b01 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C  [libc.so.6+0x89cb4]  _wordcopy_fwd_dest_aligned+0x54
#
# If you would like to submit a bug report, please visit:
#   http://java.sun.com/webapps/bugreport/crash.jsp
#

---------------  T H R E A D  ---------------

Current thread (0x00007f6044017000):  JavaThread "ajp-bio-10009-exec-97" daemon [_thread_in_vm, id=28541, stack(0x00007f605a916000,0x00007f605aa17000)]

siginfo:si_signo=SIGBUS: si_errno=0, si_code=2 (BUS_ADRERR), si_addr=0x00007f6059d3f9f8

Registers:
RAX=0x0000000000000038, RBX=0x00007f6059d3f9f9, RCX=0x0000000000000001, RDX=0x000000000000004c
RSP=0x00007f605aa14298, RBP=0x00000006e903e928, RSI=0x00007f6059d3f9f8, RDI=0x00000006e903e928
R8 =0x0000000000000008, R9 =0x00007f61085ecb38, R10=0x00007f60fd010ec1, R11=0x00007f61085d4090
R12=0x00000006e903e928, R13=0x0000000000000268, R14=0x00007f61085f0bc0, R15=0x00007f605aa14430
RIP=0x00007f61087e3cb4, EFLAGS=0x0000000000010202, CSGSFS=0x000000000000e033, ERR=0x0000000000000004
TRAPNO=0x000000000000000e

Top of Stack: (sp=0x00007f605aa14298)
0x00007f605aa14298:   00007f6059d3f9f9 00000006e903e928
0x00007f605aa142a8:   00007f61087dd8ae 0000000000000004
0x00007f605aa142b8:   00007f605aa15b60 00007f605aa142e0
0x00007f605aa142c8:   00007f6044017000 0000000000000268
0x00007f605aa142d8:   00007f6107f313eb 00007f605aa14350
0x00007f605aa142e8:   00007f6108392c00 0000000000000010
0x00007f605aa142f8:   00007f6059d3f9f9 00007f6044017000
0x00007f605aa14308:   00007f60a11b4338 00007f6044017000
0x00007f605aa14318:   00000000ffffffff 00007f6108430701
0x00007f605aa14328:   00000007e00cf808 0000000000000000
0x00007f605aa14338:   00000007e00cf808 00007f605aa14450
0x00007f605aa14348:   00007f6044017000 00007f605aa143f0
0x00007f605aa14358:   00007f60fd010eee 0000000000000268
0x00007f605aa14368:   00007f6107ef6a6c 0000000000000000
0x00007f605aa14378:   00007f60a11b4338 0000000000000004
0x00007f605aa14388:   00000000ffffffff 00007f6108430701
0x00007f605aa14398:   0000000000001389 00007f605aa14460
0x00007f605aa143a8:   00007f6107ef63ad 00007f605aa143b0
0x00007f605aa143b8:   0000000000000000 00007f605aa14450
0x00007f605aa143c8:   00000007e00d2508 0000000000000000
0x00007f605aa143d8:   00000007e00cf808 0000000000000000
0x00007f605aa143e8:   00007f605aa14410 00007f605aa14498
0x00007f605aa143f8:   00007f60fd005a82 0000000000000000
0x00007f605aa14408:   00007f60fd00df58 0000000000000268
0x00007f605aa14418:   0000000400000002 0000000000000010
0x00007f605aa14428:   00007f60a11b4340 00000006e903e918
0x00007f605aa14438:   00007f6059d3f9f9 0000000000001389
0x00007f605aa14448:   0000000000000000 000000071005d290
0x00007f605aa14458:   00007f605aa14458 00000007e015e822
0x00007f605aa14468:   00007f605aa14508 00000007e015f408
0x00007f605aa14478:   0000000000000000 00000007e015e850
0x00007f605aa14488:   00007f605aa14410 00007f605aa144c8

Instructions: (pc=0x00007f61087e3cb4)
0x00007f61087e3c94:   1b 48 85 d2 74 42 4c 8b 1e 48 8b 6e 08 48 83 ef
0x00007f61087e3ca4:   08 48 83 c6 08 e9 98 00 00 00 66 90 48 83 ea 01
0x00007f61087e3cb4:   4c 8b 16 4c 8b 5e 08 0f 85 bf 00 00 00 0f 1f 80
0x00007f61087e3cc4:   00 00 00 00 89 c1 49 d3 e3 44 89 c1 4c 89 d8 49

Register to memory mapping:

RAX=0x0000000000000038 is an unknown value
RBX=0x00007f6059d3f9f9 is an unknown value
RCX=0x0000000000000001 is an unknown value
RDX=0x000000000000004c is an unknown value
RSP=0x00007f605aa14298 is pointing into the stack for thread: 0x00007f6044017000
RBP=


问:
ITaskScheduler::Delete fails
```<code>!define GUIDTaskScheduler "{148BD52A-A2AB-11CE-B11F-00AA00530503}"
!define GUIDITaskScheduler "{148BD527-A2AB-11CE-B11F-00AA00530503}"

Function DeleteTask
    !define DeleteTask "!insertmacro  _DeleteTask"
    !macro _DeleteTask _TASK _RESULT
        Push ${_Task}
        Call DeleteTask
        Pop ${_RESULT}
    !macroend
    Exch $0
    Push $1
    Push $2
    StrCpy $0 false
    System::Call "ole32::CoCreateInstance(g'${GUIDTaskScheduler}',i0,i11,g '${GUIDITaskScheduler}',*i.r1)i.r2"
    IntCmp $2 0 0 +4
    System::Call '$1->7(w r0)i.r2'
    IntCmp $2 0 0 +2
    StrCpy $0 true
    Pop $2
    Pop $1
    END:
    Exch $0
FunctionEnd

${DeleteTask} "TaskName" $0
Pop $0
</code>```

$0 should set to true or 1 but it's false. The task isn't deleting.

What am I doing wrong here?

答:
I've figured it out. This was bothering me to no end but I've managed to figure it out after rewriting it. Here's the working function.

```<code>Function DeleteTask
    !define TaskGUID    `{148BD52A-A2AB-11CE-B11F-00AA00530503}`
    !define ITaskGUID   `{148BD527-A2AB-11CE-B11F-00AA00530503}`
    !define OLE         `ole32::CoCreateInstance(g"${TaskGUID}",`
    !define OLE32       `${OLE}i0,i11,g "${ITaskGUID}",*i.r1)i.r2`
    !define DeleteTask "!insertmacro _DeleteTask"
    !macro _DeleteTask _RESULT _TASK
        Push ${_Task}
        Call DeleteTask
        Pop ${_RESULT}
    !macroend
    Exch $0
    Push $0
    Push $1
    Push $2
    Push $3
    StrCpy $3 false
    System::Call `${OLE32}`
    IntCmp $2 0 0 +5
    System::Call "$1->7(w r0)i.r2"
    IntCmp $2 0 0 +3
    System::Call "$1->2()"
    StrCpy $3 true
    Pop $2
    Pop $1
    Pop $0
    Exch $3
FunctionEnd

;= $0 Should return either true on success or false on failure.
${DeleteTask} $0 "Task Name"
StrCmpS $0 true 0 +2
DetailPrint "${TASK} was successfully deleted."
DetailPrint "Failed to remove the task ${TASK}."
</code>```

Thanks goes to Anders for his help.

Title: ITaskScheduler::Delete fails

Body:
!define GUIDTaskScheduler "{148BD52A-A2AB-11CE-B11F-00AA00530503}"
!define GUIDITaskScheduler "{148BD527-A2AB-11CE-B11F-00AA00530503}"

Function DeleteTask
    !define DeleteTask "!insertmacro  _DeleteTask"
    !macro _DeleteTask _TASK _RESULT
        Push ${_Task}
        Call DeleteTask
        Pop ${_RESULT}
    !macroend
    Exch $0
    Push $1
    Push $2
    StrCpy $0 false
    System::Call "ole32::CoCreateInstance(g'${GUIDTaskScheduler}',i0,i11,g '${GUIDITaskScheduler}',*i.r1)i.r2"
    IntCmp $2 0 0 +4
    System::Call '$1->7(w r0)i.r2'
    IntCmp $2 0 0 +2
    StrCpy $0 true
    Pop $2
    Pop $1
    END:
    Exch $0
FunctionEnd

${DeleteTask} "TaskName" $0
Pop $0

$0 should set to true or 1 but it's false. The task isn't deleting.

What am I doing wrong here?

Body:
I've figured it out. This was bothering me to no end but I've managed to figure it out after rewriting it. Here's the working function.

Function DeleteTask
    !define TaskGUID    `{148BD52A-A2AB-11CE-B11F-00AA00530503}`
    !define ITaskGUID   `{148BD527-A2AB-11CE-B11F-00AA00530503}`
    !define OLE         `ole32::CoCreateInstance(g"${TaskGUID}",`
    !define OLE32       `${OLE}i0,i11,g "${ITaskGUID}",*i.r1)i.r2`
    !define DeleteTask "!insertmacro _DeleteTask"
    !macro _DeleteTask _RESULT _TASK
        Push ${_Task}
        Call DeleteTask
        Pop ${_RESULT}
    !macroend
    Exch $0
    Push $0
    Push $1
    Push $2
    Push $3
    StrCpy $3 false
    System::Call `${OLE32}`
    IntCmp $2 0 0 +5
    System::Call "$1->7(w r0)i.r2"
    IntCmp $2 0 0 +3
    System::Call "$1->2()"
    StrCpy $3 true
    Pop $2
    Pop $1
    Pop $0
    Exch $3
FunctionEnd

;= $0 Should return either true on success or false on failure.
${DeleteTask} $0 "Task Name"
StrCmpS $0 true 0 +2
DetailPrint "${TASK} was successfully deleted."
DetailPrint "Failed to remove the task ${TASK}."

Thanks goes to Anders for his help.


问:
How to render a view from service class in symfony?
I'm trying to make a function in my service class, that render a twig page. I've tried to do like this:
service.yml:

```<code>********
parameters:
    error.class: AppBundle\Utils\Error
services:
    app.error:
        class: '%error.class%'
        arguments: [@templating]
</code>```

Error.php (service class):

```<code>****
class Error
{
    public function __construct($templating)
    {
        $this->templating = $templating;
    }

    public function redirectToError($condition,$message)
    {
        if($condition){
            return $this->templating->render('default/error.html.twig',array(
                'error_message' => $message,
            ));
        }
    }

}
</code>```

and error.html.twig that have some random text to see if it gets there.

After that I get this answer from browser:

Can somebody to tell me what is the problem?

答:
You should put ' around @templating

```<code>services:
    app.error:
        class: AppBundle\Utils\Error
        arguments: ['@templating']
</code>```

Body:
I'm trying to make a function in my service class, that render a twig page. I've tried to do like this:
service.yml:

********
parameters:
    error.class: AppBundle\Utils\Error
services:
    app.error:
        class: '%error.class%'
        arguments: [@templating]

Error.php (service class):

****
class Error
{
    public function __construct($templating)
    {
        $this->templating = $templating;
    }

    public function redirectToError($condition,$message)
    {
        if($condition){
            return $this->templating->render('default/error.html.twig',array(
                'error_message' => $message,
            ));
        }
    }

}

and error.html.twig that have some random text to see if it gets there.

After that I get this answer from browser:

Can somebody to tell me what is the problem?

Body:
You should put ' around @templating

services:
    app.error:
        class: AppBundle\Utils\Error
        arguments: ['@templating']


问:
How to convert String value of xml file into integer
i have a java code which parse xml file to get the id of the topic, i want to convert this String into integer, i have used BigInteger but it does not work: </p>

```<code>    public void topicid(){
        File inputFile = new File("D:\\Topic.xml");
        DocumentBuilderFactory dbFactory  = DocumentBuilderFactory.newInstance();
        try {
             DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
             Document doc = dBuilder.parse(inputFile);

             doc.getDocumentElement().normalize();

             System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
             NodeList nList = doc.getElementsByTagName("top");

             for (int temp = 0; temp < nList.getLength(); temp++) {
             Node nNode = nList.item(temp);
             System.out.println("----------------------------------------------------------------------------");
             System.out.println("\n La requete :" + nNode.getNodeName());
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
               Element eElement = (Element) nNode;
           String idtopic=eElement.getElementsByTagName("querytweettime").item(0).getTextContent();
           System.out.println("l'id de la requete est:" + idtopic);
          BigInteger idq= new BigInteger(idtopic);

   System.out.println("l'id final de topic :" +idq);

}
</code>```

答:
The javax.xml.bind.DatatypeConverter class has all conversions needed for XML.

For parsing an int:

```<code>int i = DatatypeConverter.parseInt(string);
</code>```

There are other methods for long, short, BigInteger, ...

Body:
i have a java code which parse xml file to get the id of the topic, i want to convert this String into integer, i have used BigInteger but it does not work:

    public void topicid(){
        File inputFile = new File("D:\\Topic.xml");
        DocumentBuilderFactory dbFactory  = DocumentBuilderFactory.newInstance();
        try {
             DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
             Document doc = dBuilder.parse(inputFile);

             doc.getDocumentElement().normalize();

             System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
             NodeList nList = doc.getElementsByTagName("top");

             for (int temp = 0; temp < nList.getLength(); temp++) {
             Node nNode = nList.item(temp);
             System.out.println("----------------------------------------------------------------------------");
             System.out.println("\n La requete :" + nNode.getNodeName());
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
               Element eElement = (Element) nNode;
           String idtopic=eElement.getElementsByTagName("querytweettime").item(0).getTextContent();
           System.out.println("l'id de la requete est:" + idtopic);
          BigInteger idq= new BigInteger(idtopic);

   System.out.println("l'id final de topic :" +idq);

}

Body:
The javax.xml.bind.DatatypeConverter class has all conversions needed for XML.

For parsing an int:

int i = DatatypeConverter.parseInt(string);

There are other methods for long, short, BigInteger, ...


问:
Alternative to OverLibWrapper for displaying control tooltips in ASP.NET
I looked into a nice way to display tooltips dynamically and I found OverLibWrapper, which was exactly what I needed.

I have all the tooltip data stored in a custom configuration section, the tooltips are bound to their respective controls during Page_Load.

I did a quick test and worked fine. The problem came up when I realized that OverLibWrapper didn't work on masterpages. Our website has uses quite a few masterpages, so taking them out isn't an option.

I was wondering if there's anything like OverLibWrapper that I could use.

EDIT:

What I'm looking for is a control to display good-looking tooltips on mouseover preferably instantly like overlib (nothing fancy because I'm just displaying raw text) in a dynamic way, because the tooltip property in ASP.NET is not very pretty and takes a while to appear. For example let's say I have a collection of Messages:

```<code>class Message
{
    string ctrlid, msgtodisplay;
}
</code>```

And when the page is loaded:

```<code>TooltipManager manager;
foreach(var m in messages)
{
    Tooltip tltp=new Tooltip;
    m.ControlID=m.ctrlid;
    m.Message=m.msgtodisplay;
    manager.AddTooltip(tltp);
}
</code>```

So basically something that offers the functionality of Tooltip and TooltipManager.

答:
Well I finally solved my problem:

I've used this function to find any control (works with masterpages):

```<code>public static Control FindControlRecursive(Control root, string id)
{
    if (id == string.Empty)
        return null;

    if (root.ID == id)
        return root;

    foreach (Control c in root.Controls)
    {
        Control t = FindControlRecursive(c, id);
        if (t != null)
            return t;
    }
    return null;
}
</code>```

And this method:

```<code>public static void load(Page page, string pageFileName)
{
    foreach (ConfiguracionElem elem in Configuracion.GetConfig(pageFileName).Tooltips)
    {
        WebControl ctrl = (WebControl)FindControlRecursive(page, elem.controlid);
        if (ctrl == null)
            throw new ControlNotFoundException("There's no control'"+elem.controlid+"'")
        else
        {
            ctrl.Attributes.Add("onmouseover","return overlib('"+elem.message+"');");
            ctrl.Attributes.Add("onmouseout","return nd();");
        }
    }
}
</code>```

I added the Overlib library manually to a script folder, then I iterated through my Custom Configuration Section (where my tooltip data is stored) to add the javascript attributes dynamically.

Body:
I looked into a nice way to display tooltips dynamically and I found OverLibWrapper, which was exactly what I needed.

I have all the tooltip data stored in a custom configuration section, the tooltips are bound to their respective controls during Page_Load.

I did a quick test and worked fine. The problem came up when I realized that OverLibWrapper didn't work on masterpages. Our website has uses quite a few masterpages, so taking them out isn't an option.

I was wondering if there's anything like OverLibWrapper that I could use.

EDIT:

What I'm looking for is a control to display good-looking tooltips on mouseover preferably instantly like overlib (nothing fancy because I'm just displaying raw text) in a dynamic way, because the tooltip property in ASP.NET is not very pretty and takes a while to appear. For example let's say I have a collection of Messages:

class Message
{
    string ctrlid, msgtodisplay;
}

And when the page is loaded:

TooltipManager manager;
foreach(var m in messages)
{
    Tooltip tltp=new Tooltip;
    m.ControlID=m.ctrlid;
    m.Message=m.msgtodisplay;
    manager.AddTooltip(tltp);
}

So basically something that offers the functionality of Tooltip and TooltipManager.

Body:
Well I finally solved my problem:

I've used this function to find any control (works with masterpages):

public static Control FindControlRecursive(Control root, string id)
{
    if (id == string.Empty)
        return null;

    if (root.ID == id)
        return root;

    foreach (Control c in root.Controls)
    {
        Control t = FindControlRecursive(c, id);
        if (t != null)
            return t;
    }
    return null;
}

And this method:

public static void load(Page page, string pageFileName)
{
    foreach (ConfiguracionElem elem in Configuracion.GetConfig(pageFileName).Tooltips)
    {
        WebControl ctrl = (WebControl)FindControlRecursive(page, elem.controlid);
        if (ctrl == null)
            throw new ControlNotFoundException("There's no control'"+elem.controlid+"'")
        else
        {
            ctrl.Attributes.Add("onmouseover","return overlib('"+elem.message+"');");
            ctrl.Attributes.Add("onmouseout","return nd();");
        }
    }
}

I added the Overlib library manually to a script folder, then I iterated through my Custom Configuration Section (where my tooltip data is stored) to add the javascript attributes dynamically.


问:
Handle.exe does not unlock
I am running handle.exe to unlock files that are holding in a designated folder in electron app. When I do it in a development mode "npm start" it is working yet, when I "npm run build" and run the compiled exe I get "handle is invalid error".

The folder is created by the electron itself and at the end of the app the folder needs to be deleted. I cannot kill all tasks that are holdin lock for the folder content because electron alse holds a lock. moreover, I if I avoid to kill electron then its lock prevents me to delete the folder.

I am running bat file like this given below (bat name is kill.bat and takes two parameters):

for /f "tokens=3,6 skip=5 delims=: " %%i in ('%~f1 -accepteula %~f2') do %~f1 -c %%j -y -p %%i

so the usage is given as: kill.bat handle.exe FOLDER_PATH

Even I build the app as admin handle.exe cannot perform the unlocking

答:
It turned out to be that my computer needed windows updates. After I got the updates the problem vanished. Most probably the updates were wannacry updates.

If you encounter a problem such like this try to make your updates

Title: Handle.exe does not unlock


问:
Excel VBA - Unable to change year in date format in TextBox in Userform
I have a userform with two TextBox fields for dates. When I fill in the textboxes and press "tab" or click on the other box, the field will first fill in a cell on a worksheet and then format the date in the textbox (This allows for date entry in different formats such as 1/1/17, no matter what it should return as mmm dd, yyyy).

Here's my issue. Everything works absolutely perfectly, but the year is always stuck on 2017. I tried entering the date in all formats, the month and date change accordingly, but the year remains on 2017.

Here is the code below:

```<code>Private Sub Button_OK_Click()

Sheets("Inputs").Range("C18").Value = Format(TextBox_StartDate.Value, "mmm dd, yyyy")
TextBox_StartDate.Value = Format(Sheets("Inputs").Range("C18").Text, "mmm dd, yyyy")
Sheets("Inputs").Range("C19").Value = Format(TextBox_EndDate.Value, "mmm dd, yyyy")
TextBox_EndDate.Value = Format(Sheets("Inputs").Range("C19").Text, "mmm dd, yyyy")
If TextBox_StartDate.Value = "" Or TextBox_EndDate.Value = "" Then
    MsgBox ("Start and End Dates must be filled in to continue.")
ElseIf Sheets("Inputs").Range("C18").Value > Sheets("Inputs").Range("C19").Value Then
    MsgBox ("End Date must be after Start Date.")
ElseIf Not (IsNumeric(Sheets("Inputs").Range("C18").Value) And IsNumeric(Sheets("Inputs").Range("C18").Value)) Then
    MsgBox ("Date fields must be filled in properly.")
Else
    Continue = True
    Unload Me
End If
End Sub

Private Sub TextBox_StartDate_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 9 Then
    Sheets("Inputs").Range("C18").Value = Format(TextBox_StartDate.Value, "mmm dd, yyyy")
     TextBox_StartDate.Value = Format(Sheets("Inputs").Range("C18").Text, "mmm dd, yyyy")
    Sheets("Inputs").Range("C19").Value = Format(TextBox_EndDate.Value, "mmm dd, yyyy")
     TextBox_EndDate.Value = Format(Sheets("Inputs").Range("C19").Text, "mmm dd, yyyy")
End If
End Sub
</code>```

Any help would be much appreciated!

答:
```<code>Sheets("Inputs").Range("C18").Value = Format(DateValue(TextBox_StartDate.Value), "mmm dd, yyyy")
</code>```

Body:
I have a userform with two TextBox fields for dates. When I fill in the textboxes and press "tab" or click on the other box, the field will first fill in a cell on a worksheet and then format the date in the textbox (This allows for date entry in different formats such as 1/1/17, no matter what it should return as mmm dd, yyyy).

Here's my issue. Everything works absolutely perfectly, but the year is always stuck on 2017. I tried entering the date in all formats, the month and date change accordingly, but the year remains on 2017.

Here is the code below:

Private Sub Button_OK_Click()

Sheets("Inputs").Range("C18").Value = Format(TextBox_StartDate.Value, "mmm dd, yyyy")
TextBox_StartDate.Value = Format(Sheets("Inputs").Range("C18").Text, "mmm dd, yyyy")
Sheets("Inputs").Range("C19").Value = Format(TextBox_EndDate.Value, "mmm dd, yyyy")
TextBox_EndDate.Value = Format(Sheets("Inputs").Range("C19").Text, "mmm dd, yyyy")
If TextBox_StartDate.Value = "" Or TextBox_EndDate.Value = "" Then
    MsgBox ("Start and End Dates must be filled in to continue.")
ElseIf Sheets("Inputs").Range("C18").Value > Sheets("Inputs").Range("C19").Value Then
    MsgBox ("End Date must be after Start Date.")
ElseIf Not (IsNumeric(Sheets("Inputs").Range("C18").Value) And IsNumeric(Sheets("Inputs").Range("C18").Value)) Then
    MsgBox ("Date fields must be filled in properly.")
Else
    Continue = True
    Unload Me
End If
End Sub

Private Sub TextBox_StartDate_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 9 Then
    Sheets("Inputs").Range("C18").Value = Format(TextBox_StartDate.Value, "mmm dd, yyyy")
     TextBox_StartDate.Value = Format(Sheets("Inputs").Range("C18").Text, "mmm dd, yyyy")
    Sheets("Inputs").Range("C19").Value = Format(TextBox_EndDate.Value, "mmm dd, yyyy")
     TextBox_EndDate.Value = Format(Sheets("Inputs").Range("C19").Text, "mmm dd, yyyy")
End If
End Sub

Any help would be much appreciated!


问:
Trying to move two objects at the same time with arrow keys and WASD
Hey guys I am making a game in which characters can be moved with WASD and Arrow keys. I got them to move but i can not make them move at the same time. One can not be moving for the other shape to move. Is there a way to check for WASD and arrow presses simultaneously? Hope you guys can help. Thanks in advance.

Here is the code:

```<code>// The "SoccerGame" class.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class SoccerGame extends Applet implements KeyListener
{
    //x and y values of the player 1 and 2's character and the ball
    int x1 = 0, y1 = 275, x2 = 780, y2 = 275, xBall = 400, yBall = 275;

    public void init ()
    {
        this.requestFocus ();
        addKeyListener (this);

        //setting size of program
        setSize (800, 550);

    } // init method

    public void paint (Graphics g)
    {
        //Player 1
        g.setColor (Color.red);
        g.fillRect (x1, y1, 30, 30);

        //Player2
        g.setColor (Color.black);
        g.fillRect (x2, y2, 30, 30);

        //Ball
        g.setColor (Color.blue);
        g.fillRect (xBall, yBall, 30, 30);

    } // paint method

    public void keyPressed (KeyEvent e)
    {
        //Moving Player 1 with arrow Keys
        if (e.getKeyCode () == e.VK_W)
        {
            y1 = y1 - 10;
        }
        if (e.getKeyCode () == e.VK_S)
        {
            y1 = y1 + 10;
        }
        if (e.getKeyCode () == e.VK_A)
        {
            x1 = x1 - 10;
        }
        if (e.getKeyCode () == e.VK_D)
        {
            x1 = x1 + 10;
        }

        //Moving player 2 with WASD
        if (e.getKeyCode () == e.VK_UP)
        {
            y2 = y2 - 10;
        }
        if (e.getKeyCode () == e.VK_DOWN)
        {
            y2 = y2 + 10;
        }
        if (e.getKeyCode () == e.VK_LEFT)
        {
            x2 = x2 - 10;
        }
        if (e.getKeyCode () == e.VK_RIGHT)
        {
            x2 = x2 + 10;
        }

        repaint ();
    }

    public void keyReleased (KeyEvent e)
    {
    }

    public void keyTyped (KeyEvent e)
    {
    }
} // SoccerGame class
</code>```

答:
Don't use a KeyListener (as you have been suggested in your other questions).

Instead you should be using Key Bindings. You will then need to track which keys have been pressed and use a Swing Timer to schedule the animation.

Check out Motion Using the Keyboard.

The KeyboardAnimation.java example shows how this can be done.

Body:
Hey guys I am making a game in which characters can be moved with WASD and Arrow keys. I got them to move but i can not make them move at the same time. One can not be moving for the other shape to move. Is there a way to check for WASD and arrow presses simultaneously? Hope you guys can help. Thanks in advance.

Here is the code:

// The "SoccerGame" class.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class SoccerGame extends Applet implements KeyListener
{
    //x and y values of the player 1 and 2's character and the ball
    int x1 = 0, y1 = 275, x2 = 780, y2 = 275, xBall = 400, yBall = 275;

    public void init ()
    {
        this.requestFocus ();
        addKeyListener (this);

        //setting size of program
        setSize (800, 550);

    } // init method

    public void paint (Graphics g)
    {
        //Player 1
        g.setColor (Color.red);
        g.fillRect (x1, y1, 30, 30);

        //Player2
        g.setColor (Color.black);
        g.fillRect (x2, y2, 30, 30);

        //Ball
        g.setColor (Color.blue);
        g.fillRect (xBall, yBall, 30, 30);

    } // paint method

    public void keyPressed (KeyEvent e)
    {
        //Moving Player 1 with arrow Keys
        if (e.getKeyCode () == e.VK_W)
        {
            y1 = y1 - 10;
        }
        if (e.getKeyCode () == e.VK_S)
        {
            y1 = y1 + 10;
        }
        if (e.getKeyCode () == e.VK_A)
        {
            x1 = x1 - 10;
        }
        if (e.getKeyCode () == e.VK_D)
        {
            x1 = x1 + 10;
        }

        //Moving player 2 with WASD
        if (e.getKeyCode () == e.VK_UP)
        {
            y2 = y2 - 10;
        }
        if (e.getKeyCode () == e.VK_DOWN)
        {
            y2 = y2 + 10;
        }
        if (e.getKeyCode () == e.VK_LEFT)
        {
            x2 = x2 - 10;
        }
        if (e.getKeyCode () == e.VK_RIGHT)
        {
            x2 = x2 + 10;
        }

        repaint ();
    }

    public void keyReleased (KeyEvent e)
    {
    }

    public void keyTyped (KeyEvent e)
    {
    }
} // SoccerGame class


问:
Calculate HTTPS POST Request size
I have a middlet that sends data to a servlet.

Anyone knows how can I calculate the size of request of the middlet in a servlet?

I'm tring to sum of request header + request size + certificate size
Is it correct?

With this I'm trying to recreate the request:

http://wikis.sun.com/display/WebServerdocs/Analyzing+SSL+Requests+and+Responses

答:
I'm pretty sure that there is no simple way.

In fact, I'm not even sure this is a meaningful thing to measure.  The request header and body are part of the HTTP application protocol.  The certificate is sent as part of SSL / TLS setup ... before the HTTP stuff starts.  And once SSL / TLS has started, the HTTP protocol is run "on top of" the SSL / TLS channel.

Even just measuring the amount of data in a HTTP request is tricky.  A typical HTTP stack does not assemble the entire request message in one place, and does not keep a running total of the amount of data sent.  Depending on the HTTP stack that you are using, you could (in theory) arrange to use a custom socket factory and socket streams that count the bytes sent.

Title: Calculate HTTPS POST Request size