问:
How should I pass a variable to another class?
I have declared a variable  named public static  String parameterForURL which I need to pass SendRequest class so that total URL would be together like
URL=http://www.eurekabd.com/shakil/home.php/?+shaki,123.
But Server is receiving  /shakil/shakil.php/?[Ljava.lang.String;@ce6cdf7

```<code>public static  String parameterForURL = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
    parameterForURL ="shakil,123";

    doorOpenButtonActionClass.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            new SendRequest().execute();
            resultContainer="";
        }
    });
}

public class SendRequest extends AsyncTask<String, Void, String> {

    protected String doInBackground(String[] paramparameterForURL) {

        Log.v("Passed=",paramparameterForURL.toString());

        try{
            Log.v("Passed=",paramparameterForURL.toString());
            //String serv_url="http://www.eurekabd.com/shakil/home.php"+paramparameterForURL.toString();

            serv_url="http://192.168.0.109/shakil/shakil.php/?"+paramparameterForURL;
            //serv_url += paramparameterForURL;
            Log.e("Server Url",serv_url.toString());
            URL url = new URL(serv_url);
        }
    }
}
</code>```

**How to make can i pass this paramparameterForURL variable so that i can get my desired out put **

答:
First of all, you do not need a public static variable at all here. Instead, just pass the value directly to the execute() method of AsyncTask:

```<code>new SendRequest().execute("shakil,123");
</code>```

If you want to store the parameter in a variable, make it a local variable, not a static class variable:

```<code>String paramForURL = "shakil,123";
new SendRequest().execute(paramForURL);
</code>```

Now to recieve the variable, you need to get it out of the array parameter:

```<code> protected String doInBackground(String[] paramparameterForURL) {

    Log.v("Passed=",paramparameterForURL[0]);
    // ...
}
</code>```

The problem with your original code is that you are converting an array to a String. Instead, you need to get an element of the array by indexing as shown above.

Body:
I have declared a variable  named public static  String parameterForURL which I need to pass SendRequest class so that total URL would be together like
URL=http://www.eurekabd.com/shakil/home.php/?+shaki,123.
But Server is receiving  /shakil/shakil.php/?[Ljava.lang.String;@ce6cdf7

public static  String parameterForURL = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
    parameterForURL ="shakil,123";

    doorOpenButtonActionClass.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            new SendRequest().execute();
            resultContainer="";
        }
    });
}

public class SendRequest extends AsyncTask<String, Void, String> {

    protected String doInBackground(String[] paramparameterForURL) {

        Log.v("Passed=",paramparameterForURL.toString());

        try{
            Log.v("Passed=",paramparameterForURL.toString());
            //String serv_url="http://www.eurekabd.com/shakil/home.php"+paramparameterForURL.toString();

            serv_url="http://192.168.0.109/shakil/shakil.php/?"+paramparameterForURL;
            //serv_url += paramparameterForURL;
            Log.e("Server Url",serv_url.toString());
            URL url = new URL(serv_url);
        }
    }
}

**How to make can i pass this paramparameterForURL variable so that i can get my desired out put **

Body:
First of all, you do not need a public static variable at all here. Instead, just pass the value directly to the execute() method of AsyncTask:

new SendRequest().execute("shakil,123");

If you want to store the parameter in a variable, make it a local variable, not a static class variable:

String paramForURL = "shakil,123";
new SendRequest().execute(paramForURL);

Now to recieve the variable, you need to get it out of the array parameter:

 protected String doInBackground(String[] paramparameterForURL) {

    Log.v("Passed=",paramparameterForURL[0]);
    // ...
}

The problem with your original code is that you are converting an array to a String. Instead, you need to get an element of the array by indexing as shown above.


来源: stackexchange

问:
Pandas: append row to DataFrame with multiindex in columns
I have a DataFrame with a multiindex in the columns and would like to use dictionaries to append new rows.

Let's say that each row in the DataFrame is a city. The columns contains "distance" and "vehicle". And each cell would be the percentage of the population that chooses this vehicle for this distance.

I'm constructing an index like this:

```<code>index_tuples=[]

for distance in ["near", "far"]:
    for vehicle in ["bike", "car"]:
        index_tuples.append([distance, vehicle])

index = pd.MultiIndex.from_tuples(index_tuples, names=["distance", "vehicle"])
</code>```

Then I'm creating a dataframe:

```<code>dataframe = pd.DataFrame(index=["city"], columns = index)
</code>```

The structure of the dataframe looks good. Although pandas has added Nans as default values ?

Now I would like to set up a dictionary for the new city and add it:

```<code>my_home_city = {"near":{"bike":1, "car":0},"far":{"bike":0, "car":1}}
dataframe["my_home_city"] = my_home_city
</code>```

But this fails:

ValueError: Length of values does not match length of index

Here is the complete error message (pastebin)

UPDATE:

Thank you for all the good answers. I'm afraid I've oversimplified the problem in my example. Actually my index is nested with 3 levels (and it could become more).

So I've accepted the universal answer of converting my dictionary into a list of tuples. This might not be as clean as the other approaches but works for any multiindex setup.

答:
You can append to you dataframe like this:

```<code>my_home_city = {"near":{"bike":1, "car":0},"far":{"bike":0, "car":1}}
dataframe.append(pd.DataFrame.from_dict(my_home_city).unstack().rename('my_home_city'))
</code>```

Output:

```<code>distance     near       far
vehicle      bike  car bike  car
city          NaN  NaN  NaN  NaN
my_home_city    1    0    0    1
</code>```

The trick is to create the dataframe row with from_dict then unstack to get structure of your original dataframe with multiindex columns then rename to get index and append.

Or if you don't want to create the empty dataframe first you can use this method to create the dataframe with the new data.

```<code>pd.DataFrame.from_dict(my_home_city).unstack().rename('my_home_city').to_frame().T
</code>```

Output:

```<code>              far     near
             bike car bike car
my_home_city    0   1    1   0
</code>```

Explained:

```<code>pd.DataFrame.from_dict(my_home_city)

      far  near
bike    0     1
car     1     0
</code>```

Now, let's unstack to create multiindex and get to that new dataframe into the structure of the original dataframe.

```<code>pd.DataFrame.from_dict(my_home_city).unstack()

far   bike    0
      car     1
near  bike    1
      car     0
dtype: int64
</code>```

We use rename to give that series a name which becomes the index label of that dataframe row when appended to the original dataframe.

```<code>far   bike    0
      car     1
near  bike    1
      car     0
Name: my_home_city, dtype: int64
</code>```

Now if you converted that series to a frame and transposed it would look very much like a new row, however, there is no need to do this because, Pandas does intrinsic data alignment, so appending this series to the dataframe will auto-align and add the new dataframe record.

```<code>dataframe.append(pd.DataFrame.from_dict(my_home_city).unstack().rename('my_home_city'))
distance     near       far
vehicle      bike  car bike  car
city          NaN  NaN  NaN  NaN
my_home_city    1    0    0    1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a DataFrame with a multiindex in the columns and would like to use dictionaries to append new rows.

Let's say that each row in the DataFrame is a city. The columns contains "distance" and "vehicle". And each cell would be the percentage of the population that chooses this vehicle for this distance.

I'm constructing an index like this:

index_tuples=[]

for distance in ["near", "far"]:
    for vehicle in ["bike", "car"]:
        index_tuples.append([distance, vehicle])

index = pd.MultiIndex.from_tuples(index_tuples, names=["distance", "vehicle"])

Then I'm creating a dataframe:

dataframe = pd.DataFrame(index=["city"], columns = index)

The structure of the dataframe looks good. Although pandas has added Nans as default values ?

Now I would like to set up a dictionary for the new city and add it:

my_home_city = {"near":{"bike":1, "car":0},"far":{"bike":0, "car":1}}
dataframe["my_home_city"] = my_home_city

But this fails:

ValueError: Length of values does not match length of index

Here is the complete error message (pastebin)

UPDATE:

Thank you for all the good answers. I'm afraid I've oversimplified the problem in my example. Actually my index is nested with 3 levels (and it could become more).

So I've accepted the universal answer of converting my dictionary into a list of tuples. This might not be as clean as the other approaches but works for any multiindex setup.

Body:
You can append to you dataframe like this:

my_home_city = {"near":{"bike":1, "car":0},"far":{"bike":0, "car":1}}
dataframe.append(pd.DataFrame.from_dict(my_home_city).unstack().rename('my_home_city'))

Output:

distance     near       far
vehicle      bike  car bike  car
city          NaN  NaN  NaN  NaN
my_home_city    1    0    0    1

The trick is to create the dataframe row with from_dict then unstack to get structure of your original dataframe with multiindex columns then rename to get index and append.

Or if you don't want to create the empty dataframe first you can use this method to create the dataframe with the new data.

pd.DataFrame.from_dict(my_home_city).unstack().rename('my_home_city').to_frame().T

Output:

              far     near
             bike car bike car
my_home_city    0   1    1   0

Explained:

pd.DataFrame.from_dict(my_home_city)

      far  near
bike    0     1
car     1     0

Now, let's unstack to create multiindex and get to that new dataframe into the structure of the original dataframe.

pd.DataFrame.from_dict(my_home_city).unstack()

far   bike    0
      car     1
near  bike    1
      car     0
dtype: int64

We use rename to give that series a name which becomes the index label of that dataframe row when appended to the original dataframe.

far   bike    0
      car     1
near  bike    1
      car     0
Name: my_home_city, dtype: int64

Now if you converted that series to a frame and transposed it would look very much like a new row, however, there is no need to do this because, Pandas does intrinsic data alignment, so appending this series to the dataframe will auto-align and add the new dataframe record.

dataframe.append(pd.DataFrame.from_dict(my_home_city).unstack().rename('my_home_city'))
distance     near       far
vehicle      bike  car bike  car
city          NaN  NaN  NaN  NaN
my_home_city    1    0    0    1


问:
Getting hit after invicibility when standing on trap
I am working on a simple 2D platformer game in which i have made an knockback effect. When the player gets hit by an obstacle, which currently is just a spike, he has a knockback and temporary invicibility, so when standing on spike during the invicibility he dosen't get hit. However, once the invicibility ends, i want to have player get hit by a spike like in the following GIF.

https://media.giphy.com/media/26FeVTRop5PhBrJQs/giphy.gif

The player gets hit because the invicibility is gone and it is standing on the spike. The problem I have is, if the invicibility ends and the player is still standing on the spike, it dosen't get hit and it cannot be hurt untill it gets off the spikes. Can you suggest how i solve this problem? Here is my code for hiting the player.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HitThePlayer : MonoBehaviour
{
    public int damage;

    GameObject player;
    PlayerController playerController;
    PlayerMovement playerMovement;

    void Start ()
    {
        player = GameObject.FindGameObjectWithTag ("Player");
        playerController = GameObject.FindGameObjectWithTag  ("GameController").GetComponent<PlayerController>();
        playerMovement = player.GetComponent<PlayerMovement> ();
    }

    void OnTriggerEnter2D (Collider2D other)
    {
        if (!playerController.isInvicible)
        {
            if (other.gameObject.CompareTag ("Player"))
            {
                playerController.AddPlayerHealth (-damage);
                playerMovement.isKnockedBacked = true;
                if (other.transform.position.x < transform.position.x)
                {
                    playerMovement.knockFromRight = true;
                }
                else
                {
                    playerMovement.knockFromRight = false;
                }
                StartCoroutine ("KnockBackEffectsDuration");
            }
        }
    }

    IEnumerator KnockBackEffectsDuration ()
    {
        player.GetComponent<Animator> ().SetTrigger ("GotHurt");
        StartCoroutine (playerController.Invicibility (3.0f));
        yield return new WaitForSeconds (0.2f);
        playerMovement.isKnockedBacked = false;
        playerMovement.enabled = false;
        yield return new WaitForSeconds (0.2f);
        playerMovement.enabled = true;
    }
}
</code>```

Also, here is the Invicibility IEnumerator that is in another script.

```<code>public IEnumerator Invicibility (float duration)
{
    isInvicible = true;
    yield return new WaitForSeconds (duration);
    isInvicible = false;
    player.GetComponent<Animator> ().SetTrigger ("GoIdle");
}
</code>```

HitThePlayer script references other scripts, so if you need me to bring up those scripts aswell, let me know.

答:
The problem is that after the spike trigger is entered and the player is damaged, when the invincibility wears off, your player has already entered the spike trigger and therefore this method is not being called again. One way to solve this would be instead of having the OnTriggerEnter directly damaging the player, you should instead use OnTriggerEnter and OnTriggerExit to set a bool for whether or not the player can be damaged. For example:

```<code>bool damageable;

void Update()
{
        if (!playerController.isInvicible && damageable)
        {
             // damage, knockback, etc the player here;
        }
}

void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.CompareTag ("Player"))
        damageable = true;
}

void OnTriggerExit2D(Collider2D other)
{
    if (other.gameObject.CompareTag ("Player"))
        damageable = false; // player is still damageable unless he leaves spikes
}
</code>```

Body:
I am working on a simple 2D platformer game in which i have made an knockback effect. When the player gets hit by an obstacle, which currently is just a spike, he has a knockback and temporary invicibility, so when standing on spike during the invicibility he dosen't get hit. However, once the invicibility ends, i want to have player get hit by a spike like in the following GIF.

https://media.giphy.com/media/26FeVTRop5PhBrJQs/giphy.gif

The player gets hit because the invicibility is gone and it is standing on the spike. The problem I have is, if the invicibility ends and the player is still standing on the spike, it dosen't get hit and it cannot be hurt untill it gets off the spikes. Can you suggest how i solve this problem? Here is my code for hiting the player.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HitThePlayer : MonoBehaviour
{
    public int damage;

    GameObject player;
    PlayerController playerController;
    PlayerMovement playerMovement;

    void Start ()
    {
        player = GameObject.FindGameObjectWithTag ("Player");
        playerController = GameObject.FindGameObjectWithTag  ("GameController").GetComponent<PlayerController>();
        playerMovement = player.GetComponent<PlayerMovement> ();
    }

    void OnTriggerEnter2D (Collider2D other)
    {
        if (!playerController.isInvicible)
        {
            if (other.gameObject.CompareTag ("Player"))
            {
                playerController.AddPlayerHealth (-damage);
                playerMovement.isKnockedBacked = true;
                if (other.transform.position.x < transform.position.x)
                {
                    playerMovement.knockFromRight = true;
                }
                else
                {
                    playerMovement.knockFromRight = false;
                }
                StartCoroutine ("KnockBackEffectsDuration");
            }
        }
    }

    IEnumerator KnockBackEffectsDuration ()
    {
        player.GetComponent<Animator> ().SetTrigger ("GotHurt");
        StartCoroutine (playerController.Invicibility (3.0f));
        yield return new WaitForSeconds (0.2f);
        playerMovement.isKnockedBacked = false;
        playerMovement.enabled = false;
        yield return new WaitForSeconds (0.2f);
        playerMovement.enabled = true;
    }
}

Also, here is the Invicibility IEnumerator that is in another script.

public IEnumerator Invicibility (float duration)
{
    isInvicible = true;
    yield return new WaitForSeconds (duration);
    isInvicible = false;
    player.GetComponent<Animator> ().SetTrigger ("GoIdle");
}

HitThePlayer script references other scripts, so if you need me to bring up those scripts aswell, let me know.

Body:
The problem is that after the spike trigger is entered and the player is damaged, when the invincibility wears off, your player has already entered the spike trigger and therefore this method is not being called again. One way to solve this would be instead of having the OnTriggerEnter directly damaging the player, you should instead use OnTriggerEnter and OnTriggerExit to set a bool for whether or not the player can be damaged. For example:

bool damageable;

void Update()
{
        if (!playerController.isInvicible && damageable)
        {
             // damage, knockback, etc the player here;
        }
}

void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.CompareTag ("Player"))
        damageable = true;
}

void OnTriggerExit2D(Collider2D other)
{
    if (other.gameObject.CompareTag ("Player"))
        damageable = false; // player is still damageable unless he leaves spikes
}


问:
Play audio in the background of Firefox extension popup
I've been working on an add-on for Firefox and when opening the pop-up of the add-on, it needs to play an audio file. It works perfectly while the popup is open, but the audio stops after the popup is minimized.</p>

答:
The popup window will be closed when the user leaves it.

Not a perfect, but you can refer to https://github.com/ripper2hl/whitenoisefy.


问:
Generate a series of random numbers that add up to N in c#
How do I generate 30 random numbers between 1-9, that all add up to 200 (or some arbitrary N), in C#?

I'm trying to generate a string of digits that can add together to be N.

答:
After all the discussions here, there's one other way to generate a list that doesn't introduce bias. Yes, it does differ from what the question is asking, but instead of randomly choosing digits, you can randomly increment digits until you reach the sum. Like the following (again untested):

```<code>public static List<int> RandomListByIncrementing(int digitMin, int digitMax,
                                                 int targetSum, int numDigits)
{
    if(targetSum < digitMin * numDigits || targetSum > digitMax * numDigits)
        throw new ArgumentException("Impossible!", "targetSum");

    List<int> ret = new List<int>(Enumerable.Repeat(digitMin, numDigits));
    List<int> indexList = new List<int>(Enumerable.Range(0, numDigits-1));

    Random random = new Random();
    int index;

    for(int currentSum=numDigits * digitMin; currentSum<targetSum; currentSum++)
    {
        //choose a random digit in the list to increase by 1
        index = random.Next(0,indexList.Length-1);

        if(++ret[indexList[index]] == digitMax)
        {
            //if you've increased it up to the max, remove its reference
            //because you can't increase it anymore
            indexList.RemoveAt(index);
        }
    }

    return ret;
}
</code>```

The idea here is you keep a list of references to your number list. Choose a reference at random, and increment the corresponding number. If you can't increment it anymore, remove the reference so you don't choose it next time.

Now there's no shuffling business to be done at the end of the day, although arguably this will still produce one of the available sets of answers to the question and it's a question of which one "feels better" or is faster to run.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Simucal

Body:
After all the discussions here, there's one other way to generate a list that doesn't introduce bias. Yes, it does differ from what the question is asking, but instead of randomly choosing digits, you can randomly increment digits until you reach the sum. Like the following (again untested):

public static List<int> RandomListByIncrementing(int digitMin, int digitMax,
                                                 int targetSum, int numDigits)
{
    if(targetSum < digitMin * numDigits || targetSum > digitMax * numDigits)
        throw new ArgumentException("Impossible!", "targetSum");

    List<int> ret = new List<int>(Enumerable.Repeat(digitMin, numDigits));
    List<int> indexList = new List<int>(Enumerable.Range(0, numDigits-1));

    Random random = new Random();
    int index;

    for(int currentSum=numDigits * digitMin; currentSum<targetSum; currentSum++)
    {
        //choose a random digit in the list to increase by 1
        index = random.Next(0,indexList.Length-1);

        if(++ret[indexList[index]] == digitMax)
        {
            //if you've increased it up to the max, remove its reference
            //because you can't increase it anymore
            indexList.RemoveAt(index);
        }
    }

    return ret;
}

The idea here is you keep a list of references to your number list. Choose a reference at random, and increment the corresponding number. If you can't increment it anymore, remove the reference so you don't choose it next time.

Now there's no shuffling business to be done at the end of the day, although arguably this will still produce one of the available sets of answers to the question and it's a question of which one "feels better" or is faster to run.

OwnerDisplayName: lc

LastEditorDisplayName: lc


问:
Special characters are properly displayed in Eclipse but not in .jar file
This is my very first question on Stackoverflow.

I have developed a tool in Eclipse that receives an Excel file (.xls) and adds the content of some cells to a JList. The problem is when exporting the project to a Runnable JAR file, as all the special characters are shown as "�" in the JList. However, they are properly displayed when running the application from the IDE. Please help ^^

OS: macOS High Sierra (v.10.13.1)
Eclipse: Mars.1 Release (4.5.1)

答:
FIXED!

By adding the following line:
System.setProperty("file.encoding", "ISO-8859-1");


问:
dynamic_cast doesn't work across module boundaries on clang
I am seeing a very strange failure that is very similar to the problem described in
dynamic_cast on llvm clang compiler failing: dynamic_cast returns nullptr when I am trying to downcast from base type to derived type, for an object of derived type. In my case though typeid actually shows the same dynamic type.

Below is the debug function that I use to verify run-time types. It takes a pointer of SrcType* and tries to dynamically cast it to pointer of DstType*. If conversion fails, i.e. the returned pointer is nullptr, it prints an error message. VERIFY() macro checks if condition is true:

```<code>template<typename DstType, typename SrcType>
void CheckDynamicType( SrcType *pSrcPtr )
{
    VERIFY(dynamic_cast<DstType*> (pSrcPtr) != nullptr,
           "Dynamic type cast failed. Src typeid: \'", typeid(*pSrcPtr).name(),
           "\' Dst typeid: \'", typeid(DstType).name(), '\'');
}
</code>```

And here is the output that I am getting:

```<code>Dynamic type cast failed. Src typeid: 'N8Diligent15RefCountersImplE' Dst typeid: 'N8Diligent15RefCountersImplE'
</code>```

I am using clang compiler from Android ndk r16 toolchain. I am compiling with rtti flag. The same code works fine on gcc and msvc.
Another bit of information: the code also works fine if I build it with gnustl runtime (I am not sure how gnu stl works with clang, but anyway).

UPDATE

After spending few more hours looking into the issue I found out that dynamic_cast fails when it is used on the object created in another module.
From this
Using clang++, -fvisibility=hidden, and typeinfo, and type-erasure and this posts it looks like dynamic_cast should work if the class is labeled with __attribute__((visibility("default"))) so that typeid structures from two modules will be merged. This, however does not help either and I am still seeing the issue.

答: If you’re using the stock system compiler there’s a near 0 chance dynamic_cast of the compiler isn’t working. This is tested and used extensively in everything from system software up. </p>

Body:
I am seeing a very strange failure that is very similar to the problem described in
dynamic_cast on llvm clang compiler failing: dynamic_cast returns nullptr when I am trying to downcast from base type to derived type, for an object of derived type. In my case though typeid actually shows the same dynamic type.

Below is the debug function that I use to verify run-time types. It takes a pointer of SrcType* and tries to dynamically cast it to pointer of DstType*. If conversion fails, i.e. the returned pointer is nullptr, it prints an error message. VERIFY() macro checks if condition is true:

template<typename DstType, typename SrcType>
void CheckDynamicType( SrcType *pSrcPtr )
{
    VERIFY(dynamic_cast<DstType*> (pSrcPtr) != nullptr,
           "Dynamic type cast failed. Src typeid: \'", typeid(*pSrcPtr).name(),
           "\' Dst typeid: \'", typeid(DstType).name(), '\'');
}

And here is the output that I am getting:

Dynamic type cast failed. Src typeid: 'N8Diligent15RefCountersImplE' Dst typeid: 'N8Diligent15RefCountersImplE'

I am using clang compiler from Android ndk r16 toolchain. I am compiling with rtti flag. The same code works fine on gcc and msvc.
Another bit of information: the code also works fine if I build it with gnustl runtime (I am not sure how gnu stl works with clang, but anyway).

UPDATE

After spending few more hours looking into the issue I found out that dynamic_cast fails when it is used on the object created in another module.
From this
Using clang++, -fvisibility=hidden, and typeinfo, and type-erasure and this posts it looks like dynamic_cast should work if the class is labeled with __attribute__((visibility("default"))) so that typeid structures from two modules will be merged. This, however does not help either and I am still seeing the issue.


问:
Identifying concave hull of points in higher dimension
I have a set of points(clusters) in higher dimension (30d to 100d). I need to identify concave hull of these points in an efficient manner.
Is there a way to do get the exact concave hull or atleast approximate concave hull of these set of points?
Further, if we have a set of points identified as a border point, is there a way to verify whether the points are actually border points?</p>

答:
In 100d, almost every point will be on the convex hull.

Just remember that a rectangle in 2d has 4 corners, but in 100d, it has 2^100 corners.

As an extremely rough approximation, take the minimum and maximum along each axis. If it is unique, the point is on the hull. For additional points, you can sample some random projections.

But again, the expected behaviour is that almost every point is on the hull, because it is the smallest or largest in some linear combination of features.


问:
Juniper SRX add custom BGP route
I have BGP configured between AzureStack (win2k16) and SRX210. On the Juniper I see all routes advertised but the Juniper is only advertising its physical interface networks..
I want the Juniper to also include all static routes that are configured towards the 2k16 machine..

Config NOW (on juniper)

```<code>policy-statement send-direct {
    term 1 {
        from protocol direct;
        then accept;
    }

group AzureStack {
    type internal;
    multihop {
        ttl 50;
    }
    export send-direct;
    neighbor 172.16.7.14 {
        local-address 172.16.7.1;
        peer-as 65050;
        local-as 65050;
    }
}
</code>```

Received on 2k16

```<code>DestinationNetwork NextHop

172.16.4.0/29    172.16.7.1  Juniper
172.16.5.0/24    172.16.7.1  Juniper
172.16.6.0/24    172.16.7.1  Juniper
</code>```

But my Juniper for example has a static route to 172.16.8.0/22 which I want to include in the bgp advertisement..

答:
You would want to modify your policy to advertise static-routes. Maybe create another term in your policy.</p>

```<code>set policy-options policy-statement send-direct term2 from protocol static
set policy-options policy-statement send-direct term2 then accept
</code>```

Title: Juniper SRX add custom BGP route

Body:
I have BGP configured between AzureStack (win2k16) and SRX210. On the Juniper I see all routes advertised but the Juniper is only advertising its physical interface networks..
I want the Juniper to also include all static routes that are configured towards the 2k16 machine..

Config NOW (on juniper)

policy-statement send-direct {
    term 1 {
        from protocol direct;
        then accept;
    }

group AzureStack {
    type internal;
    multihop {
        ttl 50;
    }
    export send-direct;
    neighbor 172.16.7.14 {
        local-address 172.16.7.1;
        peer-as 65050;
        local-as 65050;
    }
}

Received on 2k16

DestinationNetwork NextHop

172.16.4.0/29    172.16.7.1  Juniper
172.16.5.0/24    172.16.7.1  Juniper
172.16.6.0/24    172.16.7.1  Juniper

But my Juniper for example has a static route to 172.16.8.0/22 which I want to include in the bgp advertisement..

Body:
You would want to modify your policy to advertise static-routes. Maybe create another term in your policy.

set policy-options policy-statement send-direct term2 from protocol static
set policy-options policy-statement send-direct term2 then accept


问:
Static website and Angular 2 application on same domain
I have two applications.

static (html, css)

angular2

Domain name: xyz.com

OS: Ubuntu 16.04.2 LTS

web server: nginx/1.10.3

Purpose:

opening xyz.com should serve content from directory named static

and xyz.com/app should serve content from a directory named angular2

angular2 AOT build application file structure

SERVER CONFIGURATION

```<code>    server {
    listen 80;
    listen [::]:80;

    server_name xyz.com;

    location / {

        alias /var/www/html/static/;
        # First attempt to serve request ais file, then
        # as directory, then fall back to displaying a 404.i
        index index.html;
        try_files $uri $uri/ /index.php?$query_string /index.html =404;
    }

    location /app {
        alias /var/www/html/angular2/;
        index index.html;
        try_files $uri $uri/ index.html;
    }

    location /api {
        proxy_pass http://localhost:8086;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
    #
    #   # With php7.0-cgi alone:
    #   fastcgi_pass 127.0.0.1:9000;
    #   # With php7.0-fpm:
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny all;
    }
  }
</code>```

WEBPACK CONFIGURATION

```<code>output: {

  /**
   * The output directory as absolute path (required).
   *
   * See: http://webpack.github.io/docs/configuration.html#output-path
   */
  path: helpers.root('dist'),

  publicPath: '/app/',
  /**
   * Specifies the name of each output file on disk.
   * IMPORTANT: You must not specify an absolute path here!
   *
   * See: http://webpack.github.io/docs/configuration.html#output-filename
   */
  filename: '[name].[chunkhash].bundle.js',

  /**
   * The filename of the SourceMaps for the JavaScript files.
   * They are inside the output.path directory.
   *
   * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
   */
  sourceMapFilename: '[file].map',

  /**
   * The filename of non-entry chunks as relative path
   * inside the output.path directory.
   *
   * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
   */
  chunkFilename: '[name].[chunkhash].chunk.js'

},
</code>```

I have added publicPath to be /app/ so that each of the files included in index.html should be prefixed with app/ (Refer index.html snippet below)

angluar2 application index.html preview

Keeping <base href="/app"> will prefix each route with /app so that nginx location block can serve content from angular2 application.

Results:

When I open xyz.com, content from my static website gets served and
when I open xyz.com/app/SOME_URL_HERE, content from my angular2 application gets served. Till now it looked okay to me!

PROBLEM:

I am referring an image in my angular2 app from one of my html template and it has a relative path

```<code><img src="../../assets/image.jpeg" />
</code>```

my current setup is not able to serve it. I don't want to refer it having absolute path

```<code><img src="app/assests/image.png" />
</code>```

because first it will not work in my development setup and second it would make code readability harder.

Is my whole setup is wrong ?

OR

Is there any way to make nginx serve content of angular2 app relative to index.html with my current setup in place.

References:

I am using angular-starter as application base

https://github.com/AngularClass/angular-starter/

EDITED

Initially, I put my angular 2 application on subdomain app.xyz.com but I had to change my decision when I got to know that to secure a domain and subdomain, I need to buy a wildcard ssl and it too costly for me to buy.

答:
I find that hosting an angular app on a path will lead to all kind of problems.

Solution 1

If you can, avoid it.

I would suggest having your app have it's own subdomain.
app.xyz.com

That way when your app grows and your site grows, it will be easier to maintain them separatly.

Solution 2

If your static site only is a single page site you could serve /static/index.html on /

```<code>location = / {
  root /var/www/html/static/;
  try_files $uri $uri/ =404;
}

location / {
  root /var/www/html/angular2/;
  try_files $uri index.html
}
</code>```

Body:
I have two applications.

static (html, css)

angular2

Domain name: xyz.com

OS: Ubuntu 16.04.2 LTS

web server: nginx/1.10.3

Purpose:

opening xyz.com should serve content from directory named static

and xyz.com/app should serve content from a directory named angular2

angular2 AOT build application file structure

SERVER CONFIGURATION

    server {
    listen 80;
    listen [::]:80;

    server_name xyz.com;

    location / {

        alias /var/www/html/static/;
        # First attempt to serve request ais file, then
        # as directory, then fall back to displaying a 404.i
        index index.html;
        try_files $uri $uri/ /index.php?$query_string /index.html =404;
    }

    location /app {
        alias /var/www/html/angular2/;
        index index.html;
        try_files $uri $uri/ index.html;
    }

    location /api {
        proxy_pass http://localhost:8086;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
    #
    #   # With php7.0-cgi alone:
    #   fastcgi_pass 127.0.0.1:9000;
    #   # With php7.0-fpm:
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny all;
    }
  }

WEBPACK CONFIGURATION

output: {

  /**
   * The output directory as absolute path (required).
   *
   * See: http://webpack.github.io/docs/configuration.html#output-path
   */
  path: helpers.root('dist'),

  publicPath: '/app/',
  /**
   * Specifies the name of each output file on disk.
   * IMPORTANT: You must not specify an absolute path here!
   *
   * See: http://webpack.github.io/docs/configuration.html#output-filename
   */
  filename: '[name].[chunkhash].bundle.js',

  /**
   * The filename of the SourceMaps for the JavaScript files.
   * They are inside the output.path directory.
   *
   * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
   */
  sourceMapFilename: '[file].map',

  /**
   * The filename of non-entry chunks as relative path
   * inside the output.path directory.
   *
   * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
   */
  chunkFilename: '[name].[chunkhash].chunk.js'

},

I have added publicPath to be /app/ so that each of the files included in index.html should be prefixed with app/ (Refer index.html snippet below)

angluar2 application index.html preview

Keeping <base href="/app"> will prefix each route with /app so that nginx location block can serve content from angular2 application.

Results:

When I open xyz.com, content from my static website gets served and
when I open xyz.com/app/SOME_URL_HERE, content from my angular2 application gets served. Till now it looked okay to me!

PROBLEM:

I am referring an image in my angular2 app from one of my html template and it has a relative path

my current setup is not able to serve it. I don't want to refer it having absolute path

because first it will not work in my development setup and second it would make code readability harder.

Is my whole setup is wrong ?

OR

Is there any way to make nginx serve content of angular2 app relative to index.html with my current setup in place.

References:

I am using angular-starter as application base

https://github.com/AngularClass/angular-starter/

EDITED

Initially, I put my angular 2 application on subdomain app.xyz.com but I had to change my decision when I got to know that to secure a domain and subdomain, I need to buy a wildcard ssl and it too costly for me to buy.

Body:
I find that hosting an angular app on a path will lead to all kind of problems.

Solution 1

If you can, avoid it.

I would suggest having your app have it's own subdomain.
app.xyz.com

That way when your app grows and your site grows, it will be easier to maintain them separatly.

Solution 2

If your static site only is a single page site you could serve /static/index.html on /

location = / {
  root /var/www/html/static/;
  try_files $uri $uri/ =404;
}

location / {
  root /var/www/html/angular2/;
  try_files $uri index.html
}


问:
TeamCity integration with Android Lint reports
We have TeamCity as CI server for Android projects, of course, we are building it using gradle with lintRelease task.

Gradle's lint task generates .html report (for direct viewing by human in browser) and .xml for automated reports.

My question is how to integrate Android Lint's .xml reports with TeamCity and how to give access to .html report (problem is that it creates folder with .css and images which is not connecting if we are sharing this report as artifact)

答: The solution is to created a build step of type "Inspections (IntelliJ IDEA)" that points to a gradle file.</p>


问:
Inflate fragment from activity
Here is my activity class. I am trying to inflate fragment to this activity.

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.fg1, new ButtonsFragment());
        ft.commit();
    }
</code>```

activity_main.xml

```<code><LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/a_layout"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_margin="10dp"
        android:id="@+id/fg1"
        />
</LinearLayout>
</code>```

ButtonsFragment.java

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

    Button b1,b2,b3;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
    {
        super.onCreateView(inflater,container,savedInstanceState);

       View v = inflater.inflate(R.layout.fragment_buttons,container,false);

        b2 = (Button)v.findViewById(R.id.b2);
        b1 = (Button)v.findViewById(R.id.b1);
        b3 = (Button)v.findViewById(R.id.b3);
        return v;
    }
}
</code>```

fragment_buttons.xml

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.iiitb.patientdoctormanagementsystem.ButtonsFragment">

 <LinearLayout
        android:id="@+id/ll"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:textAllCaps="false"
            android:text="Past Appointments"
            android:id="@+id/b1"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content" />

        <Button
            android:textAllCaps="false"
            android:text="Todays Appointments"
            android:id="@+id/b2"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content" />

        <Button
            android:textAllCaps="false"
            android:text="Upcoming Appointments"
            android:id="@+id/b3"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content" />
    </LinearLayout>
</FrameLayout>
</code>```

But I am getting this exception:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.iiitb.patientdoctormanagementsystem/com.example.iiitb.patientdoctormanagementsystem.MainActivity}: android.view.InflateException: Binary XML file line #7: Binary XML file line #7: Error inflating class fragment
</code>```

PLEASE HELP!!

答:
Try To Use FrameLayout Instead of fragment in  activity_main.xml </p>

<p>// activity_main.xml</p>

```<code><LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/a_layout"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_margin="10dp"
        android:id="@+id/fg1"
        />
</LinearLayout>
</code>```

Title: Inflate fragment from activity

Body:
Here is my activity class. I am trying to inflate fragment to this activity.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.fg1, new ButtonsFragment());
        ft.commit();
    }

activity_main.xml

<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/a_layout"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_margin="10dp"
        android:id="@+id/fg1"
        />
</LinearLayout>

ButtonsFragment.java

public class ButtonsFragment extends Fragment {

    Button b1,b2,b3;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
    {
        super.onCreateView(inflater,container,savedInstanceState);

       View v = inflater.inflate(R.layout.fragment_buttons,container,false);

        b2 = (Button)v.findViewById(R.id.b2);
        b1 = (Button)v.findViewById(R.id.b1);
        b3 = (Button)v.findViewById(R.id.b3);
        return v;
    }
}

fragment_buttons.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.iiitb.patientdoctormanagementsystem.ButtonsFragment">

 <LinearLayout
        android:id="@+id/ll"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:textAllCaps="false"
            android:text="Past Appointments"
            android:id="@+id/b1"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content" />

        <Button
            android:textAllCaps="false"
            android:text="Todays Appointments"
            android:id="@+id/b2"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content" />

        <Button
            android:textAllCaps="false"
            android:text="Upcoming Appointments"
            android:id="@+id/b3"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content" />
    </LinearLayout>
</FrameLayout>

But I am getting this exception:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.iiitb.patientdoctormanagementsystem/com.example.iiitb.patientdoctormanagementsystem.MainActivity}: android.view.InflateException: Binary XML file line #7: Binary XML file line #7: Error inflating class fragment

PLEASE HELP!!

Body:
Try To Use FrameLayout Instead of fragment in  activity_main.xml

// activity_main.xml

<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/a_layout"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_margin="10dp"
        android:id="@+id/fg1"
        />
</LinearLayout>


问:
How to know when gallery widget stop scrolling?
I need to start a process only when the gallery stop scrolling. "onItemSelected" doesn't cut it as it will be called continuously as if scroll by.

So how to detect or callback when the gallery stop scrolling?

答: You can tune the behaviour of the galleryview a little bit with calling setCallbackDuringFling(false). This should limit the calls to onItemSelected to cases where the user stopped scrolling.


问:
Constructors for templates that do not have default constructors
I have a template class that currently has a constructor that takes no arguments. The issue is that in some cases the class that is being used in the template does not have an empty constructor which gives compile errors.

```<code>template <typename T>
class A
{
     public:
     T Thing;
     int number;
     A():number(5) {}
 };

  class B
  {
       public:
       int a;
       B(int _a):a(_a) {}
  }

  A<int> a1; // This is fine
  A<B> a2; // This is not fine since B has no default constructor
</code>```

I’ve thought of possibly using adding a second constructor which takes a ref to T, and then using enable_if to remove the parameterless constructor if T does not have a default constructor, but I’m not sure if that would work. Are there other options?

Note that I do not want to add a default constructor to class B because I don't want to leave an instance of B in an unknown state.

答:
Spoke to some people and did more research and found the solution.
Making the default constructor templated by a constexpr static member.
Here it is:</p>

```<code>template <typename T>
class A
{
public:
     T Thing;
     int number;
     static constexpr bool HasDefaultConstructors = std::is_default_constructible<T>;

     // This removes the default constructor if T does not have one
     template<bool HDC = HasDefaultConstructors, typename std::enable_if<HDC, int>::type = 0>
     A():number(5) {}

     A(const Thing &t):T(t) {}
 };
</code>```

Body:
I have a template class that currently has a constructor that takes no arguments. The issue is that in some cases the class that is being used in the template does not have an empty constructor which gives compile errors.

template <typename T>
class A
{
     public:
     T Thing;
     int number;
     A():number(5) {}
 };

  class B
  {
       public:
       int a;
       B(int _a):a(_a) {}
  }

  A<int> a1; // This is fine
  A a2; // This is not fine since B has no default constructor

I’ve thought of possibly using adding a second constructor which takes a ref to T, and then using enable_if to remove the parameterless constructor if T does not have a default constructor, but I’m not sure if that would work. Are there other options?

Note that I do not want to add a default constructor to class B because I don't want to leave an instance of B in an unknown state.

Body:
Spoke to some people and did more research and found the solution.
Making the default constructor templated by a constexpr static member.
Here it is:

template <typename T>
class A
{
public:
     T Thing;
     int number;
     static constexpr bool HasDefaultConstructors = std::is_default_constructible<T>;

     // This removes the default constructor if T does not have one
     template<bool HDC = HasDefaultConstructors, typename std::enable_if<HDC, int>::type = 0>
     A():number(5) {}

     A(const Thing &t):T(t) {}
 };


问:
ORA-08103: object no longer exists: This error is occuring for Oracle Procedure returning Refcursor from MyBatis
When calling a Stored Procedure in Oracle returning refcursor I am getting an error

```<code>2011-05-10 03:36:23 DirtiesContextTestExecutionListener [DEBUG] After test method: context [[TestContext@3a363a36 testClass = AccountActivityServiceTest, locations = array<String>['classpath:/com/bnymellon/pwb/pfdetails/service/test/test-application-context.xml'], testInstance = com.bnymellon.pwb.pfdetails.service.test.AccountActivityServiceTest@6d2c6d2c, testMethod = getData@AccountActivityServiceTest, testException = org.springframework.jdbc.UncategorizedSQLException:
### Error updating database.  Cause: java.sql.SQLException: ORA-08103: object no longer exists

### The error may involve com.bnymellon.pwb.pfdetails.persistence.AccountActivityMapper.getAccountActivityData-Inline
### The error occurred while setting parameters
### Cause: java.sql.SQLException: ORA-08103: object no longer exists

; uncategorized SQLException for SQL []; SQL state [72000]; error code [8103]; ORA-08103: object no longer exists
; nested exception is java.sql.SQLException: ORA-08103: object no longer exists
</code>```

I am using Spring MyBatis integraton project. the version of MyBatis is 3.0.4

I can see the Procedure is being executed. The logs are below.

```<code>2011-05-10 03:36:16 PreparedStatement [DEBUG] ==>  Executing: {call PWMWI.PAM_TRANSACTION_PKG.ACCOUNT_ACTIVITY( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}
2011-05-10 03:36:16 PreparedStatement [DEBUG] ==> Parameters: 1987(Integer), 5627(Integer), null, null, 2010-01-01(Date), 2010-12-31(Date), All Asset Classes(String), [All, PYR](String), (String), null
</code>```

My Mapper XMl is as follows:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bnymellon.pwb.pfdetails.persistence.AccountActivityMapper">
    <select id="getAccountActivityData"
        parameterType="com.bnymellon.pwb.pfdetails.common.AccountActivityDTO"
        statementType="CALLABLE">
        {call PWMWI.PAM_TRANSACTION_PKG.ACCOUNT_ACTIVITY(
        #{userInstance,mode=IN, jdbcType=INTEGER},
        #{accountGroupId,mode=IN,
        jdbcType=INTEGER},
        #{accountId,mode=IN, jdbcType=VARCHAR},
        #{accountId,mode=IN, jdbcType=VARCHAR},
        #{startDate,mode=IN,
        jdbcType=DATE},
        #{endDate,mode=IN, jdbcType=DATE},
        #{assetClass,mode=IN, jdbcType=VARCHAR},
        #{transactionType,mode=IN,
        jdbcType=VARCHAR},
        #{cusipId,mode=IN, jdbcType=VARCHAR},
        #{ticker,mode=IN, jdbcType=VARCHAR},
        #{domainList,mode=OUT,jdbcType=CURSOR,javaType=java.sql.ResultSet,resultMap=aaDataMap})}
    </select>

    <resultMap type="com.bnymellon.pwb.pfdetails.domain.AccountActivity"
        id="aaDataMap">
        <result column="TICKER" property="ticker" jdbcType="VARCHAR" />
        <result column="CUSIP" property="cusIp" jdbcType="VARCHAR" />
        <result column="SECURITY_NAME" property="securityName"
            jdbcType="VARCHAR"></result>
        <result column="ASSET_CLASS" property="assetClass" jdbcType="VARCHAR" />
        <result column="TRADE_DATE" property="tradeDate" jdbcType="DATE" />
        <result column="SETTLE_DATE" property="settleDate" jdbcType="DATE" />
        <result column="DESCRIPTION" property="description" jdbcType="VARCHAR" />
        <result column="RECORD_TYPE" property="description" jdbcType="VARCHAR" />
        <result column="ACCOUNT_NUMBER" property="accountNumber"
            jdbcType="VARCHAR" />
        <result column="QUANTITY" property="shares" jdbcType="VARCHAR" />
        <result column="LONG_DESC" property="transDesc" jdbcType="VARCHAR" />
        <result column="PORT_NUM" property="indicator" jdbcType="INTEGER" />
        <result column="AMOUNT" property="amount" jdbcType="VARCHAR" />
    </resultMap>
</mapper>
</code>```

I am using MyBatis version 3.0.4 and my Oracle driver jar is ojdbc14-10.2.0.3.0.jar

The IN and OUT parameters and their data types for Procedure are as below:

```<code>P_USER_INST           NUMBER        IN
P_GROUP_ID            NUMBER        IN
P_ENTITY_ID           CHAR          IN
P_ENTITY_NAME         VARCHAR2 (30) IN
P_START_DATE          DATE          IN
P_END_DATE            DATE          IN
P_ASSETCLASS          CHAR          IN
P_TRAN_TYPE           CHAR          IN
P_PRIMARY_ASSET_ID    VARCHAR2      IN
P_TICKER              VARCHAR2      IN
P_ACCOUNT_DETAIL_CUR  REF CURSOR    OUT
</code>```

My DTO in Java is below(omitting the setter/getter methods)

```<code>private Integer userInstance;

private Integer accountGroupId;

private String accountId;

private Date startDate;

private Date endDate;

private String transactionType;

private String ticker;

private String cusipId;

private String assetClass;

private List<AccountActivity> domainList;
</code>```

Any help is highly appreciated as I am clue less what is going on and really stuck on this.

答:
After Struggling one week finally I fixed the Issue:

Solution:  Most likely that a cursor is opened based on a global temporary table(GTT), which had been created with ON COMMIT DELETE ROWS option. And the cause of the ORA-08103: object no longer exists error is commit statement that followed right after the delete statement. DBA team didn't agree to change the GTT
as on commit preserve rows so finally I added code base in Java Service Layer[Implementing the Spring - Programmatic Transaction]

```<code>package com.test;

import java.util.List;
import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

public class StudentJDBCTemplate implements StudentDAO {
   private DataSource dataSource;
   private JdbcTemplate jdbcTemplateObject;
   private PlatformTransactionManager transactionManager;

   public void setDataSource(DataSource dataSource) {
      this.dataSource = dataSource;
      this.jdbcTemplateObject = new JdbcTemplate(dataSource);
   }
   public void setTransactionManager(PlatformTransactionManager transactionManager) {
      this.transactionManager = transactionManager;
   }
   public void create(String name, Integer age, Integer marks, Integer year){
      TransactionDefinition def = new DefaultTransactionDefinition();
      TransactionStatus status = transactionManager.getTransaction(def);

      try {
         String SQL1 = "insert into Student (name, age) values (?, ?)";
         jdbcTemplateObject.update( SQL1, name, age);

         // Get the latest student id to be used in Marks table
         String SQL2 = "select max(id) from Student";
         int sid = jdbcTemplateObject.queryForInt( SQL2 );

         String SQL3 = "insert into Marks(sid, marks, year) " + "values (?, ?, ?)";
         jdbcTemplateObject.update( SQL3, sid, marks, year);

         System.out.println("Created Name = " + name + ", Age = " + age);
         transactionManager.commit(status);
      }
      catch (DataAccessException e) {
         System.out.println("Error in creating record, rolling back");
         transactionManager.rollback(status);
         throw e;
      }
      return;
   }
   public List<StudentMarks> listStudents() {
      String SQL = "select * from Student, Marks where Student.id=Marks.sid";
      List <StudentMarks> studentMarks = jdbcTemplateObject.query(SQL,
         new StudentMarksMapper());

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

Body:
When calling a Stored Procedure in Oracle returning refcursor I am getting an error

2011-05-10 03:36:23 DirtiesContextTestExecutionListener [DEBUG] After test method: context [[TestContext@3a363a36 testClass = AccountActivityServiceTest, locations = array<String>['classpath:/com/bnymellon/pwb/pfdetails/service/test/test-application-context.xml'], testInstance = com.bnymellon.pwb.pfdetails.service.test.AccountActivityServiceTest@6d2c6d2c, testMethod = getData@AccountActivityServiceTest, testException = org.springframework.jdbc.UncategorizedSQLException:
### Error updating database.  Cause: java.sql.SQLException: ORA-08103: object no longer exists

### The error may involve com.bnymellon.pwb.pfdetails.persistence.AccountActivityMapper.getAccountActivityData-Inline
### The error occurred while setting parameters
### Cause: java.sql.SQLException: ORA-08103: object no longer exists

; uncategorized SQLException for SQL []; SQL state [72000]; error code [8103]; ORA-08103: object no longer exists
; nested exception is java.sql.SQLException: ORA-08103: object no longer exists

I am using Spring MyBatis integraton project. the version of MyBatis is 3.0.4

I can see the Procedure is being executed. The logs are below.

2011-05-10 03:36:16 PreparedStatement [DEBUG] ==>  Executing: {call PWMWI.PAM_TRANSACTION_PKG.ACCOUNT_ACTIVITY( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}
2011-05-10 03:36:16 PreparedStatement [DEBUG] ==> Parameters: 1987(Integer), 5627(Integer), null, null, 2010-01-01(Date), 2010-12-31(Date), All Asset Classes(String), [All, PYR](String), (String), null

My Mapper XMl is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bnymellon.pwb.pfdetails.persistence.AccountActivityMapper">
    <select id="getAccountActivityData"
        parameterType="com.bnymellon.pwb.pfdetails.common.AccountActivityDTO"
        statementType="CALLABLE">
        {call PWMWI.PAM_TRANSACTION_PKG.ACCOUNT_ACTIVITY(
        #{userInstance,mode=IN, jdbcType=INTEGER},
        #{accountGroupId,mode=IN,
        jdbcType=INTEGER},
        #{accountId,mode=IN, jdbcType=VARCHAR},
        #{accountId,mode=IN, jdbcType=VARCHAR},
        #{startDate,mode=IN,
        jdbcType=DATE},
        #{endDate,mode=IN, jdbcType=DATE},
        #{assetClass,mode=IN, jdbcType=VARCHAR},
        #{transactionType,mode=IN,
        jdbcType=VARCHAR},
        #{cusipId,mode=IN, jdbcType=VARCHAR},
        #{ticker,mode=IN, jdbcType=VARCHAR},
        #{domainList,mode=OUT,jdbcType=CURSOR,javaType=java.sql.ResultSet,resultMap=aaDataMap})}
    </select>

    <resultMap type="com.bnymellon.pwb.pfdetails.domain.AccountActivity"
        id="aaDataMap">
        <result column="TICKER" property="ticker" jdbcType="VARCHAR" />
        <result column="CUSIP" property="cusIp" jdbcType="VARCHAR" />
        <result column="SECURITY_NAME" property="securityName"
            jdbcType="VARCHAR"></result>
        <result column="ASSET_CLASS" property="assetClass" jdbcType="VARCHAR" />
        <result column="TRADE_DATE" property="tradeDate" jdbcType="DATE" />
        <result column="SETTLE_DATE" property="settleDate" jdbcType="DATE" />
        <result column="DESCRIPTION" property="description" jdbcType="VARCHAR" />
        <result column="RECORD_TYPE" property="description" jdbcType="VARCHAR" />
        <result column="ACCOUNT_NUMBER" property="accountNumber"
            jdbcType="VARCHAR" />
        <result column="QUANTITY" property="shares" jdbcType="VARCHAR" />
        <result column="LONG_DESC" property="transDesc" jdbcType="VARCHAR" />
        <result column="PORT_NUM" property="indicator" jdbcType="INTEGER" />
        <result column="AMOUNT" property="amount" jdbcType="VARCHAR" />
    </resultMap>
</mapper>

I am using MyBatis version 3.0.4 and my Oracle driver jar is ojdbc14-10.2.0.3.0.jar

The IN and OUT parameters and their data types for Procedure are as below:

P_USER_INST           NUMBER        IN
P_GROUP_ID            NUMBER        IN
P_ENTITY_ID           CHAR          IN
P_ENTITY_NAME         VARCHAR2 (30) IN
P_START_DATE          DATE          IN
P_END_DATE            DATE          IN
P_ASSETCLASS          CHAR          IN
P_TRAN_TYPE           CHAR          IN
P_PRIMARY_ASSET_ID    VARCHAR2      IN
P_TICKER              VARCHAR2      IN
P_ACCOUNT_DETAIL_CUR  REF CURSOR    OUT

My DTO in Java is below(omitting the setter/getter methods)

private Integer userInstance;

private Integer accountGroupId;

private String accountId;

private Date startDate;

private Date endDate;

private String transactionType;

private String ticker;

private String cusipId;

private String assetClass;

private List<AccountActivity> domainList;

Any help is highly appreciated as I am clue less what is going on and really stuck on this.

Body:
After Struggling one week finally I fixed the Issue:

Solution:  Most likely that a cursor is opened based on a global temporary table(GTT), which had been created with ON COMMIT DELETE ROWS option. And the cause of the ORA-08103: object no longer exists error is commit statement that followed right after the delete statement. DBA team didn't agree to change the GTT
as on commit preserve rows so finally I added code base in Java Service Layer[Implementing the Spring - Programmatic Transaction]

package com.test;

import java.util.List;
import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

public class StudentJDBCTemplate implements StudentDAO {
   private DataSource dataSource;
   private JdbcTemplate jdbcTemplateObject;
   private PlatformTransactionManager transactionManager;

   public void setDataSource(DataSource dataSource) {
      this.dataSource = dataSource;
      this.jdbcTemplateObject = new JdbcTemplate(dataSource);
   }
   public void setTransactionManager(PlatformTransactionManager transactionManager) {
      this.transactionManager = transactionManager;
   }
   public void create(String name, Integer age, Integer marks, Integer year){
      TransactionDefinition def = new DefaultTransactionDefinition();
      TransactionStatus status = transactionManager.getTransaction(def);

      try {
         String SQL1 = "insert into Student (name, age) values (?, ?)";
         jdbcTemplateObject.update( SQL1, name, age);

         // Get the latest student id to be used in Marks table
         String SQL2 = "select max(id) from Student";
         int sid = jdbcTemplateObject.queryForInt( SQL2 );

         String SQL3 = "insert into Marks(sid, marks, year) " + "values (?, ?, ?)";
         jdbcTemplateObject.update( SQL3, sid, marks, year);

         System.out.println("Created Name = " + name + ", Age = " + age);
         transactionManager.commit(status);
      }
      catch (DataAccessException e) {
         System.out.println("Error in creating record, rolling back");
         transactionManager.rollback(status);
         throw e;
      }
      return;
   }
   public List<StudentMarks> listStudents() {
      String SQL = "select * from Student, Marks where Student.id=Marks.sid";
      List <StudentMarks> studentMarks = jdbcTemplateObject.query(SQL,
         new StudentMarksMapper());

      return studentMarks;
   }
}


问:
Deploy Microsoft Node.js bot using Visual Studio
I have created Azure Bot service for nodeJS LUIS bot.
Downloaded the zip file to for local development.

Now I want to publish the changes back to Azure Bot from Visual studio 2017.

Which different environment variables I need to set to publish from desktop without using Visual studio services.

答:
You can setup continuous deployment by following the guidelines in this article.

Download your source code via .zip file from the Azure Bot Service interface.

Upload your code to one of the following source control providers:

Visual Studio Team Services

OneDrive

Local Azure Git Repository

GitHub (recommended)

Bitbucket

Dropbox

External Repository

In Azure Bot Service, select "Settings", then go to the section "Continuous deployment" and click the "Configure" button under the section "Step 3: Configure continuous deployment"

In the "Deployments" blade, click the "Setup" link by the gears icon.

In the "Deployment option" blade to the right, click "Choose Source"

Select the source control service your selected in step 2 above, for example GitHub

Configure your repository-specific settings in the "Deployment option" blade, including project and branch, then click "OK"

You should see a popup notification that says "Setting up deployment source"

In the "Deployments" blade of your Bot Service, you should see a log of your current deployment.

Done!

Now when you push changes to your code repository, it will trigger an automatic redeployment of your bot's code, which you can monitor using the "Deployments" blade.

For more information, check out the complete article on Azure Continuous Deployment here:
https://learn.microsoft.com/en-us/azure/app-service/app-service-continuous-deployment

ContentLicense: CC BY-SA 4.0


问:
How to monitor changes to a particular website CSS?
I wish to monitor the CSS of a few websites (these websites aren't my own) for changes and receive a notification of some sort when they do. If you could please share any experience you've had with this to point me in the right direction for how to code it I'd appreciate it greatly.

I'd like this script/app to notify a Slack group on change, which I assume will require a webhook.

Not asking for code, just any advice about particular APIs and other tools that may be of benefit.

答:
I would suggest a modification of tschaefermedia's answer.

Crawl website for .css files, save.

Take an md5 of each file.

Then compare md5 of the new file will the old file.

If the md5 is different then the file changed.

Below is a function to take md5 of large files.

```<code>def md5(file_name):

    # make a md5 hash object
    hash_md5 = hashlib.md5()

    # open file as binary and read only
    with open(file_name, 'rb') as f:
        i = 0

        # read 4096 bytes at a time and take the md5 hash of it and add it to the hash total
        # b converts string literal to bytes
        for chunk in iter(lambda: f.read(4096), b''):
            i += 1

            # get sum of md5 hashes
            # m.update(a); m.update(b) is equivalent to m.update(a+b)
            hash_md5.update(chunk)

        # check for correct number of iterations
        file_size = os.path.getsize(file_name)
        expected_i = int(math.ceil(float(file_size) / float(4096)))
        correct_i = i == expected_i

        # check if md5 correct
        md5_chunk_file = hash_md5.hexdigest()

    return md5_chunk_file
</code>```

Body:
I would suggest a modification of tschaefermedia's answer.

Crawl website for .css files, save.

Take an md5 of each file.

Then compare md5 of the new file will the old file.

If the md5 is different then the file changed.

Below is a function to take md5 of large files.

def md5(file_name):

    # make a md5 hash object
    hash_md5 = hashlib.md5()

    # open file as binary and read only
    with open(file_name, 'rb') as f:
        i = 0

        # read 4096 bytes at a time and take the md5 hash of it and add it to the hash total
        # b converts string literal to bytes
        for chunk in iter(lambda: f.read(4096), b''):
            i += 1

            # get sum of md5 hashes
            # m.update(a); m.update(b) is equivalent to m.update(a+b)
            hash_md5.update(chunk)

        # check for correct number of iterations
        file_size = os.path.getsize(file_name)
        expected_i = int(math.ceil(float(file_size) / float(4096)))
        correct_i = i == expected_i

        # check if md5 correct
        md5_chunk_file = hash_md5.hexdigest()

    return md5_chunk_file


问:
UI best practice question: Cancel button or Cancel link
I have a discussion with a colleague about what the "web standard" is for canceling in an form. In our discussion we have a "change password" page as example. We have a designed "send" button and "cancel" button. Both the same design.

He claims that in web standard a cancel button is no longer a button but a link transferring the user to another page. In my opinion, for those pages including a cancel button it actually is a cancel button which either resets the form and/or send the user to the prevision page.

Who is correct? Link or button... or both? And why? Any links to where this kind of standard is decided?

Br,

Paul Peelen

EDIT
I guess the answer with most votes will be the "correct answer"?

答:
Why make it easy for users to undo all they've typed in by mistake?
Why not prevent accidental form canceling?

Why isn't the cockpit light switch next to the eject button?

By making the cancel button different from the submit one, you easily convey the idea that they do different things. So long as it does not look like the submit button, you're safe.

Make it a link.


问:
error of making a test and train data split in sklearn
I am trying to make a test and train data split by "train_test_split".
Why I got the error "At least one array required as input". </p>

<p>The input of "train_test_split" can be array and dataFrame, right ? </p>

```<code>import pandas as pd
import numpy as np
from rpy2.robjects.packages import importr
import rpy2.robjects as ro
import pandas.rpy.common as rpy_common
from sklearn.model_selection import  train_test_split

def la():
 ro.r('library(MASS)')
 pydf = rpy_common.load_data(name = 'Boston', package=None, convert=True)
 pddf = pd.DataFrame(pydf)
 targetIndex = pddf.columns.get_loc("medv")

 # make train and test data
rowNum = pddf.shape[0]
colNum = pddf.shape[1]
print(type(pddf.as_matrix()))
print(pddf.as_matrix().shape)
m = np.asarray(pddf.as_matrix()).reshape(rowNum,colNum)
print(type(m))
x_train, x_test, y_train, y_test = train_test_split(x = m[:, 0:rowNum-2], \
                                                    y = m[:, -1],\
                                                    test_size = 0.5)
# error:     raise ValueError("At least one array required as input")
ValueError: At least one array required as input
</code>```

答:
From the sklearn docs the arrays are handled with positional item unpacking ("*args").

You are using keyword arguments, "x=" and "y=", which it tries to handle by looking if "x" and "y" are the names of special keyword options.

Try:

```<code>train_test_split(m[:, 0:rowNum-2], m[:, -1], test_size=0.5)
</code>```

(removing the keyword argument names from the arrays).

Body:
I am trying to make a test and train data split by "train_test_split".
Why I got the error "At least one array required as input".

The input of "train_test_split" can be array and dataFrame, right ?

import pandas as pd
import numpy as np
from rpy2.robjects.packages import importr
import rpy2.robjects as ro
import pandas.rpy.common as rpy_common
from sklearn.model_selection import  train_test_split

def la():
 ro.r('library(MASS)')
 pydf = rpy_common.load_data(name = 'Boston', package=None, convert=True)
 pddf = pd.DataFrame(pydf)
 targetIndex = pddf.columns.get_loc("medv")

 # make train and test data
rowNum = pddf.shape[0]
colNum = pddf.shape[1]
print(type(pddf.as_matrix()))
print(pddf.as_matrix().shape)
m = np.asarray(pddf.as_matrix()).reshape(rowNum,colNum)
print(type(m))
x_train, x_test, y_train, y_test = train_test_split(x = m[:, 0:rowNum-2], \
                                                    y = m[:, -1],\
                                                    test_size = 0.5)
# error:     raise ValueError("At least one array required as input")
ValueError: At least one array required as input

Body:
From the sklearn docs the arrays are handled with positional item unpacking ("*args").

You are using keyword arguments, "x=" and "y=", which it tries to handle by looking if "x" and "y" are the names of special keyword options.

Try:

train_test_split(m[:, 0:rowNum-2], m[:, -1], test_size=0.5)

(removing the keyword argument names from the arrays).


问:
position sticky for complex table header
I'm trying to get a sticky table header to work with a complex header. It works fine for standard tables. The table will stick at the top row and not the second causing the header to look "out of whack" or sort of staggered.  I tried putting the position sticky on the thead and that didn't seem to do anything.

Here is my table:

table {
  border: 1px solid black;
  font-size: 14px;
  margin: 10px 0;
  position: relative;
}

thead tr th {
  background-color: gray;
  position: sticky;
  top: -2px;
}

thead {
  border: 1px solid black;
  line-height: 1.25;
  overflow: hidden;
}

td {
  border: 1px solid black;
  line-height: 1.25;
  overflow: hidden;
  padding: 4px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class='sticky-table'>
  <thead>
    <tr>
      <th rowspan="2">First column</th>
      <th colspan="3">Top of second column</th>
    </tr>
    <tr>
      <th>One</th>
      <th>Two</th>
      <th>Three</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
  </tbody>
</table></code>```

答:
I do not like this solution, because the space is "hard" coded, but it works as desired, I think, isn't it?

table {
  border: 1px solid black;
  font-size: 14px;
  margin: 10px 0;
  position: relative;
}

thead tr th {
  background-color: gray;
  position: sticky;
  top: -2px;
}

.header {
  background-color: gray;
  position: sticky;
  top: 20px;
}

thead {
  border: 1px solid black;
  line-height: 1.25;
  overflow: hidden;
}

td {
  border: 1px solid black;
  line-height: 1.25;
  overflow: hidden;
  padding: 4px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class='sticky-table'>
  <thead>
    <tr>
      <th rowspan="2">First column</th>
      <th colspan="3">Top of second column</th>
    </tr>
    <tr>
      <th class="header">One</th>
      <th class="header">Two</th>
      <th class="header">Three</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
  </tbody>
</table></code>```

Body:
I'm trying to get a sticky table header to work with a complex header. It works fine for standard tables. The table will stick at the top row and not the second causing the header to look "out of whack" or sort of staggered.  I tried putting the position sticky on the thead and that didn't seem to do anything.

Here is my table:

table {
  border: 1px solid black;
  font-size: 14px;
  margin: 10px 0;
  position: relative;
}

thead tr th {
  background-color: gray;
  position: sticky;
  top: -2px;
}

thead {
  border: 1px solid black;
  line-height: 1.25;
  overflow: hidden;
}

td {
  border: 1px solid black;
  line-height: 1.25;
  overflow: hidden;
  padding: 4px;
}

      First column
      Top of second column

      One
      Two
      Three

      First cell
      Second cell
      Third cell
      Fourth cell

      First cell
      Second cell
      Third cell
      Fourth cell

      First cell
      Second cell
      Third cell
      Fourth cell

      First cell
      Second cell
      Third cell
      Fourth cell

      First cell
      Second cell
      Third cell
      Fourth cell

      First cell
      Second cell
      Third cell
      Fourth cell

      First cell
      Second cell
      Third cell
      Fourth cell

      First cell
      Second cell
      Third cell
      Fourth cell

      First cell
      Second cell
      Third cell
      Fourth cell

      First cell
      Second cell
      Third cell
      Fourth cell

      First cell
      Second cell
      Third cell
      Fourth cell

      First cell
      Second cell
      Third cell
      Fourth cell

      First cell
      Second cell
      Third cell
      Fourth cell

Body:
I do not like this solution, because the space is "hard" coded, but it works as desired, I think, isn't it?

table {
  border: 1px solid black;
  font-size: 14px;
  margin: 10px 0;
  position: relative;
}

thead tr th {
  background-color: gray;
  position: sticky;
  top: -2px;
}

.header {
  background-color: gray;
  position: sticky;
  top: 20px;
}

thead {
  border: 1px solid black;
  line-height: 1.25;
  overflow: hidden;
}

td {
  border: 1px solid black;
  line-height: 1.25;
  overflow: hidden;
  padding: 4px;
}

<table class='sticky-table'>
  <thead>
    <tr>
      <th rowspan="2">First column</th>
      <th colspan="3">Top of second column</th>
    </tr>
    <tr>
      <th class="header">One</th>
      <th class="header">Two</th>
      <th class="header">Three</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
  </tbody>
</table>


问:
How would I create a palindrome checker without if statements
I'm trying to create a programme like this previous one I've made;

It simply gives a boolean true/false on if a string backwards is still spelt the same way.

I've created this using if statements, but would like too know if it is possible too create using only methods and loops, and if so how? I have looked for duplicates, and there are similar posts that achieve what I have below, but everything I find uses if else statements

Any help appreciated as always; thanks.

```<code>import java.util.*;
public class testingthingsv24 {

private static Scanner in;

public static void main(String args[])
{
    in = new Scanner(System.in);
    System.out.println("Please Enter Your String: ");
    String n=in.nextLine();
    System.out.println("Your String Was: "+n);
    StringBuffer str=new StringBuffer(n);
    StringBuffer str2=new StringBuffer(str.reverse());
    String s2=new String(str2);
    System.out.println("Reversed Is: "+str2);
    if(n.equals(s2))
        System.out.println("ITS A PALINDROME");
    else
        System.out.println("ITS NOT A PALINDROME");
}
}
</code>```

Output:

```<code>Please Enter Your String:
dad
Your String Was: dad
Reversed Is: dad
ITS A PALINDROME
</code>```

答:
To test a result, generally a conditional statement (if, ternary or switch) appears useful.

You have to avoid using conditional statements as these conditions are annoying by making your code not readable, brittle, error prone, etc..

To do that, you have to favor abstraction over sequential logic.

In your simple case, you could for example introduce a structure (key-value) that associate each boolean value to the String message.

```<code>Map<Boolean, String> messageByBoolean = new HashMap<>();
messageByBoolean.put(true, "ITS A PALINDROME");
messageByBoolean.put(false, "ITS NOT A PALINDROME");
...
System.out.println(messageByBoolean.get(n.equals(s2));
</code>```

But does it make really sense ?
 It looks like an overhead as you have just two possibilities.

With 5 or 10 of them, it would make much sense.

Body:
I'm trying to create a programme like this previous one I've made;

It simply gives a boolean true/false on if a string backwards is still spelt the same way.

I've created this using if statements, but would like too know if it is possible too create using only methods and loops, and if so how? I have looked for duplicates, and there are similar posts that achieve what I have below, but everything I find uses if else statements

Any help appreciated as always; thanks.

import java.util.*;
public class testingthingsv24 {

private static Scanner in;

public static void main(String args[])
{
    in = new Scanner(System.in);
    System.out.println("Please Enter Your String: ");
    String n=in.nextLine();
    System.out.println("Your String Was: "+n);
    StringBuffer str=new StringBuffer(n);
    StringBuffer str2=new StringBuffer(str.reverse());
    String s2=new String(str2);
    System.out.println("Reversed Is: "+str2);
    if(n.equals(s2))
        System.out.println("ITS A PALINDROME");
    else
        System.out.println("ITS NOT A PALINDROME");
}
}

Output:

Please Enter Your String:
dad
Your String Was: dad
Reversed Is: dad
ITS A PALINDROME

Body:
To test a result, generally a conditional statement (if, ternary or switch) appears useful.

You have to avoid using conditional statements as these conditions are annoying by making your code not readable, brittle, error prone, etc..

To do that, you have to favor abstraction over sequential logic.

In your simple case, you could for example introduce a structure (key-value) that associate each boolean value to the String message.

Map<Boolean, String> messageByBoolean = new HashMap<>();
messageByBoolean.put(true, "ITS A PALINDROME");
messageByBoolean.put(false, "ITS NOT A PALINDROME");
...
System.out.println(messageByBoolean.get(n.equals(s2));

But does it make really sense ?
 It looks like an overhead as you have just two possibilities.

With 5 or 10 of them, it would make much sense.


问:
jQuery - How can I create an element based on user choice in a loop?
I'm trying to create 5 different audio players from the following code to call them out individually wherever I need it in the HTML document: https://codepen.io/katzkode/pen/ZbxYYG

The issue is that these 2 loops use a single div element to call the function (5 audio players at once):

For audio:

```<code>/* createAudioElements
 * create audio elements for each file in files */
function createAudioElements() {
    for (f in files) {
        var audioString = "<audio id=\"audio-" + f + "\" class=\"audio\" preload=\"true\"><source src=\"http://www.alexkatz.me/codepen/music/" + files[f] + "\"></audio>";
        $("#audio-players").append(audioString);
    }
}
</code>```

For div element:

```<code>/* createAudioPlayers
 * create audio players for each file in files */
function createAudioPlayers() {
    for (f in files) {
        var playerString = "<div id=\"audioplayer-" + f + "\" class=\"audioplayer\"><button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button><div id=\"timeline-" + f + "\" class=\"timeline\"><div id=\"playhead-" + f + "\" class=\"playhead\"></div></div></div>";
        $("#audio-players").append(playerString);
    }
}
</code>```

But what I'm trying to do is invoke a specific player with a specific song of my choice instead of 5 of them at once which is how it currently works.

Like this:

```<code><div id="audio-players1"></div>
<div id="audio-players2"></div>
<div id="audio-players3"></div>
<div id="audio-players4"></div>
<div id="audio-players5"></div>
</code>```

I've tried to do this for both loops:

Replacing this:

```<code>$("#audio-players")
</code>```

With this:

```<code>$("#audio-players" + f)
</code>```

But then the buttons won't work.

Here's the code to pull the files from:

```<code>var files = ["interlude.mp3", // 0
            "chooseyourweapon.mp3", // 1
            "interlude.mp3", // 2
            "scriptures.mp3",
       "scriptures.mp3"// 3
            ];
</code>```

And I'm unsure how to proceed, I'm still learning. Thank you.

答:
Try this first:
https://codepen.io/wolfram77/pen/POOqmv

If you want to show only one player of a song:

```<code>function showPlayer(f) {
  for(var i=0; i<files.length; i++) {
    if(i===f) $("#audioplayer-"+i).show();
    else $("#audioplayer-"+i).hide();
  }
};
</code>```

Now, lets create a select where we can choose which some:

```<code><select id="select-songs"></select>
</code>```

And, create the options for select and handle "change" event:

```<code>/* createSelectOptions
 * create select options for each file in files */
function createSelectOptions() {
    for (f in files) {
        var optionString = `<option value="${f}">${files[f]}</option>`;
        $("#select-songs").append(optionString);
    }
  $("#select-songs").on('change', function(el) {
    var f = parseInt($("#select-songs option:selected").val());
    console.log(f, files[f]);
    showPlayer(f);
  });
  showPlayer(0);
}
</code>```

And finally, dont forget to execute it:

```<code>/* theDOMHasLoaded()
 * Execute when DOM is loaded */
function theDOMHasLoaded(e) {
    // Generate HTML for audio elements and audio players
    createAudioElements();
    createAudioPlayers();

    // Populate Audio List
    populateAudioList();
    populateComponentDictionary();
    createSelectOptions();
}
</code>```

Body:
I'm trying to create 5 different audio players from the following code to call them out individually wherever I need it in the HTML document: https://codepen.io/katzkode/pen/ZbxYYG

The issue is that these 2 loops use a single div element to call the function (5 audio players at once):

For audio:

/* createAudioElements
 * create audio elements for each file in files */
function createAudioElements() {
    for (f in files) {
        var audioString = "<audio id=\"audio-" + f + "\" class=\"audio\" preload=\"true\"><source src=\"http://www.alexkatz.me/codepen/music/" + files[f] + "\"></audio>";
        $("#audio-players").append(audioString);
    }
}

For div element:

/* createAudioPlayers
 * create audio players for each file in files */
function createAudioPlayers() {
    for (f in files) {
        var playerString = "
<button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button>

";
        $("#audio-players").append(playerString);
    }
}

But what I'm trying to do is invoke a specific player with a specific song of my choice instead of 5 of them at once which is how it currently works.

Like this:

I've tried to do this for both loops:

Replacing this:

$("#audio-players")

With this:

$("#audio-players" + f)

But then the buttons won't work.

Here's the code to pull the files from:

var files = ["interlude.mp3", // 0
            "chooseyourweapon.mp3", // 1
            "interlude.mp3", // 2
            "scriptures.mp3",
       "scriptures.mp3"// 3
            ];

And I'm unsure how to proceed, I'm still learning. Thank you.

Body:
Try this first:
https://codepen.io/wolfram77/pen/POOqmv

If you want to show only one player of a song:

function showPlayer(f) {
  for(var i=0; i<files.length; i++) {
    if(i===f) $("#audioplayer-"+i).show();
    else $("#audioplayer-"+i).hide();
  }
};

Now, lets create a select where we can choose which some:

<select id="select-songs"></select>

And, create the options for select and handle "change" event:

/* createSelectOptions
 * create select options for each file in files */
function createSelectOptions() {
    for (f in files) {
        var optionString = `<option value="${f}">${files[f]}</option>`;
        $("#select-songs").append(optionString);
    }
  $("#select-songs").on('change', function(el) {
    var f = parseInt($("#select-songs option:selected").val());
    console.log(f, files[f]);
    showPlayer(f);
  });
  showPlayer(0);
}

And finally, dont forget to execute it:

/* theDOMHasLoaded()
 * Execute when DOM is loaded */
function theDOMHasLoaded(e) {
    // Generate HTML for audio elements and audio players
    createAudioElements();
    createAudioPlayers();

    // Populate Audio List
    populateAudioList();
    populateComponentDictionary();
    createSelectOptions();
}


问:
MySQL Access denied from command connection
So I'm connecting to an AWS EC2 Ubuntu 16.04 instance. As part of my production script I do:

mysql -u root -pmy-secret -e "source resetDb.sql;" >> lastRun.log

This resetDb.sql has the queries to create and populate the database info. Then keep on going with the app.

The thing is that mysql is rejecting my access this way by throwing

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

But if I connect with mysql -u root -p and manually enter the password, it lets me into the console, so this let's me see the password is right.

I get this output on the server

$ mysql --version
mysql  Ver 14.14 Distrib 5.7.20, for Linux (x86_64) using  EditLine wrapper
$ uname -a
Linux ip-xx.xx.xx.xx 4.4.0-1038-aws #47-Ubuntu SMP Thu Sep 28 20:05:35 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

I've seen in another questions about flushing privileges and resetting the root password, but my password is correct so it did no good to me.

Anyone has a clue? The idea is to run the script to automatically setup the whole server. Thanks in advance.

答:
Another possibility is that your root password has a specific host restriction.

So if you run

```<code>select user,host,password from mysql.user;
</code>```

You may see that root@localhost, root@127.0.0.1, and root@% all exist but have different passwords.

Body:
Another possibility is that your root password has a specific host restriction.

So if you run

select user,host,password from mysql.user;

You may see that root@localhost, root@127.0.0.1, and root@% all exist but have different passwords.


问:
Tree Search using a SQL Query to find Common Cells
What I will like to do is to retrieve all the persons that contain two common columns (movie and year):

```<code>login_id | movie               | year
---------|---------------------|-----------
john     | the matrix          | 1999
john     | star wars           | 1977
bob      | titanic             | 1997
johnny   | the matrix          | 1999
tony     | lord of the rings   | 2001
tony     | lord of the rings   | 2002
tony     | lord of the rings   | 2003
james    | star wars           | 1977
robert   | star trek           | 1966
james    | titanic             | 1997
bob      | star trek           | 1966
...
</code>```

So if am interested in finding for login_id: bob what movies he watched plus who else watched the same movies expected output:

```<code>login_id | movie               | year
---------|---------------------|-----------
james    | titanic             | 1997
robert   | star trek           | 1966
...
</code>```

I want to do it efficiently as possible and if I need to restructure the table I will do it. First guess:

SELECT login_id, movie, year, count(*)
 FROM watchers
 GROUP BY login_id, movie, year
 HAVING count(*) > 1 **and login_id = 'bob'**

The 'and' is where I am confuse, because it is grouping by count instead of pulling out all the common data.

答:
I suggest using a self join:</p>

```<code>Select t1.*
From  table t0
Join table t1 on t0.movie = t1.movie
And t0.year = t1.year
Where t0.login_id ='bob'
</code>```

Body:
What I will like to do is to retrieve all the persons that contain two common columns (movie and year):

login_id | movie               | year
---------|---------------------|-----------
john     | the matrix          | 1999
john     | star wars           | 1977
bob      | titanic             | 1997
johnny   | the matrix          | 1999
tony     | lord of the rings   | 2001
tony     | lord of the rings   | 2002
tony     | lord of the rings   | 2003
james    | star wars           | 1977
robert   | star trek           | 1966
james    | titanic             | 1997
bob      | star trek           | 1966
...

So if am interested in finding for login_id: bob what movies he watched plus who else watched the same movies expected output:

login_id | movie               | year
---------|---------------------|-----------
james    | titanic             | 1997
robert   | star trek           | 1966
...

I want to do it efficiently as possible and if I need to restructure the table I will do it. First guess:

SELECT login_id, movie, year, count(*)
 FROM watchers
 GROUP BY login_id, movie, year
 HAVING count(*) > 1 **and login_id = 'bob'**

The 'and' is where I am confuse, because it is grouping by count instead of pulling out all the common data.

Body:
I suggest using a self join:

Select t1.*
From  table t0
Join table t1 on t0.movie = t1.movie
And t0.year = t1.year
Where t0.login_id ='bob'