问:
Flutter upgrade issue with lots of un-understandable logs (no harm though)
I just upgraded flutter and right after the upgrade I am getting quite a bunch of logs in the console, which don't make sense to me, tried to surf the internet for such sort of errors but apparently there don't seem to be any traces of these kind of errors: For a start, you guys can help me in trying to understand these and how to go about this because it is getting to be quite hard to debug: I must also mention though that the they don't stop the app from running:

```<code>I/HwPhoneWindow(25343): updateLayoutParamsColor false mSpecialSet=true, mForcedNavigationBarColor=true, navigationBarColor=ff6451fe, mNavBarShow=true, mIsFloating=false
I/HwPhoneWindow(25343): updateLayoutParamsColor false mSpecialSet=true, mForcedNavigationBarColor=true, navigationBarColor=ff6451fe, mNavBarShow=true, mIsFloating=false
V/InputMethodManager(25343): Reporting focus gain, without startInput
V/InputMethodManager(25343): Reporting focus gain, without startInput
</code>```

Similarly whenever I get the following when I touch anywhere on the screen:

```<code>W/HiTouch_PressGestureDetector(25343): Touch pointer move a lot. The moving distance of X is:2.0, limit is:51The moving distance of Y is:69.0, limit is:51

Below log also just appears am currently not sure of what is triggering this yet:
W/InputMethodManager(25343): startInputReason = 8
W/IInputConnectionWrapper(25343): getExtractedText on inactive InputConnection
W/IInputConnectionWrapper(25343): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper(25343): requestCursorAnchorInfo on inactive InputConnection
D/ZrHung.AppEyeUiProbe(25343): stop checker.
W/libEGL  (25343): EGLNativeWindowType 0x755f41b010 disconnect failed
D/ViewRootImpl[MainActivity](25343): surface should not be released
D/FlutterView(25343): Detaching from a FlutterEngine:
io.flutter.embedding.engine.FlutterEngine@486f178
W/InputMethodManager(25343): startInputReason = 3
W/IInputConnectionWrapper(25343): getExtractedText on inactive InputConnection
W/IInputConnectionWrapper(25343): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper(25343): requestCursorAnchorInfo on inactive InputConnection
W/libEGL  (25343): EGLNativeWindowType 0x75660d7010 disconnect failed
V/ActivityThread(25343): Handle window ActivityRecord{d450bd5 token=android.os.BinderProxy@c9b5ecf{com.example.cmed/com.example.cmed.MainActivity}} visibility: false
D/ZrHung.AppEyeUiProbe(25343): Current Activity:false
D/ZrHung.AppEyeUiProbe(25343): not watching, wait.
E/        (25343): [ZeroHung]zrhung_get_config: Get config failed for wp[0x0008]
</code>```

答:
As I'd earlier stated in the comments, there is an issue with flutter v1.12.13+hotfix.8. The issue is currently not resolved yet but you can work around the problem as of now by downgrading:

```<code>run:

flutter version v1.12.13+hotfix.7
</code>```

This is because hotfix.8 is missing log filters

Body:
I just upgraded flutter and right after the upgrade I am getting quite a bunch of logs in the console, which don't make sense to me, tried to surf the internet for such sort of errors but apparently there don't seem to be any traces of these kind of errors: For a start, you guys can help me in trying to understand these and how to go about this because it is getting to be quite hard to debug: I must also mention though that the they don't stop the app from running:

I/HwPhoneWindow(25343): updateLayoutParamsColor false mSpecialSet=true, mForcedNavigationBarColor=true, navigationBarColor=ff6451fe, mNavBarShow=true, mIsFloating=false
I/HwPhoneWindow(25343): updateLayoutParamsColor false mSpecialSet=true, mForcedNavigationBarColor=true, navigationBarColor=ff6451fe, mNavBarShow=true, mIsFloating=false
V/InputMethodManager(25343): Reporting focus gain, without startInput
V/InputMethodManager(25343): Reporting focus gain, without startInput

Similarly whenever I get the following when I touch anywhere on the screen:

W/HiTouch_PressGestureDetector(25343): Touch pointer move a lot. The moving distance of X is:2.0, limit is:51The moving distance of Y is:69.0, limit is:51

Below log also just appears am currently not sure of what is triggering this yet:
W/InputMethodManager(25343): startInputReason = 8
W/IInputConnectionWrapper(25343): getExtractedText on inactive InputConnection
W/IInputConnectionWrapper(25343): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper(25343): requestCursorAnchorInfo on inactive InputConnection
D/ZrHung.AppEyeUiProbe(25343): stop checker.
W/libEGL  (25343): EGLNativeWindowType 0x755f41b010 disconnect failed
D/ViewRootImpl[MainActivity](25343): surface should not be released
D/FlutterView(25343): Detaching from a FlutterEngine:
io.flutter.embedding.engine.FlutterEngine@486f178
W/InputMethodManager(25343): startInputReason = 3
W/IInputConnectionWrapper(25343): getExtractedText on inactive InputConnection
W/IInputConnectionWrapper(25343): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper(25343): requestCursorAnchorInfo on inactive InputConnection
W/libEGL  (25343): EGLNativeWindowType 0x75660d7010 disconnect failed
V/ActivityThread(25343): Handle window ActivityRecord{d450bd5 token=android.os.BinderProxy@c9b5ecf{com.example.cmed/com.example.cmed.MainActivity}} visibility: false
D/ZrHung.AppEyeUiProbe(25343): Current Activity:false
D/ZrHung.AppEyeUiProbe(25343): not watching, wait.
E/        (25343): [ZeroHung]zrhung_get_config: Get config failed for wp[0x0008]

Body:
As I'd earlier stated in the comments, there is an issue with flutter v1.12.13+hotfix.8. The issue is currently not resolved yet but you can work around the problem as of now by downgrading:

run:

flutter version v1.12.13+hotfix.7

This is because hotfix.8 is missing log filters


来源: stackexchange

问:
Forcing CsvHelper to use a period decimal separator when generating CSV file
I have a C# / .Net 4.8 WPF app. I'm using CsvHelper to generate CSV files for various lists. I have the following code:

```<code>public void WriteRecord(List<T> data, string filename)
{
    using (TextWriter writer = new StreamWriter(filename))
    {
        using (CsvWriter csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
        {
            csv.WriteRecords(data);
            writer.Flush();
        }
   }
}
</code>```

I'm using a T generic because that way I can save any type of list to a CSV file. It's working fine, except for one problem. If the list type has a DateTime field, and the values include milliseconds, it is using a comma decimal separator between the seconds and milliseconds. This is a problem as I am using comma for the field separators. So in other words, if the object being saved has a DateTime field such as "2020/02/17 11:45:32.153" it is saving it as "2020/02/17 11:45:32,153"

Is there a way to force it to use a period decimal separator instead of a comma?

答:
Following the link that "Louis Go" posted in his comment above, this is what I did:

```<code>public void WriteRecord(List<T> data, string filename)
{
    using (TextWriter writer = new StreamWriter(filename))
    {
        using (CsvWriter csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
        {
            csv.Configuration.TypeConverterOptionsCache.GetOptions<DateTime>().Formats = new[] { "yyyy/MM/dd HH:mm:ss.fff" };
            csv.WriteRecords(data);
            writer.Flush();
        }
   }
}
</code>```

It's working perfectly now - using a period for the decimal separator, instead of a comma. Thanks Louis Go!

ContentLicense: CC BY-SA 4.0

Body:
I have a C# / .Net 4.8 WPF app. I'm using CsvHelper to generate CSV files for various lists. I have the following code:

public void WriteRecord(List<T> data, string filename)
{
    using (TextWriter writer = new StreamWriter(filename))
    {
        using (CsvWriter csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
        {
            csv.WriteRecords(data);
            writer.Flush();
        }
   }
}

I'm using a T generic because that way I can save any type of list to a CSV file. It's working fine, except for one problem. If the list type has a DateTime field, and the values include milliseconds, it is using a comma decimal separator between the seconds and milliseconds. This is a problem as I am using comma for the field separators. So in other words, if the object being saved has a DateTime field such as "2020/02/17 11:45:32.153" it is saving it as "2020/02/17 11:45:32,153"

Is there a way to force it to use a period decimal separator instead of a comma?

Body:
Following the link that "Louis Go" posted in his comment above, this is what I did:

public void WriteRecord(List<T> data, string filename)
{
    using (TextWriter writer = new StreamWriter(filename))
    {
        using (CsvWriter csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
        {
            csv.Configuration.TypeConverterOptionsCache.GetOptions<DateTime>().Formats = new[] { "yyyy/MM/dd HH:mm:ss.fff" };
            csv.WriteRecords(data);
            writer.Flush();
        }
   }
}

It's working perfectly now - using a period for the decimal separator, instead of a comma. Thanks Louis Go!


问:
Get CosmosDb Primary Connection String in ARM template
I have an ARM template which sources the primaryMasterKey of a cosmosDb as follows:

{

         "properties": {
          "enabled": true,
          "siteConfig": {
            "appSettings": [
              {
                "name": "MongoDb:CnnDetails",
                "value": "[listKeys(resourceId('Microsoft.DocumentDB/databaseAccounts', variables('cosmosdb_full')), '2015-04-08').primaryMasterKey]"
              }
       }

How to I modify it to get the actual connection string instead?

I've tried couple of things:

changed the word primaryMasterKey to primaryConnectionString.  This gives an error saying:

'The language expression property 'primaryConnectionString' doesn't exist, available properties are 'primaryMasterKey, secondaryMasterKey, primaryReadonlyMasterKey, secondaryReadonlyMasterKey'

changed the work listKeys to listConnectionStrings.  This is red underlined in my visual studio, but seems to work when put through azure devops

'The language expression property 'primaryConnectionString' doesn't exist, available properties are 'connectionStrings'

I went to https://learn.microsoft.com/en-us/rest/api/cosmos-db-resource-provider/databaseaccounts/listconnectionstrings#code-try-0 to try it out.  ListKeys returns a structure like this:

{
  "primaryMasterKey": "[REDACTED]",
  "secondaryMasterKey": "[REDACTED]",
  "primaryReadonlyMasterKey": "[REDACTED]",
  "secondaryReadonlyMasterKey": "[REDACTED]"
 }

so I get why the .primaryMasterKey worked.  But ListConnectionStrings returns:

```<code>{
  "connectionStrings": [
{
  "connectionString": "mongodb://[REDACTED]:10255/?ssl=true&replicaSet=globaldb",
  "description": "Primary MongoDB Connection String"
},
{
  "connectionString": "mongodb://[REDACTED]:10255/?ssl=true&replicaSet=globaldb",
  "description": "Secondary MongoDB Connection String"
},
{
  "connectionString": "mongodb://[REDACTED]:10255/?ssl=true&replicaSet=globaldb",
  "description": "Primary Read-Only MongoDB Connection String"
},
{
  "connectionString": "mongodb://[REDACTED]:10255/?ssl=true&replicaSet=globaldb",
  "description": "Secondary Read-Only MongoDB Connection String"
}
]
}
</code>```

Not sure how to "index into it"?

Any clues gratefully received.

答:
For anyone else finding this question and wanting a fully complete ARM Template snippet, this is what I have used and is working:</p>

```<code>"connectionStrings": [
 {
   "name": "CosmosConnection",
   "connectionString": "[listConnectionStrings(resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('cosmosDbAccountName')), '2019-12-12').connectionStrings[0].connectionString]",
   "type": 3
 }
]
</code>```

Body:
I have an ARM template which sources the primaryMasterKey of a cosmosDb as follows:

{

         "properties": {
          "enabled": true,
          "siteConfig": {
            "appSettings": [
              {
                "name": "MongoDb:CnnDetails",
                "value": "[listKeys(resourceId('Microsoft.DocumentDB/databaseAccounts', variables('cosmosdb_full')), '2015-04-08').primaryMasterKey]"
              }
       }

How to I modify it to get the actual connection string instead?

I've tried couple of things:

changed the word primaryMasterKey to primaryConnectionString.  This gives an error saying:

'The language expression property 'primaryConnectionString' doesn't exist, available properties are 'primaryMasterKey, secondaryMasterKey, primaryReadonlyMasterKey, secondaryReadonlyMasterKey'

changed the work listKeys to listConnectionStrings.  This is red underlined in my visual studio, but seems to work when put through azure devops

'The language expression property 'primaryConnectionString' doesn't exist, available properties are 'connectionStrings'

I went to https://learn.microsoft.com/en-us/rest/api/cosmos-db-resource-provider/databaseaccounts/listconnectionstrings#code-try-0 to try it out.  ListKeys returns a structure like this:

{
  "primaryMasterKey": "[REDACTED]",
  "secondaryMasterKey": "[REDACTED]",
  "primaryReadonlyMasterKey": "[REDACTED]",
  "secondaryReadonlyMasterKey": "[REDACTED]"
 }

so I get why the .primaryMasterKey worked.  But ListConnectionStrings returns:

{
  "connectionStrings": [
{
  "connectionString": "mongodb://[REDACTED]:10255/?ssl=true&replicaSet=globaldb",
  "description": "Primary MongoDB Connection String"
},
{
  "connectionString": "mongodb://[REDACTED]:10255/?ssl=true&replicaSet=globaldb",
  "description": "Secondary MongoDB Connection String"
},
{
  "connectionString": "mongodb://[REDACTED]:10255/?ssl=true&replicaSet=globaldb",
  "description": "Primary Read-Only MongoDB Connection String"
},
{
  "connectionString": "mongodb://[REDACTED]:10255/?ssl=true&replicaSet=globaldb",
  "description": "Secondary Read-Only MongoDB Connection String"
}
]
}

Not sure how to "index into it"?

Any clues gratefully received.

Body:
For anyone else finding this question and wanting a fully complete ARM Template snippet, this is what I have used and is working:

"connectionStrings": [
 {
   "name": "CosmosConnection",
   "connectionString": "[listConnectionStrings(resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('cosmosDbAccountName')), '2019-12-12').connectionStrings[0].connectionString]",
   "type": 3
 }
]


问:
Transpose column of values skipping blank cells in Google Sheets
https://i.stack.imgur.com/f2Ztx.png

I need help, for example, I have a condition of thousands of data like in red border and want to form it like in result border

What kind of transpose formula do I have to use?
try to figure it out with this formula

```<code>=ARRAYFORMULA(QUERY(A3:A&",",,55000))
</code>```

but still don't find a suitable result

答:
try:

```<code>=ARRAYFORMULA(SPLIT(QUERY(A3:A,,99^99), " "))
</code>```

or:

```<code>=TRANSPOSE(FILTER(A3:A, A3:A<>""))
</code>```

Body:
https://i.stack.imgur.com/f2Ztx.png

I need help, for example, I have a condition of thousands of data like in red border and want to form it like in result border

What kind of transpose formula do I have to use?
try to figure it out with this formula

=ARRAYFORMULA(QUERY(A3:A&",",,55000))

but still don't find a suitable result

Body:
try:

=ARRAYFORMULA(SPLIT(QUERY(A3:A,,99^99), " "))

or:

=TRANSPOSE(FILTER(A3:A, A3:A<>""))


问:
Numba jitting changes result when adding certain kind of 0 to local variable
Consider the following function for calculating the number of steps for a given input to the 3 n + 1 problem:

```<code>def num_steps(b, steps):
    e = b
    d = 0
    while True:
        if e == 1:
            d += steps[e]
            return d
        if e % 2 == 0:
            e //= 2
        else:
            e = 3*e + 1
        d += 1
</code>```

Here, steps exists to allow for memoization of the result, but for the sake of this question, we just note that as long as steps[1] == 0, it should have no effect, since in that case, the effect of d += steps[e] is to add 0 to d. Indeed, the following example gives the expected result:

```<code>import numpy as np

steps = np.array([0, 0, 0, 0])
print(num_steps(3, steps))  # Prints 7
</code>```

If, however, we JIT compile the method using numba.jit (or njit), we no longer get the right result:

```<code>import numpy as np
from numba import jit

steps = np.array([0, 0, 0, 0])
print(jit(num_steps)(3, steps))  # Prints 0
</code>```

If we remove the seemingly-redundant d += steps[e] before compiling the method, we do get the right result, though. We could even put in a print(steps[e]) prior to d += steps[e] and see that the value is 0. I can also move the d += 1 to the top of the loop (and initialize d = -1 instead) to get something that also works in the Numba case.

This happens with Numba 0.48.0 (llvmlite 0.31.0) on Python 3.8 (the most recent versions available through the standard conda channel).

答:
It looks like a bug to me, something with the in-place increment with steps[e]. If you set parallel=True that's where Numba crashes. You could create an issue at the Numba github repo, perhaps the developers can explain it.

If I rewrite the function to avoid that final in-place increment it works for me:

```<code>@numba.njit
def numb_steps(b, steps):

    e = b
    d = 0

    while True:

        if e == 1:
            return d + steps[e]

        if e % 2 == 0:
            e //= 2
        else:
            e = 3*e + 1

        d += 1
</code>```

With:

```<code>python                    3.7.6
numba                     0.47.0
</code>```

Body:
Consider the following function for calculating the number of steps for a given input to the 3 n + 1 problem:

def num_steps(b, steps):
    e = b
    d = 0
    while True:
        if e == 1:
            d += steps[e]
            return d
        if e % 2 == 0:
            e //= 2
        else:
            e = 3*e + 1
        d += 1

Here, steps exists to allow for memoization of the result, but for the sake of this question, we just note that as long as steps[1] == 0, it should have no effect, since in that case, the effect of d += steps[e] is to add 0 to d. Indeed, the following example gives the expected result:

import numpy as np

steps = np.array([0, 0, 0, 0])
print(num_steps(3, steps))  # Prints 7

If, however, we JIT compile the method using numba.jit (or njit), we no longer get the right result:

import numpy as np
from numba import jit

steps = np.array([0, 0, 0, 0])
print(jit(num_steps)(3, steps))  # Prints 0

If we remove the seemingly-redundant d += steps[e] before compiling the method, we do get the right result, though. We could even put in a print(steps[e]) prior to d += steps[e] and see that the value is 0. I can also move the d += 1 to the top of the loop (and initialize d = -1 instead) to get something that also works in the Numba case.

This happens with Numba 0.48.0 (llvmlite 0.31.0) on Python 3.8 (the most recent versions available through the standard conda channel).

Body:
It looks like a bug to me, something with the in-place increment with steps[e]. If you set parallel=True that's where Numba crashes. You could create an issue at the Numba github repo, perhaps the developers can explain it.

If I rewrite the function to avoid that final in-place increment it works for me:

@numba.njit
def numb_steps(b, steps):

    e = b
    d = 0

    while True:

        if e == 1:
            return d + steps[e]

        if e % 2 == 0:
            e //= 2
        else:
            e = 3*e + 1

        d += 1

With:

python                    3.7.6
numba                     0.47.0


问:
Unity tutorial - game object won't destroy
I'm following a Udemy 2D tutorial in Unity to create a 2D pixel game. Language is C#.
In my player script I have an attack function, such as when i press enter , a sword comes from the player body and go in which direction the player is looking ( like in the old zelda games ). In order to make the player freeze a little moment when he attacks, but also to make the sword range limited, i'm using a second script called Sword, the problem is that i think the script isn't called at all ( i tried to put some debug even in void start, but nothing.

here are the codes:

-This is my attack code:

```<code>void attack()
{
    canMove = false;
    GameObject newSword = Instantiate(sword, transform.position, sword.transform.rotation);
    #region //SwordRotation
    int swordDir = anim.GetInteger("dir");
    if (swordDir == 0)
    {
        newSword.transform.Rotate(0, 0, 0);
        newSword.GetComponent<Rigidbody2D>().AddForce(Vector2.up * thrustPower);
    }
    else if (swordDir == 1)
    {
        newSword.transform.Rotate(0, 0, 180);
        newSword.GetComponent<Rigidbody2D>().AddForce(Vector2.down * thrustPower);
    }
    else if (swordDir == 2)
    {
        newSword.transform.Rotate(0, 0, 90);
        newSword.GetComponent<Rigidbody2D>().AddForce(Vector2.left * thrustPower);
    }

    else if (swordDir == 3)
    {
        newSword.transform.Rotate(0, 0, -90);
        newSword.GetComponent<Rigidbody2D>().AddForce(Vector2.right * thrustPower);
    }
    #endregion

 }
</code>```

and this is my Sword code : I used it primarly because when the attack is made canMove is set to false, so I have to reset it to true after a short amount time to be able to move again.

PS: what i noticed is that the sword script has been directly created in the unity interface in the scripts folder and is at first glance not associated to any gameobject.

```<code>  {
public float timer;
// Start is called before the first frame update
void Start()
{
}

// Update is called once per frame
void Update()
{
    timer -= Time.deltaTime;
    if (timer <= 0)
    {
        GameObject.FindGameObjectWithTag("Player").GetComponent<Player>().canMove = true;
        Destroy(gameObject);

    }

}
</code>```

}

答:
Does your prefab have the script attached at the point of instantiation? If not, you would still need to AddComponent< SwordScript>() on it. Make sure it's on a parent that holds the important stuff, like colliders and meshes, and not some smaller child, so that all of it gets destroyed.

Also looks like you're not giving your timer a value (float timer; intead of float timer = 10f;). So when you instantiate your sword it would immediately be destroyed. Maybe that's why you can't see it?

Off topic - I would advise against doing this in Update():

```<code>    GameObject.FindGameObjectWithTag("Player").GetComponent<Player>().canMove = true;
</code>```

And instead consider giving the player a singleton, or at least getting that reference once at Start(). You're searching all gameobjects with that tag, trying to find the player for every sword in game 60 times per second, and getcomponent too. Idk if you have a good reason for doing this, but if not, consider changing that. Tbh not a huge deal if you're just experimenting and having fun, but still maybe something to consider at some point.

Body:
I'm following a Udemy 2D tutorial in Unity to create a 2D pixel game. Language is C#.
In my player script I have an attack function, such as when i press enter , a sword comes from the player body and go in which direction the player is looking ( like in the old zelda games ). In order to make the player freeze a little moment when he attacks, but also to make the sword range limited, i'm using a second script called Sword, the problem is that i think the script isn't called at all ( i tried to put some debug even in void start, but nothing.

here are the codes:

-This is my attack code:

void attack()
{
    canMove = false;
    GameObject newSword = Instantiate(sword, transform.position, sword.transform.rotation);
    #region //SwordRotation
    int swordDir = anim.GetInteger("dir");
    if (swordDir == 0)
    {
        newSword.transform.Rotate(0, 0, 0);
        newSword.GetComponent<Rigidbody2D>().AddForce(Vector2.up * thrustPower);
    }
    else if (swordDir == 1)
    {
        newSword.transform.Rotate(0, 0, 180);
        newSword.GetComponent<Rigidbody2D>().AddForce(Vector2.down * thrustPower);
    }
    else if (swordDir == 2)
    {
        newSword.transform.Rotate(0, 0, 90);
        newSword.GetComponent<Rigidbody2D>().AddForce(Vector2.left * thrustPower);
    }

    else if (swordDir == 3)
    {
        newSword.transform.Rotate(0, 0, -90);
        newSword.GetComponent<Rigidbody2D>().AddForce(Vector2.right * thrustPower);
    }
    #endregion

 }

and this is my Sword code : I used it primarly because when the attack is made canMove is set to false, so I have to reset it to true after a short amount time to be able to move again.

PS: what i noticed is that the sword script has been directly created in the unity interface in the scripts folder and is at first glance not associated to any gameobject.

  {
public float timer;
// Start is called before the first frame update
void Start()
{
}

// Update is called once per frame
void Update()
{
    timer -= Time.deltaTime;
    if (timer <= 0)
    {
        GameObject.FindGameObjectWithTag("Player").GetComponent<Player>().canMove = true;
        Destroy(gameObject);

    }

}

}

Body:
Does your prefab have the script attached at the point of instantiation? If not, you would still need to AddComponent< SwordScript>() on it. Make sure it's on a parent that holds the important stuff, like colliders and meshes, and not some smaller child, so that all of it gets destroyed.

Also looks like you're not giving your timer a value (float timer; intead of float timer = 10f;). So when you instantiate your sword it would immediately be destroyed. Maybe that's why you can't see it?

Off topic - I would advise against doing this in Update():

    GameObject.FindGameObjectWithTag("Player").GetComponent<Player>().canMove = true;

And instead consider giving the player a singleton, or at least getting that reference once at Start(). You're searching all gameobjects with that tag, trying to find the player for every sword in game 60 times per second, and getcomponent too. Idk if you have a good reason for doing this, but if not, consider changing that. Tbh not a huge deal if you're just experimenting and having fun, but still maybe something to consider at some point.


问:
why this regular does not Match the html using python
the html is :

```<code><div style="background-color:#A7A7A7;text-align:center;">
<span style="color:#FFFFFF;">{{rk_user.name}}のｽﾃｰﾀｽ</span>
</div>
</code>```

my Regular is :

```<code>a = r'''
<div style="background-color:#([a-z0-9]+);text-align:center;">
\s*<span style="color:#(.+?);">(.+)</span>
</div>
'''
</code>```

but this Regular does not Match the html ,

so what is wrong  ?

thanks

答:
You should make the regex case insensitive because the color is #A7A7A7 and you're matching #a7a7a7.

You can try it on many sites as: http://regexpal.com/

ContentLicense: CC BY-SA 3.0

Body:
the html is :

{{rk_user.name}}のｽﾃｰﾀｽ

my Regular is :

a = r'''

\s*(.+)

'''

but this Regular does not Match the html ,

so what is wrong  ?

thanks


问:
How to set UINavigationController as root from UITabBarController.?
I am working on App where Login is shown to user, after successful login user is landed on dashboard. where 4 tabs are shown to navigate to respective use.
I have to use, UITabBarController for four tabs from dashboard and UINavigationController for navigation from LoginView.

I set my UITabBarController to navigationController, when user successfully logged in.
Each view will have one logout button, on click of which I have to set my navigationcontroller back to root.

Here is code sample which I have done.

My UITabBarController

class TabBarVC: UITabBarController {

```<code>let dashboardViewObj = DashboardVC()
let registerViewObj = RegisterVC()
let alertViewObj = AlertVC()
let historyViewObj = HistoryVC()
override func viewDidLoad() {
    super.viewDidLoad()
    self.viewControllers = [dashboardViewObj, registerViewObj,historyViewObj,alertViewObj]
    // Do any additional setup after loading the view.

    dashboardViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .search, tag: 0)
    registerViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .history, tag: 0)
    historyViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 0)
    alertViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .bookmarks, tag: 0)
}
</code>```

In my LoginViewContoller

let tabbarObj = TabBarVC()

```<code>@IBAction func loginBtnClicked(_ sender: Any) {
            self.navigationController?.setViewControllers([tabbarObj], animated: true)
        }
</code>```

Now on click of logout button from any of these views, I need to set navigationController as root.
How to do it...?

Following chart will help to understand what I need.
Any help will be appeciated.

答:
@frzi :- Thank you very much for answers and correction from comment section.

I just did what you suggested.
The following line is corrected in my LoginViewController.

```<code>self.navigationController?.setViewControllers([tabbarObj], animated: true)
</code>```

To updated line as

```<code>self.navigationController?.pushViewController(tabbarObj, animated: true)
</code>```

And on Logout button action just added the line,

```<code>self.tabBarController?.navigationController?.popViewController(animated: true)
</code>```

and it worked...
Cheers J...

Body:
I am working on App where Login is shown to user, after successful login user is landed on dashboard. where 4 tabs are shown to navigate to respective use.
I have to use, UITabBarController for four tabs from dashboard and UINavigationController for navigation from LoginView.

I set my UITabBarController to navigationController, when user successfully logged in.
Each view will have one logout button, on click of which I have to set my navigationcontroller back to root.

Here is code sample which I have done.

My UITabBarController

class TabBarVC: UITabBarController {

let dashboardViewObj = DashboardVC()
let registerViewObj = RegisterVC()
let alertViewObj = AlertVC()
let historyViewObj = HistoryVC()
override func viewDidLoad() {
    super.viewDidLoad()
    self.viewControllers = [dashboardViewObj, registerViewObj,historyViewObj,alertViewObj]
    // Do any additional setup after loading the view.

    dashboardViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .search, tag: 0)
    registerViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .history, tag: 0)
    historyViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 0)
    alertViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .bookmarks, tag: 0)
}

In my LoginViewContoller

let tabbarObj = TabBarVC()

@IBAction func loginBtnClicked(_ sender: Any) {
            self.navigationController?.setViewControllers([tabbarObj], animated: true)
        }

Now on click of logout button from any of these views, I need to set navigationController as root.
How to do it...?

Following chart will help to understand what I need.
Any help will be appeciated.

Body:
@frzi :- Thank you very much for answers and correction from comment section.

I just did what you suggested.
The following line is corrected in my LoginViewController.

self.navigationController?.setViewControllers([tabbarObj], animated: true)

To updated line as

self.navigationController?.pushViewController(tabbarObj, animated: true)

And on Logout button action just added the line,

self.tabBarController?.navigationController?.popViewController(animated: true)

and it worked...
Cheers J...


问:
How to delete 1 of 2 data ranges for an existing chart using App Script?
For some context, I have a chart with originally 1 data range, which my existing macro adds a second data range to.

I now want to delete the charts original data range, so that it is only displaying the new data range. Is this possible to do via Google App Script?

答:
Just to explicitly answer this question I copied @Tanaike portion of the answer that solves your issue.

Pattern

var daily_data = spreadsheet.getSheetByName("Daily Data");
var LTD_data = spreadsheet.getSheetByName("Long Term Data");

var chart = daily_data.getCharts()[0];
var range = LTD_data.getRange("B2:J3")

var ranges = chart.getRanges();
chart = chart.modify();
ranges.forEach(function(range) {chart.removeRange(range)});
var modifiedChart = chart.addRange(range).build();
daily_data.updateChart(modifiedChart);
```

References:

updateChart(chart)

removeRange(range)

Body:
Just to explicitly answer this question I copied @Tanaike portion of the answer that solves your issue.

Pattern

var daily_data = spreadsheet.getSheetByName("Daily Data");
var LTD_data = spreadsheet.getSheetByName("Long Term Data");

var chart = daily_data.getCharts()[0];
var range = LTD_data.getRange("B2:J3")

var ranges = chart.getRanges();
chart = chart.modify();
ranges.forEach(function(range) {chart.removeRange(range)});
var modifiedChart = chart.addRange(range).build();
daily_data.updateChart(modifiedChart);

References:

updateChart(chart)

removeRange(range)


问:
Non readable - YANG
There is a way to define non readable data in yang?

```<code>module system{
   leaf name{
      type string;
   }
   leaf password{
      type string;
   }
}
</code>```

So in this case 'password' is the non readable data.

答:
If you wish to make the data "unreadable", you can use binary built-in type, which enables you to set an arbitrary blob of bytes (base64 encoded) as the value for a leaf. Encrypted bytes included.

```<code>leaf password {
  type binary;
  default "cGFzc3dvcmQ="; // <-- plain text "password"
}
</code>```

Title: Non readable - YANG

Body:
There is a way to define non readable data in yang?

module system{
   leaf name{
      type string;
   }
   leaf password{
      type string;
   }
}

So in this case 'password' is the non readable data.

Body:
If you wish to make the data "unreadable", you can use binary built-in type, which enables you to set an arbitrary blob of bytes (base64 encoded) as the value for a leaf. Encrypted bytes included.

leaf password {
  type binary;
  default "cGFzc3dvcmQ="; // <-- plain text "password"
}


问:
Cannot bind my Converter class in my XAML command that pass parameter
This is my XAML that is trying to have my ListView pass a parameter to the ViewModel command.

```<code>xmlns:mvvm="http://www.galasoft.ch/mvvmlight"

<ListBox x:Name="MyListView" ItemsSource="{Binding Objects}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <mvvm:EventToCommand Command="{Binding MyCommand}"
                                    PassEventArgsToCommand="True"
                                    EventArgsConverter="{StaticResource ParamConverter }"
                                    EventArgsConverterParameter ="{Binding Name}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
</code>```

And this is my converter:

```<code>public class ParamConverter : IEventArgsConverter
{
    public object Convert(object value, object parameter)
    {
        var args = (SelectionChangedEventArgs)value;

        var name = parameter as string;

        return (string)name.ToString();
    }
}
</code>```

But I got the following error:

The resource "ParamConverter" could not be resolved

答:
Your converter is not declared in XAML, you should add something like

```<code><ListBox.Resources>
  <yournamespace:ParamConverter x:Key="ParamConverter"/>
</ListBox.Resources>
</code>```

inside your listbox tags.

EDIT: I'm not an expert at all, so bear with my "imprecise" terms if any. I think you're missing something: there is no magic that allows your XAML to be aware of your C#. You need to tell XAML that somewhere in your code (in yournamespace) there will be a ParamConverter object, that can be referenced inside xaml with ParamConverter key.
You can declare your resource locally inside ListBox tags as suggested, or at outer scope if needed.
Once resource is declared inside XAML, you can access it via StaticResource.

Body:
This is my XAML that is trying to have my ListView pass a parameter to the ViewModel command.

xmlns:mvvm="http://www.galasoft.ch/mvvmlight"

<ListBox x:Name="MyListView" ItemsSource="{Binding Objects}">

            <mvvm:EventToCommand Command="{Binding MyCommand}"
                                    PassEventArgsToCommand="True"
                                    EventArgsConverter="{StaticResource ParamConverter }"
                                    EventArgsConverterParameter ="{Binding Name}"/>

    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

And this is my converter:

public class ParamConverter : IEventArgsConverter
{
    public object Convert(object value, object parameter)
    {
        var args = (SelectionChangedEventArgs)value;

        var name = parameter as string;

        return (string)name.ToString();
    }
}

But I got the following error:

The resource "ParamConverter" could not be resolved

Body:
Your converter is not declared in XAML, you should add something like

<ListBox.Resources>
  <yournamespace:ParamConverter x:Key="ParamConverter"/>
</ListBox.Resources>

inside your listbox tags.

EDIT: I'm not an expert at all, so bear with my "imprecise" terms if any. I think you're missing something: there is no magic that allows your XAML to be aware of your C#. You need to tell XAML that somewhere in your code (in yournamespace) there will be a ParamConverter object, that can be referenced inside xaml with ParamConverter key.
You can declare your resource locally inside ListBox tags as suggested, or at outer scope if needed.
Once resource is declared inside XAML, you can access it via StaticResource.


答:
Like @BoltClock mentions, it is not recommended to use regex like this. If not now, sometime down the line you will regret it. There are lots of corner cases which will make the regex complex and also plain useless at times.

Anyway, at a cursory glance, for background-color you have used [a-z0-9] that will only match lower case. But the sample has uppercase. You may want to have upper case as well [a-zA-Z0-9] For the other colors also, why don't you use the same? Why a (.+?)

Title: why this regular does not Match the html using python


问:
how to count the number of elements in XML?
I'm looking to get basic metadata about the data within a database.  Specifically, the number of line elements which are surrouned by the root text element.

Analogous to what I'd expect COUNT to return in SQL -- a single integer.

the database:

```<code>thufir@dur:~/flwor/group$
thufir@dur:~/flwor/group$ basex
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
>
> open people
Database 'people' was opened in 225.24 ms.
>
> xquery /
<text>
  <line>people</line>
  <line>joe</line>
  <line>phone1</line>
  <line>phone2</line>
  <line>phone3</line>
  <line>sue</line>
  <line>cell4</line>
  <line>home5</line>
  <line>alice</line>
  <line>atrib6</line>
  <line>x7</line>
  <line>y9</line>
  <line>z10</line>
</text>
Query executed in 215.13 ms.
>
> exit
See you.
thufir@dur:~/flwor/group$
</code>```

Counting the lines:

```<code>thufir@dur:~/flwor/group$
thufir@dur:~/flwor/group$ basex each.xq
1
2
3
4
5
6
7
8
9
10
11
12
13thufir@dur:~/flwor/group$
</code>```

code:

```<code>xquery version "3.0";

for $line in db:open("people")
for $index at $count in $line/text/line
return $count
</code>```

答: I suppose you simply want to use count(/text/line).

Body:
I'm looking to get basic metadata about the data within a database.  Specifically, the number of line elements which are surrouned by the root text element.

Analogous to what I'd expect COUNT to return in SQL -- a single integer.

the database:

thufir@dur:~/flwor/group$
thufir@dur:~/flwor/group$ basex
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
>
> open people
Database 'people' was opened in 225.24 ms.
>
> xquery /
<text>
  <line>people</line>
  <line>joe</line>
  <line>phone1</line>
  <line>phone2</line>
  <line>phone3</line>
  <line>sue</line>
  <line>cell4</line>
  <line>home5</line>
  <line>alice</line>
  <line>atrib6</line>
  <line>x7</line>
  <line>y9</line>
  <line>z10</line>
</text>
Query executed in 215.13 ms.
>
> exit
See you.
thufir@dur:~/flwor/group$

Counting the lines:

thufir@dur:~/flwor/group$
thufir@dur:~/flwor/group$ basex each.xq
1
2
3
4
5
6
7
8
9
10
11
12
13thufir@dur:~/flwor/group$

code:

xquery version "3.0";

for $line in db:open("people")
for $index at $count in $line/text/line
return $count


问:
Using Pandas Autocorrelation Plot - how to limit x-axis to make it more readable?
I am using python 3.7.

I am performing time series forecasting using an ARIMA model. I am assessing the properties of my data for ARIMA using an Autocorrelation Plot - specifically using autocorrelation_plot from pandas.plotting.

My data has 50,000 records or so, making the plot extremely busy and hard to pick out any specific trends. Is there a way to limit the x-axis to bring the first few hundred lags more into focus?

I can't share the actual plot, but my code is as follow:

import pandas as pd
from pandas.plotting import autocorrelation_plot

#Import Data
time_series_2619 = pd.read_csv("Consumption/2619.csv", parse_dates=['Date/Time'], index_col = ['Date/Time'])['Recording']

#Auto Correlation Plot
autocorrelation_plot(time_series_2619)
```

I couldn't find anything in the documentation.

答:
Just to add another way of plotting the autocorrelation, which to be honest is much faster in small-data cases:

```<code>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
plt.title('Autocorrelation plot')
plt.plot(np.arange(720), [time_series_2619['column_name'].autocorr(j) for j in range(720)])
plt.show();
</code>```

You are just using the Series.autocorr() function of a pandas series, which needs a lag number and returns the autocorrelation between the two timestamps. Doing a simple comprehension list you will be able to have an array of autocorrelations, which can be plotted easily using pyplot.

Body:
I am using python 3.7.

I am performing time series forecasting using an ARIMA model. I am assessing the properties of my data for ARIMA using an Autocorrelation Plot - specifically using autocorrelation_plot from pandas.plotting.

My data has 50,000 records or so, making the plot extremely busy and hard to pick out any specific trends. Is there a way to limit the x-axis to bring the first few hundred lags more into focus?

I can't share the actual plot, but my code is as follow:

import pandas as pd
from pandas.plotting import autocorrelation_plot

#Import Data
time_series_2619 = pd.read_csv("Consumption/2619.csv", parse_dates=['Date/Time'], index_col = ['Date/Time'])['Recording']

#Auto Correlation Plot
autocorrelation_plot(time_series_2619)

I couldn't find anything in the documentation.

Body:
Just to add another way of plotting the autocorrelation, which to be honest is much faster in small-data cases:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
plt.title('Autocorrelation plot')
plt.plot(np.arange(720), [time_series_2619['column_name'].autocorr(j) for j in range(720)])
plt.show();

You are just using the Series.autocorr() function of a pandas series, which needs a lag number and returns the autocorrelation between the two timestamps. Doing a simple comprehension list you will be able to have an array of autocorrelations, which can be plotted easily using pyplot.


问:
Ansible overwrites which variable? Inventory parameter or extra parameters at runtime?
I have a parameter pkg for all hosts of an envrionment specific inventory.

```<code>[atlanta]
host1
host2

[atlanta:vars]
ntp_server=ntp.atlanta.example.com
proxy=proxy.atlanta.example.com
pkg=123
</code>```

Now if I use the same variable pkg while executing an ansible playbook ex. ansible-playbook xyzzy.yml -e "pkg=123" with some different value. Which one will be picked by Ansible ? The value that is associated with pkg at Inventory level or the one given at runtime in command ?

答:
Extra variable (i.e. vars given at runtime) override all other variables. Inventory variables will be overriden by extra variable given at runtime. In detail, precedence is such as:

Here is the order of precedence from least to greatest (the last listed variables winning prioritization):

...

inventory file or script group vars

inventory group_vars/all

playbook group_vars/all

inventory group_vars/*

playbook group_vars/*

inventory file or script host vars

inventory host_vars/*

playbook host_vars/*

...

extra vars (always win precedence)

The doc is indeed a bit confusing. For clarification:

inventory file or script group vars are variables associated to groups in your inventory files. In your case, everything under atlanta:vars are inventory file group vars

```<code>[atlanta:vars]
pkg=123
</code>```

inventory file or script host vars are variables associated to a specific host and would have higher precedence other inventory file or script group vars, for example:

```<code>[atlanta]
host1 pkg=override-123
host2
</code>```

inventory group_vars/all|* are variables defined under inventories group_vars/ folder such as $PLAYBOOK_DIR/inventories/my-inventory/group_vars/atlanta/main.yml

playbook group_vars/all|* are variables defined under playbook group_vars/ folder such as $PLAYBOOK_DIR/group_vars/atlanta/main.yml

inventory host_vars/* are variables under inventories host_vars/ folder such as $PLAYBOOK_DIR/inventories/my-inventory/host_vars/somehostname.yml

playbook host_vars/* are variables under playbook host_vars/ folder such as $PLAYBOOK_DIR/host_vars/somehostname.yml

See Ansible doc on variable precedence.

You may also want to check out Directory Layout and Alternative Directory Layout for a better understand regarding all these directories and files.

Body:
I have a parameter pkg for all hosts of an envrionment specific inventory.

[atlanta]
host1
host2

[atlanta:vars]
ntp_server=ntp.atlanta.example.com
proxy=proxy.atlanta.example.com
pkg=123

Now if I use the same variable pkg while executing an ansible playbook ex. ansible-playbook xyzzy.yml -e "pkg=123" with some different value. Which one will be picked by Ansible ? The value that is associated with pkg at Inventory level or the one given at runtime in command ?

Body:
Extra variable (i.e. vars given at runtime) override all other variables. Inventory variables will be overriden by extra variable given at runtime. In detail, precedence is such as:

Here is the order of precedence from least to greatest (the last listed variables winning prioritization):

...

inventory file or script group vars

inventory group_vars/all

playbook group_vars/all

inventory group_vars/*

playbook group_vars/*

inventory file or script host vars

inventory host_vars/*

playbook host_vars/*

...

extra vars (always win precedence)

The doc is indeed a bit confusing. For clarification:

inventory file or script group vars are variables associated to groups in your inventory files. In your case, everything under atlanta:vars are inventory file group vars

[atlanta:vars]
pkg=123

inventory file or script host vars are variables associated to a specific host and would have higher precedence other inventory file or script group vars, for example:

[atlanta]
host1 pkg=override-123
host2

inventory group_vars/all|* are variables defined under inventories group_vars/ folder such as $PLAYBOOK_DIR/inventories/my-inventory/group_vars/atlanta/main.yml

playbook group_vars/all|* are variables defined under playbook group_vars/ folder such as $PLAYBOOK_DIR/group_vars/atlanta/main.yml

inventory host_vars/* are variables under inventories host_vars/ folder such as $PLAYBOOK_DIR/inventories/my-inventory/host_vars/somehostname.yml

playbook host_vars/* are variables under playbook host_vars/ folder such as $PLAYBOOK_DIR/host_vars/somehostname.yml

See Ansible doc on variable precedence.

You may also want to check out Directory Layout and Alternative Directory Layout for a better understand regarding all these directories and files.


问:
Pentaho CDE doesnt load with console error
I've been having trouble getting CDE to load CDE filed in edit since a restart of the service earlier today.  We have similar issues another environment but haven't ever been able to get to the bottom the the issue.  When I edit a CDE file the page doesn't ever load properly and a error is displayed in the console, preview also doesn't work.  I've tried restarting the service again, & clearing my cache.  Opening CDA files still works fine and the app is up,I can also open the CDE files, just edit doesn't load properly.

Error is on Pentaho user console 8.1.0.0.365:
  Uncaught TypeError: Cannot read property 'getPropertyObject' of undefined

答:
Finally traced the issue to a .KTR file with an invalid name in our endpoints folder.  Once deleted and the service restarted the issue is resolved and the editor loads as usual.

We managed to track this down via an error buried in the console:
enter image description here


答:
In JavaScript could be something like this, if you want it in other language it's just matter of language syntactic:

/*
   positions: array of positions
   times: array with the moments user stop ad each position
   p: interested position
   return: probabile time user stops at p (or saw p)
*/
function(positions, times, p){
    var tot = 0;
    if(position[0]>p) tot+= times[0]; // first position already greater than the desired once
    for(var i = 1; i < positions.length; i++){
        if(
             Math.min(positions[i-1], positions[i])
 p// smaller then the grater position between the current 2
                 ) tot+= times[i] - times[i-1];
    }
    return tot;
}
```

Title: Calculate how long user stop at indicator position on a website

Body:
I want to detect attention of users on a website. And I've data includes:

The scroll positions array (from top = 0): [982,1023,1125,1191,1193,1196,1228,1288,1359,1428,1476,1509,1511,1541,1625,1731,1814,1871,1882,1855,1812,1750,1661,1582,1564,1561,1504,1390,1281,1246,1216,1135,1043,985,981]

The time array in millisecond: (corresponding to scroll positions array):
[2514,2588,2687,2789,2883,3410,3490,3590,3691,3794,3890,3992,4083,4591,4692,4795,4894,4990,5082,8382,8482,8592,8691,8790,8882,9190,9291,9392,9489,9590,10090,10188,10289,10392,10482]

That's mean user scroll to 982px at 2514ms (origin 0 when user access the website); 1023px at 2588ms, ......

So I want to calculate how long user stop at specific point, example 1000px

Please note that user maybe scroll from TOP to BOTTOM, then BOTTOM to TOP

thanks!

Body:
In JavaScript could be something like this, if you want it in other language it's just matter of language syntactic:

/*
   positions: array of positions
   times: array with the moments user stop ad each position
   p: interested position
   return: probabile time user stops at p (or saw p)
*/
function(positions, times, p){
    var tot = 0;
    if(position[0]>p) tot+= times[0]; // first position already greater than the desired once
    for(var i = 1; i < positions.length; i++){
        if(
             Math.min(positions[i-1], positions[i]) < p // greater then the smaller position between the current 2
             &&
             Math.max(positions[i-1], positions[i]) > p// smaller then the grater position between the current 2
                 ) tot+= times[i] - times[i-1];
    }
    return tot;
}


问:
Meshlabserver: How to convert STL to PLY and unify vertices?
I have several .stl files that I would like to convert to .ply by calling meshlabserver from the command line. When I go the straightforward way

```<code>> meshlabserver -i cube-binary.stl -o cube.ply
</code>```

(where cube.stl is a sample file given below with 12 faces), the resulting mesh has 12 faces and 36 vertices. This means that no unification of repeated vertices has happened, although that was the very reason why I wanted to go for .ply instead of .stl.

Now, I assume that it is not possible for the same reason it was impossible make the vertex unification default in the Meshlab GUI (I asked about it some time ago, although it later turned out that such a question had already existed). But maybe someone knows some trick? Browsing through possible filters after -om, I did not find a solution.

The behaviour was tested with Meshlab 2016 on Open SUSE and with Meshlab v1.3.2_64bit on Ubuntu.

The sample file

(also created by Meshlab)

```<code>solid vcg
  facet normal  0.000000e+00  0.000000e+00  1.000000e+00
    outer loop
      vertex   5.000000e-01  5.000000e-01  5.000000e-01
      vertex  -5.000000e-01  5.000000e-01  5.000000e-01
      vertex   5.000000e-01 -5.000000e-01  5.000000e-01
    endloop
  endfacet
  facet normal  0.000000e+00  0.000000e+00  1.000000e+00
    outer loop
      vertex  -5.000000e-01 -5.000000e-01  5.000000e-01
      vertex   5.000000e-01 -5.000000e-01  5.000000e-01
      vertex  -5.000000e-01  5.000000e-01  5.000000e-01
    endloop
  endfacet
  facet normal  1.000000e+00  0.000000e+00  0.000000e+00
    outer loop
      vertex   5.000000e-01  5.000000e-01  5.000000e-01
      vertex   5.000000e-01 -5.000000e-01  5.000000e-01
      vertex   5.000000e-01  5.000000e-01 -5.000000e-01
    endloop
  endfacet
  facet normal  1.000000e+00  0.000000e+00  0.000000e+00
    outer loop
      vertex   5.000000e-01 -5.000000e-01 -5.000000e-01
      vertex   5.000000e-01  5.000000e-01 -5.000000e-01
      vertex   5.000000e-01 -5.000000e-01  5.000000e-01
    endloop
  endfacet
  facet normal  0.000000e+00  1.000000e+00  0.000000e+00
    outer loop
      vertex   5.000000e-01  5.000000e-01  5.000000e-01
      vertex   5.000000e-01  5.000000e-01 -5.000000e-01
      vertex  -5.000000e-01  5.000000e-01  5.000000e-01
    endloop
  endfacet
  facet normal  0.000000e+00  1.000000e+00  0.000000e+00
    outer loop
      vertex  -5.000000e-01  5.000000e-01 -5.000000e-01
      vertex  -5.000000e-01  5.000000e-01  5.000000e-01
      vertex   5.000000e-01  5.000000e-01 -5.000000e-01
    endloop
  endfacet
  facet normal  0.000000e+00  0.000000e+00 -1.000000e+00
    outer loop
      vertex  -5.000000e-01 -5.000000e-01 -5.000000e-01
      vertex  -5.000000e-01  5.000000e-01 -5.000000e-01
      vertex   5.000000e-01 -5.000000e-01 -5.000000e-01
    endloop
  endfacet
  facet normal -0.000000e+00 -0.000000e+00 -1.000000e+00
    outer loop
      vertex   5.000000e-01  5.000000e-01 -5.000000e-01
      vertex   5.000000e-01 -5.000000e-01 -5.000000e-01
      vertex  -5.000000e-01  5.000000e-01 -5.000000e-01
    endloop
  endfacet
  facet normal  0.000000e+00 -1.000000e+00  0.000000e+00
    outer loop
      vertex  -5.000000e-01 -5.000000e-01 -5.000000e-01
      vertex   5.000000e-01 -5.000000e-01 -5.000000e-01
      vertex  -5.000000e-01 -5.000000e-01  5.000000e-01
    endloop
  endfacet
  facet normal -0.000000e+00 -1.000000e+00 -0.000000e+00
    outer loop
      vertex   5.000000e-01 -5.000000e-01  5.000000e-01
      vertex  -5.000000e-01 -5.000000e-01  5.000000e-01
      vertex   5.000000e-01 -5.000000e-01 -5.000000e-01
    endloop
  endfacet
  facet normal -1.000000e+00  0.000000e+00  0.000000e+00
    outer loop
      vertex  -5.000000e-01 -5.000000e-01 -5.000000e-01
      vertex  -5.000000e-01 -5.000000e-01  5.000000e-01
      vertex  -5.000000e-01  5.000000e-01 -5.000000e-01
    endloop
  endfacet
  facet normal -1.000000e+00 -0.000000e+00 -0.000000e+00
    outer loop
      vertex  -5.000000e-01  5.000000e-01  5.000000e-01
      vertex  -5.000000e-01  5.000000e-01 -5.000000e-01
      vertex  -5.000000e-01 -5.000000e-01  5.000000e-01
    endloop
  endfacet
endsolid vcg
</code>```

答:
The easiest way is to use a script that apply the Remove Duplicate Vertices filter.

Try saving this to a file named cleanVertex.mlx

```<code><!DOCTYPE FilterScript>
<FilterScript>
 <filter name="Remove Duplicate Vertices"/>
 <filter name="Remove Unreferenced Vertices"/>
</FilterScript>

</code>```

And then using the command:

```<code>> meshlabserver -i cube-binary.stl -o cube.ply -s cleanVertex.mlx
</code>```

Body:
I have several .stl files that I would like to convert to .ply by calling meshlabserver from the command line. When I go the straightforward way

> meshlabserver -i cube-binary.stl -o cube.ply

(where cube.stl is a sample file given below with 12 faces), the resulting mesh has 12 faces and 36 vertices. This means that no unification of repeated vertices has happened, although that was the very reason why I wanted to go for .ply instead of .stl.

Now, I assume that it is not possible for the same reason it was impossible make the vertex unification default in the Meshlab GUI (I asked about it some time ago, although it later turned out that such a question had already existed). But maybe someone knows some trick? Browsing through possible filters after -om, I did not find a solution.

The behaviour was tested with Meshlab 2016 on Open SUSE and with Meshlab v1.3.2_64bit on Ubuntu.

The sample file

(also created by Meshlab)

solid vcg
  facet normal  0.000000e+00  0.000000e+00  1.000000e+00
    outer loop
      vertex   5.000000e-01  5.000000e-01  5.000000e-01
      vertex  -5.000000e-01  5.000000e-01  5.000000e-01
      vertex   5.000000e-01 -5.000000e-01  5.000000e-01
    endloop
  endfacet
  facet normal  0.000000e+00  0.000000e+00  1.000000e+00
    outer loop
      vertex  -5.000000e-01 -5.000000e-01  5.000000e-01
      vertex   5.000000e-01 -5.000000e-01  5.000000e-01
      vertex  -5.000000e-01  5.000000e-01  5.000000e-01
    endloop
  endfacet
  facet normal  1.000000e+00  0.000000e+00  0.000000e+00
    outer loop
      vertex   5.000000e-01  5.000000e-01  5.000000e-01
      vertex   5.000000e-01 -5.000000e-01  5.000000e-01
      vertex   5.000000e-01  5.000000e-01 -5.000000e-01
    endloop
  endfacet
  facet normal  1.000000e+00  0.000000e+00  0.000000e+00
    outer loop
      vertex   5.000000e-01 -5.000000e-01 -5.000000e-01
      vertex   5.000000e-01  5.000000e-01 -5.000000e-01
      vertex   5.000000e-01 -5.000000e-01  5.000000e-01
    endloop
  endfacet
  facet normal  0.000000e+00  1.000000e+00  0.000000e+00
    outer loop
      vertex   5.000000e-01  5.000000e-01  5.000000e-01
      vertex   5.000000e-01  5.000000e-01 -5.000000e-01
      vertex  -5.000000e-01  5.000000e-01  5.000000e-01
    endloop
  endfacet
  facet normal  0.000000e+00  1.000000e+00  0.000000e+00
    outer loop
      vertex  -5.000000e-01  5.000000e-01 -5.000000e-01
      vertex  -5.000000e-01  5.000000e-01  5.000000e-01
      vertex   5.000000e-01  5.000000e-01 -5.000000e-01
    endloop
  endfacet
  facet normal  0.000000e+00  0.000000e+00 -1.000000e+00
    outer loop
      vertex  -5.000000e-01 -5.000000e-01 -5.000000e-01
      vertex  -5.000000e-01  5.000000e-01 -5.000000e-01
      vertex   5.000000e-01 -5.000000e-01 -5.000000e-01
    endloop
  endfacet
  facet normal -0.000000e+00 -0.000000e+00 -1.000000e+00
    outer loop
      vertex   5.000000e-01  5.000000e-01 -5.000000e-01
      vertex   5.000000e-01 -5.000000e-01 -5.000000e-01
      vertex  -5.000000e-01  5.000000e-01 -5.000000e-01
    endloop
  endfacet
  facet normal  0.000000e+00 -1.000000e+00  0.000000e+00
    outer loop
      vertex  -5.000000e-01 -5.000000e-01 -5.000000e-01
      vertex   5.000000e-01 -5.000000e-01 -5.000000e-01
      vertex  -5.000000e-01 -5.000000e-01  5.000000e-01
    endloop
  endfacet
  facet normal -0.000000e+00 -1.000000e+00 -0.000000e+00
    outer loop
      vertex   5.000000e-01 -5.000000e-01  5.000000e-01
      vertex  -5.000000e-01 -5.000000e-01  5.000000e-01
      vertex   5.000000e-01 -5.000000e-01 -5.000000e-01
    endloop
  endfacet
  facet normal -1.000000e+00  0.000000e+00  0.000000e+00
    outer loop
      vertex  -5.000000e-01 -5.000000e-01 -5.000000e-01
      vertex  -5.000000e-01 -5.000000e-01  5.000000e-01
      vertex  -5.000000e-01  5.000000e-01 -5.000000e-01
    endloop
  endfacet
  facet normal -1.000000e+00 -0.000000e+00 -0.000000e+00
    outer loop
      vertex  -5.000000e-01  5.000000e-01  5.000000e-01
      vertex  -5.000000e-01  5.000000e-01 -5.000000e-01
      vertex  -5.000000e-01 -5.000000e-01  5.000000e-01
    endloop
  endfacet
endsolid vcg

Body:
The easiest way is to use a script that apply the Remove Duplicate Vertices filter.

Try saving this to a file named cleanVertex.mlx

<!DOCTYPE FilterScript>
<FilterScript>
 <filter name="Remove Duplicate Vertices"/>
 <filter name="Remove Unreferenced Vertices"/>
</FilterScript>

And then using the command:

> meshlabserver -i cube-binary.stl -o cube.ply -s cleanVertex.mlx


问:
How to reindex in ElasticSearch via Java API
Like title says...

I read this article (https://www.elastic.co/blog/changing-mapping-with-zero-downtime), and the concept was great, but I struggling to find decent reference on how to do it via JAVA API.

I found this plugin: https://github.com/karussell/elasticsearch-reindex, but seems like overkill of what I am trying to do

答:
You can use ES Reindex API to reduce your code amount

```<code> new ReindexRequestBuilder(client, ReindexAction.INSTANCE)
            .source("source_index")
            .destination("destination index")
            .get();
</code>```

Here is a official doc:
https://www.elastic.co/guide/en/elasticsearch/reference/7.6/docs-reindex.html

Body:
You can use ES Reindex API to reduce your code amount

 new ReindexRequestBuilder(client, ReindexAction.INSTANCE)
            .source("source_index")
            .destination("destination index")
            .get();

Here is a official doc:
https://www.elastic.co/guide/en/elasticsearch/reference/7.6/docs-reindex.html


问:
MySQL SELECT IFNULL then compare it numerically with other column
I've tried numerous methods to translate NULL to the number 0 upon selection:

```<code>SELECT
  ss.id AS staff_id,
  u.realname AS realname,
  ss.amount AS salary_amount,
  IF(s.paid_amount IS NOT NULL, s.paid_amount,0.00) AS paid_amount,
  (ss.amount-s.paid_amount)
FROM f_salary_staff ss
  JOIN user u ON (u.id=ss.user_id)
  LEFT JOIN (
    SELECT staff_id,
      month_year,
      SUM(amount) AS paid_amount
    FROM f_salary
    WHERE month_year='2020-02-29'
    GROUP BY staff_id,month_year
  ) s ON (ss.id=s.staff_id)
</code>```

I've used IFNULL but that doesn't turn the 0 into any numeric at all hence the selection didn't even list those with NULL values. Is there a way at all to turn NULL values into numerical upon selection and compare it against other columns numerically?

BTW .. down here is the create table statements for both tables.

f_salary_staff

```<code>CREATE TABLE `f_salary_staff` (  `id` int(11) NOT NULL AUTO_INCREMENT, `store_id` int(11) NOT NULL,  `user_id` int(11) NOT NULL,  `date_enter` date DEFAULT NULL,  `amount` decimal(12,2) DEFAULT NULL,  `updated` datetime DEFAULT NULL,  `updated_by` int(11) DEFAULT NULL,  `created` datetime DEFAULT NULL,  `created_by` int(11) DEFAULT NULL,  `last_activated` datetime DEFAULT NULL,  `last_inactivated` datetime DEFAULT NULL,  `status` varchar(16) DEFAULT NULL,  PRIMARY KEY (`id`), KEY `store_id` (`store_id`),  KEY `user_id` (`user_id`),  CONSTRAINT `f_salary_staff_ibfk_1` FOREIGN KEY (`store_id`) REFERENCES `store` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,  CONSTRAINT `f_salary_staff_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE )
</code>```

then f_salary

```<code>CREATE TABLE `f_salary` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `staff_id` int(11) NOT NULL,  `amount` decimal(12,2) DEFAULT NULL,  `note` tinytext,  `ref_date` date DEFAULT NULL,  `month_year` date DEFAULT NULL,  `created` datetime DEFAULT NULL,  `created_by` int(11) DEFAULT NULL,  `updated` datetime DEFAULT NULL,  `updated_by` int(11) DEFAULT NULL,  `approved` datetime DEFAULT NULL,  `approved_by` int(11) DEFAULT NULL,  PRIMARY KEY (`id`),  KEY `staff_id` (`staff_id`),  CONSTRAINT `f_salary_ibfk_1` FOREIGN KEY (`staff_id`) REFERENCES `f_salary_staff` (`id`) ON DELETE CASCADE ON UPDATE CASCADE )
</code>```

hope this helps those who needs to understand the table structure

答:
If i understand your need well, the following query should work :</p>

```<code>SELECT t.*
FROM (
  SELECT
    ss.id AS staff_id,
    u.realname AS realname,
    ss.amount AS salary_amount,
    COALESCE(s.paid_amount, 0) AS paid_amount
  FROM f_salary_staff ss
  INNER JOIN user u ON (u.id=ss.user_id)
  LEFT JOIN (
    SELECT staff_id, ref_date, SUM(amount) AS paid_amount
    FROM f_salary
    WHERE month_year='2020-02-29'
    GROUP BY staff_id, ref_date
  ) s ON (ss.id=s.staff_id)
) t
WHERE paid_amount > salary_amount
</code>```

Body:
I've tried numerous methods to translate NULL to the number 0 upon selection:

SELECT
  ss.id AS staff_id,
  u.realname AS realname,
  ss.amount AS salary_amount,
  IF(s.paid_amount IS NOT NULL, s.paid_amount,0.00) AS paid_amount,
  (ss.amount-s.paid_amount)
FROM f_salary_staff ss
  JOIN user u ON (u.id=ss.user_id)
  LEFT JOIN (
    SELECT staff_id,
      month_year,
      SUM(amount) AS paid_amount
    FROM f_salary
    WHERE month_year='2020-02-29'
    GROUP BY staff_id,month_year
  ) s ON (ss.id=s.staff_id)

I've used IFNULL but that doesn't turn the 0 into any numeric at all hence the selection didn't even list those with NULL values. Is there a way at all to turn NULL values into numerical upon selection and compare it against other columns numerically?

BTW .. down here is the create table statements for both tables.

f_salary_staff

CREATE TABLE `f_salary_staff` (  `id` int(11) NOT NULL AUTO_INCREMENT, `store_id` int(11) NOT NULL,  `user_id` int(11) NOT NULL,  `date_enter` date DEFAULT NULL,  `amount` decimal(12,2) DEFAULT NULL,  `updated` datetime DEFAULT NULL,  `updated_by` int(11) DEFAULT NULL,  `created` datetime DEFAULT NULL,  `created_by` int(11) DEFAULT NULL,  `last_activated` datetime DEFAULT NULL,  `last_inactivated` datetime DEFAULT NULL,  `status` varchar(16) DEFAULT NULL,  PRIMARY KEY (`id`), KEY `store_id` (`store_id`),  KEY `user_id` (`user_id`),  CONSTRAINT `f_salary_staff_ibfk_1` FOREIGN KEY (`store_id`) REFERENCES `store` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,  CONSTRAINT `f_salary_staff_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE )

then f_salary

CREATE TABLE `f_salary` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `staff_id` int(11) NOT NULL,  `amount` decimal(12,2) DEFAULT NULL,  `note` tinytext,  `ref_date` date DEFAULT NULL,  `month_year` date DEFAULT NULL,  `created` datetime DEFAULT NULL,  `created_by` int(11) DEFAULT NULL,  `updated` datetime DEFAULT NULL,  `updated_by` int(11) DEFAULT NULL,  `approved` datetime DEFAULT NULL,  `approved_by` int(11) DEFAULT NULL,  PRIMARY KEY (`id`),  KEY `staff_id` (`staff_id`),  CONSTRAINT `f_salary_ibfk_1` FOREIGN KEY (`staff_id`) REFERENCES `f_salary_staff` (`id`) ON DELETE CASCADE ON UPDATE CASCADE )

hope this helps those who needs to understand the table structure

Body:
If i understand your need well, the following query should work :

SELECT t.*
FROM (
  SELECT
    ss.id AS staff_id,
    u.realname AS realname,
    ss.amount AS salary_amount,
    COALESCE(s.paid_amount, 0) AS paid_amount
  FROM f_salary_staff ss
  INNER JOIN user u ON (u.id=ss.user_id)
  LEFT JOIN (
    SELECT staff_id, ref_date, SUM(amount) AS paid_amount
    FROM f_salary
    WHERE month_year='2020-02-29'
    GROUP BY staff_id, ref_date
  ) s ON (ss.id=s.staff_id)
) t
WHERE paid_amount > salary_amount


问:
parseerror when getting XML via jQuery AJAX
I want to pull an RSS feed via jQuery AJAX, but every time I do, I get a parsererror. My feed is relatively complex (using CDATA and custom namespaces), so I tried stripping down the document returned (along with a million other combinations), but even with an extremely simple document, it still fails. This is my AJAX code:

```<code>$.ajax({
    type: 'GET',
    url: ...,
    dataType: 'xml',

    success: function(xml) {
        ...
    },

    error: function(xhr, textStatus, error) {
        console.log('status: ' + textStatus);
        console.log(xhr.responseText);
        showError('an unknown error occurred while trying to fetch the feed: ' + xhr.status);
    }
});
</code>```

Console output:

```<code>status: parsererror
<?xml version="1.0"?>

<rss version="2.0">
    <channel>
        <title>title</title>
        <link>link</link>
        <description>desc</description>

        <lastBuildDate>build date</lastBuildDate>
        <generator>gen</generator>
    </channel>
</rss>
</code>```

答: Make sure to serve the document with a Content-Type header of application/rss+xml or text/xml.

ContentLicense: CC BY-SA 2.5

Body:
I want to pull an RSS feed via jQuery AJAX, but every time I do, I get a parsererror. My feed is relatively complex (using CDATA and custom namespaces), so I tried stripping down the document returned (along with a million other combinations), but even with an extremely simple document, it still fails. This is my AJAX code:

$.ajax({
    type: 'GET',
    url: ...,
    dataType: 'xml',

    success: function(xml) {
        ...
    },

    error: function(xhr, textStatus, error) {
        console.log('status: ' + textStatus);
        console.log(xhr.responseText);
        showError('an unknown error occurred while trying to fetch the feed: ' + xhr.status);
    }
});

Console output:

status: parsererror
<?xml version="1.0"?>

<rss version="2.0">
    <channel>
        <title>title</title>
        <link>link</link>
        <description>desc</description>

        <lastBuildDate>build date</lastBuildDate>
        <generator>gen</generator>
    </channel>
</rss>


问:
How can I randomly capitalise letters in a string
I'm sorry if this has been asked before, but I can't seem to find the right answer.

I'm trying to create a random password generator using Javascript. I've set meself 4 basic requirements:

Must contain letters, numbers and special characters

Must be 14 characters

Must have upper and lower case lettering

Must log the result as a string

Here is what I have:

```<code>var characters = 'abcdefghijklmnoqrstuvwxyz0123456789?<>!"£$%^&*()-+./';
var results = '';
var length = characters.length;

function randomPassword() {

for (i=0; i<=13; i++) {
    var mix = characters.charAt(Math.floor(Math.random() * length));
    var newString = results += mix;
    }
    console.log(newString);
}

randomPassword();
</code>```

The code above passes all of my requirements apart from the upper and lower case letters. Is there a way to randomly capitalise some of the letters in my string? I've tried playing with .toUpperCase() in the same way I have to create my 'mix' variable, but I can't work out how to do it.

This isn't for any real life projects. I'm just using this as a way to try to learn Javascript, so any advice would be greatly appreciated :)

Thanks!

答:
if you need to have both upper and lower characters and numbers and special chars, a random choice from a single characters variable can't always ensure this requirement.

In the version below I've created an array of characters subsets, where every required subset is included at least 3 times in the final password.

Simple version

var alphabet = [
  'abcdefghijklmnoqrstuvwxyz',
  'ABCDEFGHIJKLMNOQRSTUVWXYZ',
  '0123456789',
  '?<>!"£$%^&*()-+./'
];

password = '';

for (var i = 0; i < 14; i++) {
   var subset = alphabet[i%4];
   password += subset[Math.floor(Math.random() * subset.length)]
}

console.log(password);```
</div>
</div>
</p>

<hr>

<p><strong>Safer version</strong></p>

<p>here both the subsets and the password are scrambled using a JS implementation of Fisher-Yates algorithm so to avoid predictable generations.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function shuffle_Fisher_Yates(array) {

  var currentIndex = array.length, temporaryValue, randomIndex;

  while (0 !== currentIndex) {

    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

var alphabet = shuffle_Fisher_Yates([
  'abcdefghijklmnoqrstuvwxyz',
  'ABCDEFGHIJKLMNOQRSTUVWXYZ',
  '0123456789',
  '?<>!"£$%^&*()-+./'
]);

password = '';

for (var i = 0; i < 14; i++) {
   var subset = alphabet[i%4];
   password += subset[Math.floor(Math.random() * subset.length)]
}

console.log(shuffle_Fisher_Yates(password.split('')).join(''));</code>```

Body:
I'm sorry if this has been asked before, but I can't seem to find the right answer.

I'm trying to create a random password generator using Javascript. I've set meself 4 basic requirements:

Must contain letters, numbers and special characters

Must be 14 characters

Must have upper and lower case lettering

Must log the result as a string

Here is what I have:

var characters = 'abcdefghijklmnoqrstuvwxyz0123456789?<>!"£$%^&*()-+./';
var results = '';
var length = characters.length;

function randomPassword() {

for (i=0; i<=13; i++) {
    var mix = characters.charAt(Math.floor(Math.random() * length));
    var newString = results += mix;
    }
    console.log(newString);
}

randomPassword();

The code above passes all of my requirements apart from the upper and lower case letters. Is there a way to randomly capitalise some of the letters in my string? I've tried playing with .toUpperCase() in the same way I have to create my 'mix' variable, but I can't work out how to do it.

This isn't for any real life projects. I'm just using this as a way to try to learn Javascript, so any advice would be greatly appreciated :)

Thanks!

Body:
if you need to have both upper and lower characters and numbers and special chars, a random choice from a single characters variable can't always ensure this requirement.

In the version below I've created an array of characters subsets, where every required subset is included at least 3 times in the final password.

Simple version

var alphabet = [
  'abcdefghijklmnoqrstuvwxyz',
  'ABCDEFGHIJKLMNOQRSTUVWXYZ',
  '0123456789',
  '?<>!"£$%^&*()-+./'
];

password = '';

for (var i = 0; i < 14; i++) {
   var subset = alphabet[i%4];
   password += subset[Math.floor(Math.random() * subset.length)]
}

console.log(password);

Safer version

here both the subsets and the password are scrambled using a JS implementation of Fisher-Yates algorithm so to avoid predictable generations.

function shuffle_Fisher_Yates(array) {

  var currentIndex = array.length, temporaryValue, randomIndex;

  while (0 !== currentIndex) {

    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

var alphabet = shuffle_Fisher_Yates([
  'abcdefghijklmnoqrstuvwxyz',
  'ABCDEFGHIJKLMNOQRSTUVWXYZ',
  '0123456789',
  '?<>!"£$%^&*()-+./'
]);

password = '';

for (var i = 0; i < 14; i++) {
   var subset = alphabet[i%4];
   password += subset[Math.floor(Math.random() * subset.length)]
}

console.log(shuffle_Fisher_Yates(password.split('')).join(''));


问:
Core Data: NSPredicate for many-to-many relationship. ("to-many key not allowed here")
I have two entities named "Category" and "Article" which have a many to many relationship. I want to form a predicate which searches for all articles where category.name is equal to some value. I have the following:

```<code> NSEntityDescription  *entityArticle   = [NSEntityDescription entityForName:@"Article" inManagedObjectContext:managedObjectContext];
 NSSortDescriptor  *sortDescriptor   = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
 NSArray     *sortDescriptors  = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
 NSPredicate    *predicate    = [NSPredicate predicateWithFormat:@"categories.name == [cd] %@", category.name];

 [request setSortDescriptors:sortDescriptors];
 [request setEntity:entityArticle];
 [request setPredicate:predicate];

 NSMutableArray *results = [[managedObjectContext executeFetchRequest:request error:nil] mutableCopy];

 if ([results count] > 0)
  NSLog(@"Results found.");
 else
  NSLog(@"NO results found.");

 [request release];
 [sortDescriptor release];
 [sortDescriptors release];
</code>```

The error I receive is *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'to-many key not allowed here'

Are there any options to retrieve the desired data?

答:
For those who faced the same problem. You can use IN operator instead of = / == to look for specific objects in any Collection.
Look here for reference. No difference Swift or Objective-C

Body:
I have two entities named "Category" and "Article" which have a many to many relationship. I want to form a predicate which searches for all articles where category.name is equal to some value. I have the following:

 NSEntityDescription  *entityArticle   = [NSEntityDescription entityForName:@"Article" inManagedObjectContext:managedObjectContext];
 NSSortDescriptor  *sortDescriptor   = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
 NSArray     *sortDescriptors  = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
 NSPredicate    *predicate    = [NSPredicate predicateWithFormat:@"categories.name == [cd] %@", category.name];

 [request setSortDescriptors:sortDescriptors];
 [request setEntity:entityArticle];
 [request setPredicate:predicate];

 NSMutableArray *results = [[managedObjectContext executeFetchRequest:request error:nil] mutableCopy];

 if ([results count] > 0)
  NSLog(@"Results found.");
 else
  NSLog(@"NO results found.");

 [request release];
 [sortDescriptor release];
 [sortDescriptors release];

The error I receive is *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'to-many key not allowed here'

Are there any options to retrieve the desired data?


问:
Angular universal window is not defined
im trying to run SSR on my angular8 project but when i run server.js this error happens

    home/daba/client/dist/server/main.js:288235
})(window, document, 'Hammer');
^

ReferenceError: window is not defined
at Object.yLV6 (/home/daba/client/dist/server/main.js:288235:4)
at webpack_require (/home/daba/client/dist/server/main.js:20:30)
at Object.ZAI4 (/home/daba/client/dist/server/main.js:171354:1)
at webpack_require (/home/daba/client/dist/server/main.js:20:30)
at Object.V7fC (/home/daba/client/dist/server/main.js:161821:10)
at webpack_require (/home/daba/client/dist/server/main.js:20:30)
at Object.K011 (/home/daba/client/dist/server/main.js:125145:37)
at webpack_require (/home/daba/client/dist/server/main.js:20:30)
at Object.0 (/home/daba/client/dist/server/main.js:1251:18)
at webpack_require (/home/daba/
client/dist/server/main.js:20:30)
`
```

i've tried many things but still nothing

答:
Server-side applications can't reference browser-only global objects such as window, document, navigator, or location. You must check whether the code runs on the server or the client side:</p>

```<code>constructor(
    @Inject(PLATFORM_ID) private platformId: Object
)

...
myFunction() {
    if (isPlatformBrowser(this.platformId)) {
        // do something with window here
    }
}
</code>```

Title: Angular universal window is not defined

Body:
im trying to run SSR on my angular8 project but when i run server.js this error happens

    home/daba/client/dist/server/main.js:288235
})(window, document, 'Hammer');
^

ReferenceError: window is not defined
at Object.yLV6 (/home/daba/client/dist/server/main.js:288235:4)
at webpack_require (/home/daba/client/dist/server/main.js:20:30)
at Object.ZAI4 (/home/daba/client/dist/server/main.js:171354:1)
at webpack_require (/home/daba/client/dist/server/main.js:20:30)
at Object.V7fC (/home/daba/client/dist/server/main.js:161821:10)
at webpack_require (/home/daba/client/dist/server/main.js:20:30)
at Object.K011 (/home/daba/client/dist/server/main.js:125145:37)
at webpack_require (/home/daba/client/dist/server/main.js:20:30)
at Object.0 (/home/daba/client/dist/server/main.js:1251:18)
at webpack_require (/home/daba/
client/dist/server/main.js:20:30)
`

i've tried many things but still nothing

Body:
Server-side applications can't reference browser-only global objects such as window, document, navigator, or location. You must check whether the code runs on the server or the client side:

constructor(
    @Inject(PLATFORM_ID) private platformId: Object
)

...
myFunction() {
    if (isPlatformBrowser(this.platformId)) {
        // do something with window here
    }
}


问:
Convert javascript from minified to uncompressed?

Possible Duplicate:

  Can compressed javascript be uncompressed

How can I convert my javascript from mifified to uncompressed? Thanks

答: You can't get exact uncompressed file by beautifying minified as variable names will be changed</p>


问:
creating s3 bucket and folders inside it using node js in aws lambda function
I am both new to Node js and AWS. I am trying to create a bucket in S3 using node js in lambda function. Consequently, I am trying to create folders inside this S3 bucket.

I followed all the questions answered before and tried different iterations of code, but none of them seem to be working. Following is my code which is executing without giving any issues, yet the bucket and the folders are not getting created.

```<code>const AWS = require('aws-sdk');

let s3Client = new AWS.S3({
  accessKeyId: '<access_key_id>',
  secretAccessKey: '<secret_access_key>'
});

var params = {
  Bucket : 'pshycology06'
};

exports.handler = async (event, context, callback) => {

// call spaces to create the bucket
    s3Client.createBucket(params, function(err, data) {
      if (err) {
        console.log("\r\n[ERROR] : ", err);
      } else {
        console.log("\r\n[SUCCESS] : data = ",data);
      }
    });
};
</code>```

The code for creating folders inside the Lambda function is as following --

```<code>var AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
var s3Client = new AWS.S3({apiVersion: '2006-03-01'});

exports.handler = async (event, context) => {

    let params1 = { Bucket: 'travasko', Key: '2/dir1/dir2', Body:'body does not matter' };

    s3Client.putObject(params1, function (err, data) {
        if (err) {
            console.log("Error creating the folder: ", err);
        } else {
            console.log("Successfully created a folder on S3");
        }
    });
</code>```

Both of them doesn't work. I read a lot of documents on this issue and answers previously asked, but none of them are working for me.

The lambda function has a timeout of 1 minute. It has following policies for the IAM role -
1. AmazonRDSFullAccess
2. AmazonS3FullAccess
3. AWSLambdaVPCExecutionRole

The VPC security group is the default one.

Also, when I am trying to create the same bucket using the following AWS CLI command, it creates the bucket.

```<code>aws s3api create-bucket --bucket psychology06 --region us-east-1

</code>```

I am not sure, where am i making a mistake.

答:
Since, you are using async functionality. Thus, you have to use await on calling "s3Client.createBucket". Then resolve the received promise.

For creating folders, use trailing "/". For example "pshycology06/travasko/".

Do post error logs if these doesn't work.

Body:
I am both new to Node js and AWS. I am trying to create a bucket in S3 using node js in lambda function. Consequently, I am trying to create folders inside this S3 bucket.

I followed all the questions answered before and tried different iterations of code, but none of them seem to be working. Following is my code which is executing without giving any issues, yet the bucket and the folders are not getting created.

const AWS = require('aws-sdk');

let s3Client = new AWS.S3({
  accessKeyId: '<access_key_id>',
  secretAccessKey: '<secret_access_key>'
});

var params = {
  Bucket : 'pshycology06'
};

exports.handler = async (event, context, callback) => {

// call spaces to create the bucket
    s3Client.createBucket(params, function(err, data) {
      if (err) {
        console.log("\r\n[ERROR] : ", err);
      } else {
        console.log("\r\n[SUCCESS] : data = ",data);
      }
    });
};

The code for creating folders inside the Lambda function is as following --

var AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
var s3Client = new AWS.S3({apiVersion: '2006-03-01'});

exports.handler = async (event, context) => {

    let params1 = { Bucket: 'travasko', Key: '2/dir1/dir2', Body:'body does not matter' };

    s3Client.putObject(params1, function (err, data) {
        if (err) {
            console.log("Error creating the folder: ", err);
        } else {
            console.log("Successfully created a folder on S3");
        }
    });

Both of them doesn't work. I read a lot of documents on this issue and answers previously asked, but none of them are working for me.

The lambda function has a timeout of 1 minute. It has following policies for the IAM role -
1. AmazonRDSFullAccess
2. AmazonS3FullAccess
3. AWSLambdaVPCExecutionRole

The VPC security group is the default one.

Also, when I am trying to create the same bucket using the following AWS CLI command, it creates the bucket.

aws s3api create-bucket --bucket psychology06 --region us-east-1

I am not sure, where am i making a mistake.


问:
How can I redirect my Window page to another URL from the ajax called php function, I dont want to redirect it from jQuery or javascript
I have a main page url localhost/php/coadlines/home.php and hiting an ajax localhost/php/coadlines/processAjax.php but in processAjax.php page I want to some redirection function, so that My main page url ie.localhost/php/coadlines/home.php redirect to localhost/php/coadlines/index.php.
I dont want to write any redirection function in ajax success callback function like (window.location.replace()).

NOTE:ALL i need to do redirect it from PHP only dont want to do it from jQuery and javascript redirection.

答:
Short answer: you can't.

Long answer: you already finished sending the page, and it's in the browser's control now. If you want to add information (like a redirect), you have to do it using the javascript that's running on that page.

As a workaround, you might be able to instruct the first page to redirect after a delay, as described here. This is not-standard, not guaranteed to work, and does not guarantee that the ajax request finishes, but it might work for you use case. But if in any possible: use javascript.


问:
How to detect a click event of a button outside another method
Please find below the code I have implemented.

I need to detect the click event of the button outside another method.

```<code> public List<CorrectAnswer> passSessionIdTogetResults(String id) {

    db = this.getReadableDatabase();
    List<CorrectAnswer> correctAnswerList = new ArrayList<>();
    CorrectAnswer correctAnswer = new CorrectAnswer();

   Cursor cursor2 = db.rawQuery("SELECT * FROM table_test_start WHERE test_start_id ="+id,null);
   if(cursor2.moveToFirst()){

       do{

          String question_number= cursor2.getString(cursor2.getColumnIndex(ID_TEST));
          String question_id = cursor2.getString(cursor2.getColumnIndex(QUESTION_ID_TEST_START));
          String selected_option =  cursor2.getString(cursor2.getColumnIndex(SELECTED_OPTION_TEST_START));
          Cursor cursor = db.rawQuery("SELECT * FROM practice_questions WHERE question_content_id='"+question_id+"' AND question_answer='"+selected_option+"'", null);
           if (cursor.moveToFirst()) {
               String green = "green";

               correctAnswer.setCorrect_anwer_green(green);

               Log.d("DbHelper","Question ID "+question_id);
               Log.d("DbHelper","Correct Answer "+green);

           }else {

               String red = "red";
               correctAnswer.setWrong_answer_red(red);

               Log.d("DbHelper","Question ID "+question_id);
               Log.d("DbHelper","Wrong Answer " +red );
           }
           correctAnswer.setCorrect_id(question_number);
           correctAnswer.setQuestion_number_id(question_id);
           correctAnswer.setSelected_set_options(selected_option);
           correctAnswerList.add(correctAnswer);

      }while(cursor2.moveToNext());

    }

  return correctAnswerList;
}
</code>```

Getting last value of and inserted for n times.

答:
Try this

```<code>  String question_number= cursor2.getString(cursor2.getColumnIndex(ID_TEST));
  String question_id = cursor2.getString(cursor2.getColumnIndex(QUESTION_ID_TEST_START));
  String selected_option =  cursor2.getString(cursor2.getColumnIndex(SELECTED_OPTION_TEST_START));
  Cursor cursor = db.rawQuery("SELECT * FROM practice_questions WHERE question_content_id='"+question_id+"' AND question_answer='"+selected_option+"'", null);
   cursor.moveToFirst()
   do{
       String green = "green";

       correctAnswer.setCorrect_anwer_green(green);

       Log.d("DbHelper","Question ID "+question_id);
       Log.d("DbHelper","Correct Answer "+green);

   correctAnswer.setCorrect_id(question_number);
   correctAnswer.setQuestion_number_id(question_id);
   correctAnswer.setSelected_set_options(selected_option);
   correctAnswerList.add(correctAnswer);
} while(cursor2.moveToNext());
</code>```

Body:
Please find below the code I have implemented.

I need to detect the click event of the button outside another method.

 public List<CorrectAnswer> passSessionIdTogetResults(String id) {

    db = this.getReadableDatabase();
    List<CorrectAnswer> correctAnswerList = new ArrayList<>();
    CorrectAnswer correctAnswer = new CorrectAnswer();

   Cursor cursor2 = db.rawQuery("SELECT * FROM table_test_start WHERE test_start_id ="+id,null);
   if(cursor2.moveToFirst()){

       do{

          String question_number= cursor2.getString(cursor2.getColumnIndex(ID_TEST));
          String question_id = cursor2.getString(cursor2.getColumnIndex(QUESTION_ID_TEST_START));
          String selected_option =  cursor2.getString(cursor2.getColumnIndex(SELECTED_OPTION_TEST_START));
          Cursor cursor = db.rawQuery("SELECT * FROM practice_questions WHERE question_content_id='"+question_id+"' AND question_answer='"+selected_option+"'", null);
           if (cursor.moveToFirst()) {
               String green = "green";

               correctAnswer.setCorrect_anwer_green(green);

               Log.d("DbHelper","Question ID "+question_id);
               Log.d("DbHelper","Correct Answer "+green);

           }else {

               String red = "red";
               correctAnswer.setWrong_answer_red(red);

               Log.d("DbHelper","Question ID "+question_id);
               Log.d("DbHelper","Wrong Answer " +red );
           }
           correctAnswer.setCorrect_id(question_number);
           correctAnswer.setQuestion_number_id(question_id);
           correctAnswer.setSelected_set_options(selected_option);
           correctAnswerList.add(correctAnswer);

      }while(cursor2.moveToNext());

    }

  return correctAnswerList;
}

Getting last value of and inserted for n times.

Body:
Try this

  String question_number= cursor2.getString(cursor2.getColumnIndex(ID_TEST));
  String question_id = cursor2.getString(cursor2.getColumnIndex(QUESTION_ID_TEST_START));
  String selected_option =  cursor2.getString(cursor2.getColumnIndex(SELECTED_OPTION_TEST_START));
  Cursor cursor = db.rawQuery("SELECT * FROM practice_questions WHERE question_content_id='"+question_id+"' AND question_answer='"+selected_option+"'", null);
   cursor.moveToFirst()
   do{
       String green = "green";

       correctAnswer.setCorrect_anwer_green(green);

       Log.d("DbHelper","Question ID "+question_id);
       Log.d("DbHelper","Correct Answer "+green);

   correctAnswer.setCorrect_id(question_number);
   correctAnswer.setQuestion_number_id(question_id);
   correctAnswer.setSelected_set_options(selected_option);
   correctAnswerList.add(correctAnswer);
} while(cursor2.moveToNext());


问:
How to Filter a txt file in java
As input i have a File containing a list of rooms.
Each room has the following information: (1 line of the file)

```<code>ID;name;phonenumber;PIN e.g.:
1234;A 0.12;1234;123456789 (ID is same as [first] phonenumber)
2345;A 0.12;2345;123456789 (A room can have more than 1 phonenumber - in a new line like in the example)
</code>```

Now i need a java program which returns a list like this:

```<code>Example Input:
1127,A 0.01,1127,1
2476,A 0.01,2476,1
2309,A 0.01,2309,1
2306,A 0.01,2306,1
2706,A 0.01,2706,1
2757,A 0.01,2757,1
Generates Output:
1127,A 0.01,1127,2476,2309,2306,2706,2757,1
</code>```

ID;name;phonenumber1;...;phonenumberN;PIN

This code (without main function) adds a second phone number to the existing one, if the rooms from 2 lines are the same.

```<code>public static String duplicateNumbers(String s, String x) {

    String result = s;
    if(compareString(s, x)) {
         result = result.substring(0, 21)
                 + x.charAt(21) + x.charAt(22) + x.charAt(23) + x.charAt(24)
                 + result.substring(20);
    }
    return result;
}

public static boolean compareString(String s, String x) {
    for(int i = 5; i < 10; i++) {
        if(s.charAt(i) != x.charAt(i)) return false;
    }
    return true;
}
</code>```

ß

答:
Try This:</p>

```<code>String fileName = "D:/test.txt";

try (Stream<String> stream = Files.lines(Paths.get(fileName))) {

  stream.forEach(System.out::println);

} catch (IOException e) {
  e.printStackTrace();
}
</code>```

Title: How to Filter a txt file in java

Body:
As input i have a File containing a list of rooms.
Each room has the following information: (1 line of the file)

ID;name;phonenumber;PIN e.g.:
1234;A 0.12;1234;123456789 (ID is same as [first] phonenumber)
2345;A 0.12;2345;123456789 (A room can have more than 1 phonenumber - in a new line like in the example)

Now i need a java program which returns a list like this:

Example Input:
1127,A 0.01,1127,1
2476,A 0.01,2476,1
2309,A 0.01,2309,1
2306,A 0.01,2306,1
2706,A 0.01,2706,1
2757,A 0.01,2757,1
Generates Output:
1127,A 0.01,1127,2476,2309,2306,2706,2757,1

ID;name;phonenumber1;...;phonenumberN;PIN

This code (without main function) adds a second phone number to the existing one, if the rooms from 2 lines are the same.

public static String duplicateNumbers(String s, String x) {

    String result = s;
    if(compareString(s, x)) {
         result = result.substring(0, 21)
                 + x.charAt(21) + x.charAt(22) + x.charAt(23) + x.charAt(24)
                 + result.substring(20);
    }
    return result;
}

public static boolean compareString(String s, String x) {
    for(int i = 5; i < 10; i++) {
        if(s.charAt(i) != x.charAt(i)) return false;
    }
    return true;
}

ß

Body:
Try This:

String fileName = "D:/test.txt";

try (Stream<String> stream = Files.lines(Paths.get(fileName))) {

  stream.forEach(System.out::println);

} catch (IOException e) {
  e.printStackTrace();
}


问:
No post found matching the query
views.py

```<code>class PostDetailView(DetailView):
    model = Post
    template_name = 'blog/post_detail.html'
</code>```

urls.py

```<code>path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail')
</code>```

When I go to 127.0.0.1:8000/post/1, it says no post found matching the query

Screenshot

答:
In Views.py

```<code>class PostDetailView(DetailView):
   model = Post
   template_name = 'blog/post_detail.html'
   lookup_field = 'id'

   def get_object(self, *args, **kwargs):
      kwargs = self.kwargs
      kw_id = kwargs.get('id')
      return Post.objects.get(id=kw_id)
</code>```

Title: No post found matching the query

Body:
views.py

class PostDetailView(DetailView):
    model = Post
    template_name = 'blog/post_detail.html'

urls.py

path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail')

When I go to 127.0.0.1:8000/post/1, it says no post found matching the query

Screenshot

Body:
In Views.py

class PostDetailView(DetailView):
   model = Post
   template_name = 'blog/post_detail.html'
   lookup_field = 'id'

   def get_object(self, *args, **kwargs):
      kwargs = self.kwargs
      kw_id = kwargs.get('id')
      return Post.objects.get(id=kw_id)


问:
How to rectify code from zero division error:
I am writing a program to find the cube root of a number. I am getting a division by zero error. I have changed all values to float but still getting the error.

Here is the code.

```<code>def cube_root(num):
    import random
    g = random.randint(1,num+1)
    new_g = float(num/(g*g))
    check_ifclose(g,new_g,num)

def check_ifclose(g,new_g,num):
    from math import isclose
    if isclose(g, new_g, abs_tol=0.0000001):
        print("The cube root of ",num,"is ",float(new_g))
    else:
        g = float(new_g)
        new_g = float(num/(g*g))
        check_ifclose(g,new_g,num)
</code>```

This is the error that I am getting

```<code>ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-53-7ad3ad630bd7> in <module>
----> 1 cube_root(16)

<ipython-input-52-46121e93a109> in cube_root(num)
      3     g = random.randint(1,num+1)
      4     new_g = float(num/(g*g))
----> 5     check_ifclose(g,new_g,num)
      6
      7 def check_ifclose(g,new_g,num):

<ipython-input-52-46121e93a109> in check_ifclose(g, new_g, num)
     12         g = float(new_g)
     13         new_g = float(num/(g*g))
---> 14         check_ifclose(g,new_g,num)

ZeroDivisionError: float division by zero
</code>```

答: The issue is that if you have very small numbers as g (less than 1e-200) then the g * g python "treats" as 0. Check here https://docs.python.org/3.7/tutorial/floatingpoint.html.

Body:
I am writing a program to find the cube root of a number. I am getting a division by zero error. I have changed all values to float but still getting the error.

Here is the code.

def cube_root(num):
    import random
    g = random.randint(1,num+1)
    new_g = float(num/(g*g))
    check_ifclose(g,new_g,num)

def check_ifclose(g,new_g,num):
    from math import isclose
    if isclose(g, new_g, abs_tol=0.0000001):
        print("The cube root of ",num,"is ",float(new_g))
    else:
        g = float(new_g)
        new_g = float(num/(g*g))
        check_ifclose(g,new_g,num)

This is the error that I am getting

ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-53-7ad3ad630bd7> in <module>
----> 1 cube_root(16)

<ipython-input-52-46121e93a109> in cube_root(num)
      3     g = random.randint(1,num+1)
      4     new_g = float(num/(g*g))
----> 5     check_ifclose(g,new_g,num)
      6
      7 def check_ifclose(g,new_g,num):

<ipython-input-52-46121e93a109> in check_ifclose(g, new_g, num)
     12         g = float(new_g)
     13         new_g = float(num/(g*g))
---> 14         check_ifclose(g,new_g,num)

ZeroDivisionError: float division by zero