问:
Jquery Tools Slideshow Plugin : disable action onclick in
 for use external link
I'm new to jquery and i got a problem to use Jquery Tools Slideshow Plugin.
Could someone help me please.

For my case i have many link in a html block called (image like the example bellow)

http://flowplayer.org/tools/demos/tabs/slideshow.htm

i would like to disable function onclick that passe my div to the next one. Because in my div i have many external links and i would like to allow the user to click on my links.

Finally, could someone tell me how to do that please.

Thanks in advanced.

Patrick

```<code>$(".slidetabs").tabs(".images > div", {

    // enable "cross-fading" effect
    effect: 'fade',
    fadeOutSpeed: "slow",

    // start from the beginning after the last tab
    rotate: true

// use the slideshow plugin. It accepts its own configuration
}).slideshow();
</code>```

答:
```<code>$(".slidetabs").tabs(".images > div").unbind("click");
</code>```

Or if you only want it for the ones containing links:

```<code>$(".slidetabs").tabs(".images > div").has("a").unbind("click");
</code>```

Title: Jquery Tools Slideshow Plugin : disable action onclick in <div class="images"> for use external link

Body:
I'm new to jquery and i got a problem to use Jquery Tools Slideshow Plugin.
Could someone help me please.

For my case i have many link in a html block called (image like the example bellow)

http://flowplayer.org/tools/demos/tabs/slideshow.htm

i would like to disable function onclick that passe my div to the next one. Because in my div i have many external links and i would like to allow the user to click on my links.

Finally, could someone tell me how to do that please.

Thanks in advanced.

Patrick

$(".slidetabs").tabs(".images > div", {

    // enable "cross-fading" effect
    effect: 'fade',
    fadeOutSpeed: "slow",

    // start from the beginning after the last tab
    rotate: true

// use the slideshow plugin. It accepts its own configuration
}).slideshow();

Body:
$(".slidetabs").tabs(".images > div").unbind("click");

Or if you only want it for the ones containing links:

$(".slidetabs").tabs(".images > div").has("a").unbind("click");


来源: stackexchange

问:
Clarification on calling srand
I'm wondering why it's advantageous to seed srand at the beginning of the program, instead of where I use it.

I generate pseudo-random numbers when seeding srand at the beginning of my program but I get the numbers all the same when I seed srand inside the function I call to generate the numbers

```<code>#include <iostream>
#include <ctime>
using namespace std;

int rng()
{
    const int SIZE = 10;
    int rng[10];
  srand(time(NULL));
    for (int i = 0; i < 10; i++)
    {
        rng[i] = rand() % 128 + 1;
        return rng[i];
    }

}

int main()
{
    int array;
  //srand(time(NULL)); If i put it here i get actual random numbers
    cout << "Welcome to the program";
    cout << "\nthis is your rng\n";
    for (int i = 0; i < 10; i++)
    {
        array = rng();
        cout << array << endl;
    }

    return 0;
}
</code>```

When I run the program all of the numbers are the same, but when I delete the seeding from in the rng function and uncomment the srand in the main module the numbers are pseudo-random which is what I want. Im wondering why though. I've looked into it and heard that im seeding srand with a time and when I run that function the loop iterates so fast that all of the numbers are generated with the same seed value so they're all the same, but I'm wondering what's the difference from that and having srand(time(NULL)) in main because either way doesn't the function generate the numbers so fast they'll be at the same seed value anyway? It doesn't appear that way because of the different output but im curious, why?

答:
time returns number of seconds since 1.1.1970 so calling it repeatedly during one second will indeed return same values. It doesn't matter exactly where you put srand as long as it's before all rand calls and it should only be called once per program as it's global and obviously resets the random sequence. So if you use it only where you need it, you risk that when some other part of the code will need it too and calls srand again, it will interfere with your rand calls. It's not necessary to call it at all but then the seed will always be the same. It's good for debugging to have an option to set the seed deterministicly.

That said, don't use it, just don't.

As you observed time is not a good seed generator and rand is not even good random number generator, certainly not for floats and x mod n. Use <random> library. It has std::random_device which can generate true random numbers = good seeds. Sadly it's not required to. std::mt19937 is go-to RNG which together with std::XX_YY_distributions should be more than enough for everything but the most extreme need for randomness. It's also thread-safe because you control access to the generator and how it's used.

ContentLicense: CC BY-SA 4.0

Title: Clarification on calling srand

Body:
I'm wondering why it's advantageous to seed srand at the beginning of the program, instead of where I use it.

I generate pseudo-random numbers when seeding srand at the beginning of my program but I get the numbers all the same when I seed srand inside the function I call to generate the numbers

#include <iostream>
#include <ctime>
using namespace std;

int rng()
{
    const int SIZE = 10;
    int rng[10];
  srand(time(NULL));
    for (int i = 0; i < 10; i++)
    {
        rng[i] = rand() % 128 + 1;
        return rng[i];
    }

}

int main()
{
    int array;
  //srand(time(NULL)); If i put it here i get actual random numbers
    cout << "Welcome to the program";
    cout << "\nthis is your rng\n";
    for (int i = 0; i < 10; i++)
    {
        array = rng();
        cout << array << endl;
    }

    return 0;
}

When I run the program all of the numbers are the same, but when I delete the seeding from in the rng function and uncomment the srand in the main module the numbers are pseudo-random which is what I want. Im wondering why though. I've looked into it and heard that im seeding srand with a time and when I run that function the loop iterates so fast that all of the numbers are generated with the same seed value so they're all the same, but I'm wondering what's the difference from that and having srand(time(NULL)) in main because either way doesn't the function generate the numbers so fast they'll be at the same seed value anyway? It doesn't appear that way because of the different output but im curious, why?


问:
updatePickerInput default select all choices
I know that there is a very similar question on StackExchange (pickerInput default select all choices), however, the solution can not be applied to my problem.
I have a updatePickerInput which is based on two Inputs. on the updatePickerInput I have the selectAll and clearAll buttons from shinyWidgets. I want selectAll to be the default, but since it is dynamically, I dont know how to pass my choices into the selected option.

Here is my relevant ui code:

```<code>radioButtons(inputId = 'selected_group', label = 'group', choices = '')
</code>```

This is my observeEvent code:

```<code>observeEvent(c(input$selected_tab,input$selected_group),{
    req(input$selected_group)

    updatePickerInput(
        session,
        'selected_subgroup',
        choices = df %>%
            filter(tab == input$selected_tab) %>%
            filter(group == input$selected_group) %>%
            select(subgroup) %>%
            distinct(subgroup) %>%
            arrange(subgroup) %>%
            .[[1]]
    )
})
</code>```

答:
To have all options selected dynamically you'll need to pass the same information to updatePickerInput's choices and selected arguments:

```<code>library(shiny)
library(datasets)
library(shinyWidgets)

statesDF <- data.frame(region = state.region, name = state.name, area = state.area, stringsAsFactors = FALSE)

ui <- fluidPage(
  radioButtons(inputId = 'selected_group', label = 'group', choices = unique(statesDF$region)),
  pickerInput(inputId = 'selected_subgroup', label = 'subgroup', choices = NULL, selected = NULL, multiple = TRUE)
)

server <- function(input, output, session) {
  filteredChoices <- reactive({
    statesDF$name[statesDF$region == input$selected_group]
  })

  observeEvent(filteredChoices(), {
    updatePickerInput(session, inputId = 'selected_subgroup', label = 'subgroup', choices = filteredChoices(), selected = filteredChoices())
  })

}

shinyApp(ui = ui, server = server)
</code>```

Body:
I know that there is a very similar question on StackExchange (pickerInput default select all choices), however, the solution can not be applied to my problem.
I have a updatePickerInput which is based on two Inputs. on the updatePickerInput I have the selectAll and clearAll buttons from shinyWidgets. I want selectAll to be the default, but since it is dynamically, I dont know how to pass my choices into the selected option.

Here is my relevant ui code:

radioButtons(inputId = 'selected_group', label = 'group', choices = '')

This is my observeEvent code:

observeEvent(c(input$selected_tab,input$selected_group),{
    req(input$selected_group)

    updatePickerInput(
        session,
        'selected_subgroup',
        choices = df %>%
            filter(tab == input$selected_tab) %>%
            filter(group == input$selected_group) %>%
            select(subgroup) %>%
            distinct(subgroup) %>%
            arrange(subgroup) %>%
            .[[1]]
    )
})

Body:
To have all options selected dynamically you'll need to pass the same information to updatePickerInput's choices and selected arguments:

library(shiny)
library(datasets)
library(shinyWidgets)

statesDF <- data.frame(region = state.region, name = state.name, area = state.area, stringsAsFactors = FALSE)

ui <- fluidPage(
  radioButtons(inputId = 'selected_group', label = 'group', choices = unique(statesDF$region)),
  pickerInput(inputId = 'selected_subgroup', label = 'subgroup', choices = NULL, selected = NULL, multiple = TRUE)
)

server <- function(input, output, session) {
  filteredChoices <- reactive({
    statesDF$name[statesDF$region == input$selected_group]
  })

  observeEvent(filteredChoices(), {
    updatePickerInput(session, inputId = 'selected_subgroup', label = 'subgroup', choices = filteredChoices(), selected = filteredChoices())
  })

}

shinyApp(ui = ui, server = server)


问:
How to make use of an ASP.Net MVC controller action using Ajax to return the difference between two dates in a form?
I'm using MVC3 and have a view which is used to book leave for employees. As part of this I want to display the number of days to be taken based on two dates that they enter - I've done this in a rudimentary way using jQuery but want to make use of a controller action I've got which will return a single value based on the two dates (it takes into account weekends and bank holidays).

The question is, what is the best way to pass the values of DateFrom and DateTo (the two inputs) to the controller and retrieve the result using Ajax? I want this value to update whenever either of the dates is changed and without submitting the whole form.

I'm not sure of the best practice for this sort of thing so any help would be appreciated.

答:
The question is, what is the best way to pass the values of DateFrom and DateTo (the two inputs) to the controller and retrieve the result using Ajax?

You could subscribe to the change event of those textboxes and send an AJAX request:

```<code>$(function() {
    $('#DateFrom, #DateTo').change(function() {
        // whenever the user changes the value send an AJAX request:
        $.ajax({
            url: '@Url.Action("SomeAction", "SomeController")',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({
                dateFrom: $('#DateFrom').val(),
                dateTo: $('#DateTo').val()
            }),
            success: function(result) {
                // TODO: The AJAX call succeeded => do something with the results
            }
        });
    });
});
</code>```

and the controller action could look like this:

```<code>public ActionResult SomeAction(DateTime dateFrom, DateTime dateTo)
{
    ...
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The question is, what is the best way to pass the values of DateFrom and DateTo (the two inputs) to the controller and retrieve the result using Ajax?

You could subscribe to the change event of those textboxes and send an AJAX request:

$(function() {
    $('#DateFrom, #DateTo').change(function() {
        // whenever the user changes the value send an AJAX request:
        $.ajax({
            url: '@Url.Action("SomeAction", "SomeController")',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({
                dateFrom: $('#DateFrom').val(),
                dateTo: $('#DateTo').val()
            }),
            success: function(result) {
                // TODO: The AJAX call succeeded => do something with the results
            }
        });
    });
});

and the controller action could look like this:

public ActionResult SomeAction(DateTime dateFrom, DateTime dateTo)
{
    ...
}


问:
Cannot remove files from powershell, but can from the GUI
I am trying to remove files I generated using powershell and del, but I get this message

```<code>del : Cannot remove item C:\Users\stefano.borini\<redacted>\.tox\py36\Include\fakepq.h: You do not have sufficient access rights to perform this operation.
At line:1 char:1
+ del .\.tox\

+ ~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (fakepq.h:FileInfo) [Remove-Item], IOException
    + FullyQualifiedErrorId : RemoveFileSystemItemUnAuthorizedAccess,Microsoft.PowerShell.Commands.RemoveItemCommand
del : Cannot remove item C:\Users\stefano.borini\<redacted>\.tox\py36\Include\fakesql.h: You do not have sufficient access rights to perform this operation.
</code>```

However, I can right click the items and delete them from the windows explorer without any problem. Why?

答:
Did you run Powershell as Administrator rights?

If so, you can try to add "-force" to your command.

Body:
I am trying to remove files I generated using powershell and del, but I get this message

del : Cannot remove item C:\Users\stefano.borini\<redacted>\.tox\py36\Include\fakepq.h: You do not have sufficient access rights to perform this operation.
At line:1 char:1
+ del .\.tox\

+ ~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (fakepq.h:FileInfo) [Remove-Item], IOException
    + FullyQualifiedErrorId : RemoveFileSystemItemUnAuthorizedAccess,Microsoft.PowerShell.Commands.RemoveItemCommand
del : Cannot remove item C:\Users\stefano.borini\<redacted>\.tox\py36\Include\fakesql.h: You do not have sufficient access rights to perform this operation.

However, I can right click the items and delete them from the windows explorer without any problem. Why?


问:
Select from a 3-dimensional array with a 2-dimensional array
I have two arrays:

a: a 3-dimensional source array (N x M x 2)

b: a 2-dimensional index array (N x M) containing 0 and 1s.

I want to use the indices in b to select the corresponding elements of a in its third dimension. The resulting array should have the dimensions N x M. Here is the example as code:

```<code>import numpy as np

a = np.array( # dims: 3x3x2
    [[[ 0,  1],
     [ 2,  3],
     [ 4,  5]],
    [[ 6,  7],
     [ 8,  9],
     [10, 11]],
    [[12, 13],
     [14, 15],
     [16, 17]]]
)
b = np.array( # dims: 3x3
    [[1, 1, 1],
    [1, 1, 1],
    [1, 1, 1]]
)

# select the elements in a according to b
# to achieve this result:
desired = np.array(
  [[ 1,  3,  5],
   [ 7,  9, 11],
   [13, 15, 17]]
)
</code>```

At first, I thought this must have a simple solution but I could not find one at all. Since I would like to port it to tensorflow, I would appreciate if somebody knows a numpy-type solution for this.

Edit: The third dimension of a might contain more than two elements. Hence, b might also contain indices different from 0 and 1 - it is not a boolean mask.

答:
I added some solutions for tensorflow.</p>

```<code>import tensorflow as tf

a = tf.constant([[[ 0,  1],[ 2,  3],[ 4,  5]],
                 [[ 6,  7],[ 8,  9],[10, 11]],
                 [[12, 13],[14, 15],[16, 17]]],dtype=tf.float32)
b = tf.constant([[1, 1, 1],[1, 1, 1],[1, 1, 1]],dtype=tf.int32)

# 1. use tf.gather_nd
colum,row = tf.meshgrid(tf.range(a.shape[0]),tf.range(a.shape[1]))
idx = tf.stack([row, colum, b], axis=-1) # Thanks for @jdehesa's suggestion
result1 = tf.gather_nd(a,idx)

# 2. use tf.reduce_sum
mask = tf.one_hot(b,depth=a.shape[-1],dtype=tf.float32)
result2 = tf.reduce_sum(a*mask,axis=-1)

# 3. use tf.boolean_mask
mask = tf.one_hot(b,depth=a.shape[-1],dtype=tf.float32)
result3 = tf.reshape(tf.boolean_mask(a,mask),b.shape)

with tf.Session() as sess:
    print('method 1: \n',sess.run(result1))
    print('method 2: \n',sess.run(result2))
    print('method 3: \n',sess.run(result3))

method 1:
 [[ 1.  3.  5.]
 [ 7.  9. 11.]
 [13. 15. 17.]]
method 2:
 [[ 1.  3.  5.]
 [ 7.  9. 11.]
 [13. 15. 17.]]
method 3:
 [[ 1.  3.  5.]
 [ 7.  9. 11.]
 [13. 15. 17.]]
</code>```

Body:
I have two arrays:

a: a 3-dimensional source array (N x M x 2)

b: a 2-dimensional index array (N x M) containing 0 and 1s.

I want to use the indices in b to select the corresponding elements of a in its third dimension. The resulting array should have the dimensions N x M. Here is the example as code:

import numpy as np

a = np.array( # dims: 3x3x2
    [[[ 0,  1],
     [ 2,  3],
     [ 4,  5]],
    [[ 6,  7],
     [ 8,  9],
     [10, 11]],
    [[12, 13],
     [14, 15],
     [16, 17]]]
)
b = np.array( # dims: 3x3
    [[1, 1, 1],
    [1, 1, 1],
    [1, 1, 1]]
)

# select the elements in a according to b
# to achieve this result:
desired = np.array(
  [[ 1,  3,  5],
   [ 7,  9, 11],
   [13, 15, 17]]
)

At first, I thought this must have a simple solution but I could not find one at all. Since I would like to port it to tensorflow, I would appreciate if somebody knows a numpy-type solution for this.

Edit: The third dimension of a might contain more than two elements. Hence, b might also contain indices different from 0 and 1 - it is not a boolean mask.

Body:
I added some solutions for tensorflow.

import tensorflow as tf

a = tf.constant([[[ 0,  1],[ 2,  3],[ 4,  5]],
                 [[ 6,  7],[ 8,  9],[10, 11]],
                 [[12, 13],[14, 15],[16, 17]]],dtype=tf.float32)
b = tf.constant([[1, 1, 1],[1, 1, 1],[1, 1, 1]],dtype=tf.int32)

# 1. use tf.gather_nd
colum,row = tf.meshgrid(tf.range(a.shape[0]),tf.range(a.shape[1]))
idx = tf.stack([row, colum, b], axis=-1) # Thanks for @jdehesa's suggestion
result1 = tf.gather_nd(a,idx)

# 2. use tf.reduce_sum
mask = tf.one_hot(b,depth=a.shape[-1],dtype=tf.float32)
result2 = tf.reduce_sum(a*mask,axis=-1)

# 3. use tf.boolean_mask
mask = tf.one_hot(b,depth=a.shape[-1],dtype=tf.float32)
result3 = tf.reshape(tf.boolean_mask(a,mask),b.shape)

with tf.Session() as sess:
    print('method 1: \n',sess.run(result1))
    print('method 2: \n',sess.run(result2))
    print('method 3: \n',sess.run(result3))

method 1:
 [[ 1.  3.  5.]
 [ 7.  9. 11.]
 [13. 15. 17.]]
method 2:
 [[ 1.  3.  5.]
 [ 7.  9. 11.]
 [13. 15. 17.]]
method 3:
 [[ 1.  3.  5.]
 [ 7.  9. 11.]
 [13. 15. 17.]]


问:
How to change hit point to crosshair?
Below script uses a function whereas there first is a check if there is a object in range and if it, it is.

On pressing mouse key, the projectile is shooting towards the pivot point of that said object. I want the projectile to

always being able to fire (indifferent if the object is in range) and

shoot towards the crosshair (to the screen midpoint) and NOT towards the object pivot point.

I am a novice at coding and I can't see what code to remove and what to add.

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

    public struct ShootHit
    {
    public GameObject gameObject;
    public Vector3 point;
    }

    [System.Serializable]
    public class UnityEventShootHit : UnityEvent<ShootHit> { }

    [DisallowMultipleComponent, AddComponentMenu("(つ♥v♥)つ/Useables/Shoot")]
    public class ShootComponent : MonoBehaviour
    {
    [Header("Input")]
    [Tooltip("Data that determines the input of player actions")]
    [SerializeField] private InputProfile _inputProfile;
    // [SerializeField] private float _range = 100.0f;

    /* [Header("Sight Values")]
     [Tooltip("How far the the sight can reach")]
     public float sightRadius = 1f;
     [Range(0f, 360f)]
     public float fieldOfViewAngle = 100f;*/

    [Header("Charge-up")]
    [SerializeField] private float _chargeupTime = 0.5f;
    private bool _isChargingPrimary = false;
    private bool _isChargingSecondary = false;

    [Header("Aim Assist")]
    [SerializeField] private LayerMask _aimAssistLayerMask;

    public float aimAssistRadius = 30.0f;  // radius
    [Range(0.0f, 360.0f)]
    public float aimAssistMaxAngleToAssist = 45.0f;  // angle

    private ShootHit? _target;

    //publics
    public Transform shootOrigin;

    [Header("Events")]
    public UnityEventShootHit OnPrimaryFire;
    public UnityEvent OnPrimaryFireStart;
    public UnityEvent OnPrimaryFireStop;

    public UnityEventShootHit OnSecondaryFire;
    public UnityEvent OnSecondaryFireStart;
    public UnityEvent OnSecondaryFireStop;

    private void Start()
    {
        if (_inputProfile == null) Debug.LogError(gameObject.name + " does not
        have a player input");
    }

     private void Update()
     {
         // Remove target if object is too far away
         if (_target.HasValue)
         {
            if (Vector3.Distance(_target.Value.gameObject.transform.position,
         transform.position) > aimAssistRadius)
            {
                _target = null;
            }
         }

         if (_inputProfile.GetPrimaryFireButtonDown())
         {
            StopCoroutine(ChargeUpBeforeFireSecondary());

            if (!_isChargingPrimary)
            {
                StartCoroutine(ChargeUpBeforeFirePrimary());
            }
         }

         else if (_inputProfile.GetSecondaryFireButtonDown())
         {
            StopCoroutine(ChargeUpBeforeFirePrimary());

            if (!_isChargingSecondary)
            {
                StartCoroutine(ChargeUpBeforeFireSecondary());
            }
        }

         if (_inputProfile.GetPrimaryFireButton() ||
        _inputProfile.GetSecondaryFireButton())
        {
            if (!_target.HasValue) _target = GetObjectClosestToAim();

            if (_inputProfile.GetPrimaryFireButton())
            {
                OnPrimaryFire.Invoke(_target.Value);
            }
            if (_inputProfile.GetSecondaryFireButton())
            {
                OnSecondaryFire.Invoke(_target.Value);
            }

        }
        else
        {
            _target = null;
        }

        if (_inputProfile.GetPrimaryFireButtonUp())
            OnPrimaryFireStop.Invoke();
        if (_inputProfile.GetSecondaryFireButtonUp())
            OnSecondaryFireStop.Invoke();
    }

    /// <summary>
    /// Finds the object within range closest to the players forward-vector
    using _aimAssistLayerMask.
    /// </summary>
    /// <returns>Returns object closest to aim if any object is found, else
    returns null.</returns>
    ShootHit? GetObjectClosestToAim()
    {
        // Raycast
        RaycastHit hit;
        if (Physics.Raycast(shootOrigin.position, Camera.main.transform.forward,
        out hit, aimAssistRadius, _aimAssistLayerMask))
        {
            if (hit.transform?.GetComponent<IShootTarget>() != null)
            {
                Debug.Log(hit.transform.name);

                return new ShootHit { gameObject = hit.transform.gameObject,
    point = hit.point };
            }
        }

        float _closestDot = -2f;
        GameObject _closestDotObject = null;
        RaycastHit[] _hit = Physics.SphereCastAll(transform.position,
        aimAssistRadius, transform.forward, 0, _aimAssistLayerMask,
        QueryTriggerInteraction.Ignore);

        // Get best dot from all objects within range
        for (int i = 0; i < _hit.Length; i++)
        {
            if (_hit[i].transform.gameObject == this.gameObject ||
        _hit[i].transform.GetComponent<IShootTarget>() == null)
                continue;

            Vector3 _dif = _hit[i].transform.position - transform.position;

            float _newDot = Vector3.Dot(transform.forward.normalized,
      _dif.normalized);
            if (_newDot > _closestDot)
            {
                _closestDot = _newDot;
                _closestDotObject = _hit[i].transform.gameObject;
            }
        }
        if (!_closestDotObject)
            return null;

        // Make sure there are no object in the way of our best-dot-object
        Collider[] colliders = _closestDotObject.GetComponents<Collider>();
        Vector3 point = colliders[0].ClosestPoint(shootOrigin.position);
        float distanceToPoint = Vector3.Distance(shootOrigin.position, point);
        // Get closest collider
        for (int i = 1; i < colliders.Length; i++)
        {
            Vector3 newPoint = colliders[i].ClosestPoint(shootOrigin.position);
            float newDistanceToPoint = Vector3.Distance(shootOrigin.position,
        newPoint);
            if (distanceToPoint > newDistanceToPoint)
            {
                point = newPoint;
                distanceToPoint = newDistanceToPoint;
            }
        }
        RaycastHit _rayhit;
        if (Physics.Raycast(shootOrigin.position, point - transform.position,
        out _rayhit, aimAssistRadius, _aimAssistLayerMask))
        {
            if (_rayhit.transform.gameObject != _closestDotObject)
            {
                return null;
            }
        }

        Vector3 _vecToClosest = _closestDotObject.transform.position -
    transform.position;
        if (Vector3.Angle(transform.forward, _vecToClosest) <=
    aimAssistMaxAngleToAssist)
         {
            return new ShootHit { gameObject = _closestDotObject, point = point
 };
        }
        else
        {
            return null;
        }
    }

     IEnumerator ChargeUpBeforeFirePrimary()
    {
        _isChargingPrimary = true;
        yield return new WaitForSeconds(_chargeupTime);
        _isChargingPrimary = false;
        OnPrimaryFireStart.Invoke();
    }

    IEnumerator ChargeUpBeforeFireSecondary()
    {
        _isChargingSecondary = true;
        yield return new WaitForSeconds(_chargeupTime);
        _isChargingSecondary = false;
        OnSecondaryFireStart.Invoke();
    }

    #if UNITY_EDITOR
    private void OnDrawGizmosSelected()
    {
        if (!Application.isPlaying) return;

        Color oldColor = Gizmos.color;

        float halfFeildOfView = aimAssistMaxAngleToAssist * 0.5f;
        float coneDirection = -90f;

        Quaternion leftRayRotation = Quaternion.AngleAxis(-halfFeildOfView + coneDirection, Vector3.up);
        Quaternion rightRayRotation = Quaternion.AngleAxis(halfFeildOfView + coneDirection, Vector3.up);

        Vector3 leftRayDirection = leftRayRotation * transform.right * aimAssistRadius;
        Vector3 rightRayDirection = rightRayRotation * transform.right * aimAssistRadius;

        // Green Arc
        Handles.color = new Color(0f, 1f, 0f, 0.25f);
        Handles.DrawSolidArc(transform.position, Vector3.up, leftRayDirection, aimAssistMaxAngleToAssist, aimAssistRadius);

        Gizmos.color = oldColor;

    }
     #endif

}
`
</code>```

This is the code attached to the projectile

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

[RequireComponent(typeof(Rigidbody))]
public class ProjectileScript : MonoBehaviour
{

    public GameObject Explosion;

    public Transform Target;

    Rigidbody _rigidbody;

    public float speed = 1.0f;

    void Start()
    {
        _rigidbody = GetComponent<Rigidbody>();

    }

    void FixedUpdate()
    {
        // _rigidbody.AddForce((Target.position - transform.position).normalized, ForceMode.Impulse);
        Collider targetCollider = Target.GetComponent<Collider>();
        Vector3 targetDirection;
        if (targetCollider)
            targetDirection = targetCollider.ClosestPoint(transform.position) - transform.position;
        else
            targetDirection = Target.position - transform.position;

        _rigidbody.velocity = targetDirection.normalized * speed;
        if (Vector3.Distance(transform.position, Target.position) < 1.0f)
        {
            //make the explosion
            GameObject ThisExplosion = Instantiate(Explosion, gameObject.transform.position, gameObject.transform.rotation) as GameObject;

            //destory the projectile
            Destroy(gameObject);
        }
    }

    public void SetTarget(GameObject target)
    {
        this.Target = target.transform;
    }

    public void SetTarget(ShootHit hit) => SetTarget(hit.gameObject);

}
</code>```

This script is how and where the Projectile Spawns. It is attached to an empty gameobject located on the muzzle of the gun.

```<code>public class ProjectileSpawner : MonoBehaviour
{

    public GameObject projectileInsert;

        public GameObject projectileExtract;
        public float projectileSpeed = 1.0f;

        GameObject projectile;

        public void Insert(GameObject target)
        {
            if (projectile) return;

            projectile = Instantiate(projectileInsert, transform.position, Quaternion.identity);
            ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
            projectileScript.SetTarget(target);
            projectileScript.speed = projectileSpeed;

            // Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
            // projectileSpawn.parent.GetComponent<Collider>());

        }

        public void Extract(GameObject target)
        {
            if (projectile) return;

            projectile = Instantiate(projectileExtract, target.transform.position, Quaternion.identity);
            ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
            projectileScript.SetTarget(gameObject);
            projectileScript.speed = projectileSpeed;

            // Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
            // projectileSpawn.parent.GetComponent<Collider>());

        }

    }
</code>```

答:
Your question is a bit vague and doesn't look like you have put a lot of effort into understanding the code and trying to alterate it. Anyway I'll do my best.

always being able to fire (indifferent if the object is in range)`

probably simply set aimAssistRadius = 0; or entirely remove the check

```<code>if (Vector3.Distance(_target.Value.gameObject.transform.position, transform.position) > aimAssistRadius)
{
    _target = null;
}
</code>```

shoot towards the crosshair (to the screen midpoint) and NOT towards the object pivot point.

The script you posted (probably not yours) seems to have the entire purpose of doing what you not want to do: Aim assist. Removing it probably changes a lot of things but the simpliest would be to simply set the ProjectileScript._rigidbody.velocity in the moment the projectile is instantiated. Unfortunately you didn't provide the code where this happens.

I don't see in which moment your ShootComponent interacts with the ProjectileScript but probably in one of those UnityEvents ... ?

But in general it would maybe simply look like

```<code>public class ProjectileScript : MonoBehaviour
{
     public float speed = 1.0f;

    private RigidBody _rigidbody;

    private void Awake()
    {
        _rigidbody = GetComponent<RigidBody>();
    }

    public void SetDirection(Vector3 direction)
    {
        _rigidbody.velocity = direction.normalized * speed;
    }
}
</code>```

and whereever you Instantiate the projectile do

```<code>var projectile = instantiatedObject.GetComponent<ProjectileScript>();
var direction = Camera.main.transform.forward;
projectile.SetDirection(direction);
</code>```

as you can see you will have to make the

```<code>if (Vector3.Distance(transform.position, Target.position) < 1.0f)
{
    //make the explosion
    GameObject ThisExplosion = Instantiate(Explosion, gameObject.transform.position, gameObject.transform.rotation) as GameObject;

    //destory the projectile
    Destroy(gameObject);
}
</code>```

happen somewhere else since the code will not be target based anymore ... I would probably use OnCollisionEnter instead something like e.g.

```<code>private void OnCollisionEnter(Collision collision)
{
    // maybe only collide with a certain tag
    if(collision.gameObject.tag != "Target") return;

    //make the explosion
    GameObject ThisExplosion = Instantiate(Explosion, gameObject.transform.position, gameObject.transform.rotation) as GameObject;

    //destory the projectile
    Destroy(gameObject);
}
</code>```

Title: How to change hit point to crosshair?

Body:
Below script uses a function whereas there first is a check if there is a object in range and if it, it is.

On pressing mouse key, the projectile is shooting towards the pivot point of that said object. I want the projectile to

always being able to fire (indifferent if the object is in range) and

shoot towards the crosshair (to the screen midpoint) and NOT towards the object pivot point.

I am a novice at coding and I can't see what code to remove and what to add.

    using System.Collections;
    using System.Collections.Generic;
    using UnityEditor;
    using UnityEngine;
    using UnityEngine.Events;

    public struct ShootHit
    {
    public GameObject gameObject;
    public Vector3 point;
    }

    [System.Serializable]
    public class UnityEventShootHit : UnityEvent<ShootHit> { }

    [DisallowMultipleComponent, AddComponentMenu("(つ♥v♥)つ/Useables/Shoot")]
    public class ShootComponent : MonoBehaviour
    {
    [Header("Input")]
    [Tooltip("Data that determines the input of player actions")]
    [SerializeField] private InputProfile _inputProfile;
    // [SerializeField] private float _range = 100.0f;

    /* [Header("Sight Values")]
     [Tooltip("How far the the sight can reach")]
     public float sightRadius = 1f;
     [Range(0f, 360f)]
     public float fieldOfViewAngle = 100f;*/

    [Header("Charge-up")]
    [SerializeField] private float _chargeupTime = 0.5f;
    private bool _isChargingPrimary = false;
    private bool _isChargingSecondary = false;

    [Header("Aim Assist")]
    [SerializeField] private LayerMask _aimAssistLayerMask;

    public float aimAssistRadius = 30.0f;  // radius
    [Range(0.0f, 360.0f)]
    public float aimAssistMaxAngleToAssist = 45.0f;  // angle

    private ShootHit? _target;

    //publics
    public Transform shootOrigin;

    [Header("Events")]
    public UnityEventShootHit OnPrimaryFire;
    public UnityEvent OnPrimaryFireStart;
    public UnityEvent OnPrimaryFireStop;

    public UnityEventShootHit OnSecondaryFire;
    public UnityEvent OnSecondaryFireStart;
    public UnityEvent OnSecondaryFireStop;

    private void Start()
    {
        if (_inputProfile == null) Debug.LogError(gameObject.name + " does not
        have a player input");
    }

     private void Update()
     {
         // Remove target if object is too far away
         if (_target.HasValue)
         {
            if (Vector3.Distance(_target.Value.gameObject.transform.position,
         transform.position) > aimAssistRadius)
            {
                _target = null;
            }
         }

         if (_inputProfile.GetPrimaryFireButtonDown())
         {
            StopCoroutine(ChargeUpBeforeFireSecondary());

            if (!_isChargingPrimary)
            {
                StartCoroutine(ChargeUpBeforeFirePrimary());
            }
         }

         else if (_inputProfile.GetSecondaryFireButtonDown())
         {
            StopCoroutine(ChargeUpBeforeFirePrimary());

            if (!_isChargingSecondary)
            {
                StartCoroutine(ChargeUpBeforeFireSecondary());
            }
        }

         if (_inputProfile.GetPrimaryFireButton() ||
        _inputProfile.GetSecondaryFireButton())
        {
            if (!_target.HasValue) _target = GetObjectClosestToAim();

            if (_inputProfile.GetPrimaryFireButton())
            {
                OnPrimaryFire.Invoke(_target.Value);
            }
            if (_inputProfile.GetSecondaryFireButton())
            {
                OnSecondaryFire.Invoke(_target.Value);
            }

        }
        else
        {
            _target = null;
        }

        if (_inputProfile.GetPrimaryFireButtonUp())
            OnPrimaryFireStop.Invoke();
        if (_inputProfile.GetSecondaryFireButtonUp())
            OnSecondaryFireStop.Invoke();
    }

    ///
    /// Finds the object within range closest to the players forward-vector
    using _aimAssistLayerMask.
    ///
    /// <returns>Returns object closest to aim if any object is found, else
    returns null.</returns>
    ShootHit? GetObjectClosestToAim()
    {
        // Raycast
        RaycastHit hit;
        if (Physics.Raycast(shootOrigin.position, Camera.main.transform.forward,
        out hit, aimAssistRadius, _aimAssistLayerMask))
        {
            if (hit.transform?.GetComponent<IShootTarget>() != null)
            {
                Debug.Log(hit.transform.name);

                return new ShootHit { gameObject = hit.transform.gameObject,
    point = hit.point };
            }
        }

        float _closestDot = -2f;
        GameObject _closestDotObject = null;
        RaycastHit[] _hit = Physics.SphereCastAll(transform.position,
        aimAssistRadius, transform.forward, 0, _aimAssistLayerMask,
        QueryTriggerInteraction.Ignore);

        // Get best dot from all objects within range
        for (int i = 0; i < _hit.Length; i++)
        {
            if (_hit[i].transform.gameObject == this.gameObject ||
        _hit[i].transform.GetComponent<IShootTarget>() == null)
                continue;

            Vector3 _dif = _hit[i].transform.position - transform.position;

            float _newDot = Vector3.Dot(transform.forward.normalized,
      _dif.normalized);
            if (_newDot > _closestDot)
            {
                _closestDot = _newDot;
                _closestDotObject = _hit[i].transform.gameObject;
            }
        }
        if (!_closestDotObject)
            return null;

        // Make sure there are no object in the way of our best-dot-object
        Collider[] colliders = _closestDotObject.GetComponents<Collider>();
        Vector3 point = colliders[0].ClosestPoint(shootOrigin.position);
        float distanceToPoint = Vector3.Distance(shootOrigin.position, point);
        // Get closest collider
        for (int i = 1; i < colliders.Length; i++)
        {
            Vector3 newPoint = colliders[i].ClosestPoint(shootOrigin.position);
            float newDistanceToPoint = Vector3.Distance(shootOrigin.position,
        newPoint);
            if (distanceToPoint > newDistanceToPoint)
            {
                point = newPoint;
                distanceToPoint = newDistanceToPoint;
            }
        }
        RaycastHit _rayhit;
        if (Physics.Raycast(shootOrigin.position, point - transform.position,
        out _rayhit, aimAssistRadius, _aimAssistLayerMask))
        {
            if (_rayhit.transform.gameObject != _closestDotObject)
            {
                return null;
            }
        }

        Vector3 _vecToClosest = _closestDotObject.transform.position -
    transform.position;
        if (Vector3.Angle(transform.forward, _vecToClosest) <=
    aimAssistMaxAngleToAssist)
         {
            return new ShootHit { gameObject = _closestDotObject, point = point
 };
        }
        else
        {
            return null;
        }
    }

     IEnumerator ChargeUpBeforeFirePrimary()
    {
        _isChargingPrimary = true;
        yield return new WaitForSeconds(_chargeupTime);
        _isChargingPrimary = false;
        OnPrimaryFireStart.Invoke();
    }

    IEnumerator ChargeUpBeforeFireSecondary()
    {
        _isChargingSecondary = true;
        yield return new WaitForSeconds(_chargeupTime);
        _isChargingSecondary = false;
        OnSecondaryFireStart.Invoke();
    }

    #if UNITY_EDITOR
    private void OnDrawGizmosSelected()
    {
        if (!Application.isPlaying) return;

        Color oldColor = Gizmos.color;

        float halfFeildOfView = aimAssistMaxAngleToAssist * 0.5f;
        float coneDirection = -90f;

        Quaternion leftRayRotation = Quaternion.AngleAxis(-halfFeildOfView + coneDirection, Vector3.up);
        Quaternion rightRayRotation = Quaternion.AngleAxis(halfFeildOfView + coneDirection, Vector3.up);

        Vector3 leftRayDirection = leftRayRotation * transform.right * aimAssistRadius;
        Vector3 rightRayDirection = rightRayRotation * transform.right * aimAssistRadius;

        // Green Arc
        Handles.color = new Color(0f, 1f, 0f, 0.25f);
        Handles.DrawSolidArc(transform.position, Vector3.up, leftRayDirection, aimAssistMaxAngleToAssist, aimAssistRadius);

        Gizmos.color = oldColor;

    }
     #endif

}
`

This is the code attached to the projectile

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody))]
public class ProjectileScript : MonoBehaviour
{

    public GameObject Explosion;

    public Transform Target;

    Rigidbody _rigidbody;

    public float speed = 1.0f;

    void Start()
    {
        _rigidbody = GetComponent<Rigidbody>();

    }

    void FixedUpdate()
    {
        // _rigidbody.AddForce((Target.position - transform.position).normalized, ForceMode.Impulse);
        Collider targetCollider = Target.GetComponent<Collider>();
        Vector3 targetDirection;
        if (targetCollider)
            targetDirection = targetCollider.ClosestPoint(transform.position) - transform.position;
        else
            targetDirection = Target.position - transform.position;

        _rigidbody.velocity = targetDirection.normalized * speed;
        if (Vector3.Distance(transform.position, Target.position) < 1.0f)
        {
            //make the explosion
            GameObject ThisExplosion = Instantiate(Explosion, gameObject.transform.position, gameObject.transform.rotation) as GameObject;

            //destory the projectile
            Destroy(gameObject);
        }
    }

    public void SetTarget(GameObject target)
    {
        this.Target = target.transform;
    }

    public void SetTarget(ShootHit hit) => SetTarget(hit.gameObject);

}

This script is how and where the Projectile Spawns. It is attached to an empty gameobject located on the muzzle of the gun.

public class ProjectileSpawner : MonoBehaviour
{

    public GameObject projectileInsert;

        public GameObject projectileExtract;
        public float projectileSpeed = 1.0f;

        GameObject projectile;

        public void Insert(GameObject target)
        {
            if (projectile) return;

            projectile = Instantiate(projectileInsert, transform.position, Quaternion.identity);
            ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
            projectileScript.SetTarget(target);
            projectileScript.speed = projectileSpeed;

            // Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
            // projectileSpawn.parent.GetComponent<Collider>());

        }

        public void Extract(GameObject target)
        {
            if (projectile) return;

            projectile = Instantiate(projectileExtract, target.transform.position, Quaternion.identity);
            ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
            projectileScript.SetTarget(gameObject);
            projectileScript.speed = projectileSpeed;

            // Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
            // projectileSpawn.parent.GetComponent<Collider>());

        }

    }

Body:
Your question is a bit vague and doesn't look like you have put a lot of effort into understanding the code and trying to alterate it. Anyway I'll do my best.

always being able to fire (indifferent if the object is in range)`

probably simply set aimAssistRadius = 0; or entirely remove the check

if (Vector3.Distance(_target.Value.gameObject.transform.position, transform.position) > aimAssistRadius)
{
    _target = null;
}

shoot towards the crosshair (to the screen midpoint) and NOT towards the object pivot point.

The script you posted (probably not yours) seems to have the entire purpose of doing what you not want to do: Aim assist. Removing it probably changes a lot of things but the simpliest would be to simply set the ProjectileScript._rigidbody.velocity in the moment the projectile is instantiated. Unfortunately you didn't provide the code where this happens.

I don't see in which moment your ShootComponent interacts with the ProjectileScript but probably in one of those UnityEvents ... ?

But in general it would maybe simply look like

public class ProjectileScript : MonoBehaviour
{
     public float speed = 1.0f;

    private RigidBody _rigidbody;

    private void Awake()
    {
        _rigidbody = GetComponent<RigidBody>();
    }

    public void SetDirection(Vector3 direction)
    {
        _rigidbody.velocity = direction.normalized * speed;
    }
}

and whereever you Instantiate the projectile do

var projectile = instantiatedObject.GetComponent<ProjectileScript>();
var direction = Camera.main.transform.forward;
projectile.SetDirection(direction);

as you can see you will have to make the

if (Vector3.Distance(transform.position, Target.position) < 1.0f)
{
    //make the explosion
    GameObject ThisExplosion = Instantiate(Explosion, gameObject.transform.position, gameObject.transform.rotation) as GameObject;

    //destory the projectile
    Destroy(gameObject);
}

happen somewhere else since the code will not be target based anymore ... I would probably use OnCollisionEnter instead something like e.g.

private void OnCollisionEnter(Collision collision)
{
    // maybe only collide with a certain tag
    if(collision.gameObject.tag != "Target") return;

    //make the explosion
    GameObject ThisExplosion = Instantiate(Explosion, gameObject.transform.position, gameObject.transform.rotation) as GameObject;

    //destory the projectile
    Destroy(gameObject);
}


问:
Convert array of Strings to Array list
I have a String array with name and id, I need to convert that String array to List of objects.

This is my code:

```<code>private List<ObjectAttribute> getDtls(String newVal) {
    ObjectAttribute object = new ObjectAttribute();
    List<ObjectAttribute> objLst = new ArrayList<ObjectAttribute>();
    String[] newImageVal = [step0005.jpg, 172B6846-0073-4E5B-B10A-DDD928994EA6, step0003.jpg, FBC8D143-2CD7-47E6-B323-31A0928A9338]
    for (int i = 0; i <= newImageVal.length - 1; i++) {
        object.setImageName(newImageVal[i]);
        object.setImageId(newImageVal[++i]);
        objLst.add(object);
    }
    return objLst;
}
</code>```

but there is a problem that it always returns only the last value in objList. Can anyone correct this code.

答:
The root cause of your problem is, as @StefanBeike wrote, that you instantiate the object only once before the for-loop and then you just keep rewriting its attributes. Moving the instantiation (= calling of new) inside the for-loop fixes the functionality.

However, apart from this, it is a very bad practice to increment the for-loop variable inside the for-loop body. Thus you obscure your intention and you will get a code which is less readable, harder maintainable and easier to break by later changes.

And the main condition should be i < newImageVal.length-1 to handle the array size safely. (To be 100% sure you do not get ArrayIndexOutOfBoundsException.)

There are multiple better ways.

Increment by 2 in the for-loop "header":

```<code>for (int i = 0; i < newImageVal.length-1; i += 2) {
    ObjectAttribute object = new ObjectAttribute();
    object.setImageName(newImageVal[i]);
    object.setImageId(newImageVal[i+1]);
    objLst.add(object);
}
</code>```

Use while-loop instead of for-loop:

```<code>int i = 0;
while (i < newImageVal.length-1) {
    ObjectAttribute object = new ObjectAttribute();
    object.setImageName(newImageVal[i++]);
    object.setImageId(newImageVal[i++]);
    objLst.add(object);
}
</code>```

Title: Convert array of Strings to Array list

Body:
I have a String array with name and id, I need to convert that String array to List of objects.

This is my code:

private List<ObjectAttribute> getDtls(String newVal) {
    ObjectAttribute object = new ObjectAttribute();
    List<ObjectAttribute> objLst = new ArrayList<ObjectAttribute>();
    String[] newImageVal = [step0005.jpg, 172B6846-0073-4E5B-B10A-DDD928994EA6, step0003.jpg, FBC8D143-2CD7-47E6-B323-31A0928A9338]
    for (int i = 0; i <= newImageVal.length - 1; i++) {
        object.setImageName(newImageVal[i]);
        object.setImageId(newImageVal[++i]);
        objLst.add(object);
    }
    return objLst;
}

but there is a problem that it always returns only the last value in objList. Can anyone correct this code.

Body:
The root cause of your problem is, as @StefanBeike wrote, that you instantiate the object only once before the for-loop and then you just keep rewriting its attributes. Moving the instantiation (= calling of new) inside the for-loop fixes the functionality.

However, apart from this, it is a very bad practice to increment the for-loop variable inside the for-loop body. Thus you obscure your intention and you will get a code which is less readable, harder maintainable and easier to break by later changes.

And the main condition should be i < newImageVal.length-1 to handle the array size safely. (To be 100% sure you do not get ArrayIndexOutOfBoundsException.)

There are multiple better ways.

Increment by 2 in the for-loop "header":

for (int i = 0; i < newImageVal.length-1; i += 2) {
    ObjectAttribute object = new ObjectAttribute();
    object.setImageName(newImageVal[i]);
    object.setImageId(newImageVal[i+1]);
    objLst.add(object);
}

Use while-loop instead of for-loop:

int i = 0;
while (i < newImageVal.length-1) {
    ObjectAttribute object = new ObjectAttribute();
    object.setImageName(newImageVal[i++]);
    object.setImageId(newImageVal[i++]);
    objLst.add(object);
}


问:
Android Install failed insufficient storage when running Mobile-UXSDK-Android
Trying to run this example on API 28 Tablet emulator when got this error, Install_failed_insufficient_storage, on my AndroidStudio.
I did not change code or gardle script (Just unmarked the exclude module: 'library-anti-distortion' line in order to reduce apk size).</p>

答:
There are a few ways to free some space from internal storage:

1) Uninstall unneeded applications.

2) Remove unneeded files via adb:

```<code>adb shell
$ cd /data/local/tmp && ls -la && rm -rf *
</code>```

You can remove files from that directory without root access.

Where to find adb executable: https://android.stackexchange.com/a/94049

3) Do a factory reset (make sure you understand what it means before doing it).

Body:
There are a few ways to free some space from internal storage:

1) Uninstall unneeded applications.

2) Remove unneeded files via adb:

adb shell
$ cd /data/local/tmp && ls -la && rm -rf *

You can remove files from that directory without root access.

Where to find adb executable: https://android.stackexchange.com/a/94049

3) Do a factory reset (make sure you understand what it means before doing it).


问:
How to switch TextView between values every 5 seconds
I don't know if using Threads is the practice for what I am trying to achieve so please feel free to amend the code where you wish.

I am trying to implement a feature in my app where a TextView switches to 1 value and thereafter reverts back to the initial value every 5 seconds. I have implemented the following using on a thread:

```<code>    layoutDate.setText(firstNumber);

    Thread numberSwitch = new Thread() {
    @Override
    public void run() {
        while(!isInterrupted()) {
            try {

                Thread.sleep(5000);

                runOnUiThread(new Runnable () {
                    @Override
                    public void run() {

                        layoutDate.setText(secondNumber);

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

numberSwitch.start();
</code>```

I have tried adding layoutDate.setText(firstNumber) just after the runUiOnThread and also after the nested run but it still doesn't work as I want it to.

I want to achieve something like the following:

答:
Verify the current number that is in the field and change to the other, you can do this through getting the value layoutDate.getText().toString() or using a new variable to store the value.

```<code>layoutDate.setText(firstNumber);

    Thread numberSwitch = new Thread() {
    @Override
    public void run() {
        while(!isInterrupted()) {
            try {

                Thread.sleep(5000);

                runOnUiThread(new Runnable () {
                    @Override
                    public void run() {

                        if(currentNumber == firstNumber){
                            currentNumber = secondNumber;
                        }else{
                            currentNumber = firstNumber;
                        }
                        layoutDate.setText(currentNumber);
                    }
                });
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
};

numberSwitch.start();
</code>```

Or

```<code>if(layoutDate.getText().toString().equals(firstNumber+"")){
    layoutDate.set(secondNumber);
}else{
    layoutDate.set(firstNumber);
}
</code>```

Body:
I don't know if using Threads is the practice for what I am trying to achieve so please feel free to amend the code where you wish.

I am trying to implement a feature in my app where a TextView switches to 1 value and thereafter reverts back to the initial value every 5 seconds. I have implemented the following using on a thread:

    layoutDate.setText(firstNumber);

    Thread numberSwitch = new Thread() {
    @Override
    public void run() {
        while(!isInterrupted()) {
            try {

                Thread.sleep(5000);

                runOnUiThread(new Runnable () {
                    @Override
                    public void run() {

                        layoutDate.setText(secondNumber);

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

numberSwitch.start();

I have tried adding layoutDate.setText(firstNumber) just after the runUiOnThread and also after the nested run but it still doesn't work as I want it to.

I want to achieve something like the following:

Body:
Verify the current number that is in the field and change to the other, you can do this through getting the value layoutDate.getText().toString() or using a new variable to store the value.

layoutDate.setText(firstNumber);

    Thread numberSwitch = new Thread() {
    @Override
    public void run() {
        while(!isInterrupted()) {
            try {

                Thread.sleep(5000);

                runOnUiThread(new Runnable () {
                    @Override
                    public void run() {

                        if(currentNumber == firstNumber){
                            currentNumber = secondNumber;
                        }else{
                            currentNumber = firstNumber;
                        }
                        layoutDate.setText(currentNumber);
                    }
                });
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
};

numberSwitch.start();

Or

if(layoutDate.getText().toString().equals(firstNumber+"")){
    layoutDate.set(secondNumber);
}else{
    layoutDate.set(firstNumber);
}


问:
How to get ID's of the records in Cross-reference field using Web API in RSA Archer?
I need to get the ID's of the records in a cross-reference field using Web API. Is there an API method to solve this type of task? Or at least I want to know, how to get the value of a specific field?

There are many different methods described in the documentation for operating with list fields (such as GetValuesListValue) and I wonder if there a same way to solve my task.
I can use ExecuteSeach method, but it isn't very convenient.

答:
Alexander, you can either use the REST or Webservices APIs.

REST APIs

Using the Get content by id, /api/core/content/*contentid*
Then you can pass OData to just get the field (id) contents by passing the following in the body
{"Value":"?$filter=FieldId eq '*field id of cross-reference field*'"}

Webservices APIs

You can call the /ws/record.asmx GetRecordById passing the following

```<code><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetRecordById xmlns="http://archer-tech.com/webservices/">
      <sessionToken>session token</sessionToken>
      <moduleId>int</moduleId>
      <contentId>int</contentId>
    </GetRecordById>
  </soap:Body>
</soap:Envelope>
</code>```

Then you'd have to iterate through the returned XML to get the field contents.

Body:
Alexander, you can either use the REST or Webservices APIs.

REST APIs

Using the Get content by id, /api/core/content/*contentid*
Then you can pass OData to just get the field (id) contents by passing the following in the body
{"Value":"?$filter=FieldId eq '*field id of cross-reference field*'"}

Webservices APIs

You can call the /ws/record.asmx GetRecordById passing the following

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetRecordById xmlns="http://archer-tech.com/webservices/">
      <sessionToken>session token</sessionToken>
      <moduleId>int</moduleId>
      <contentId>int</contentId>
    </GetRecordById>
  </soap:Body>
</soap:Envelope>

Then you'd have to iterate through the returned XML to get the field contents.


问:
Has Soundex been improved?
Soundex seems to be implemented in some DBMS's, but have there been any algorithmic improvements that are definitively better than the current implementation of Soundex?</p>

答: I don't know about "definitively better", but you might want to look at Metaphone (and its variants) and Caverphone. See, e.g., http://www.atomodo.com/code/double-metaphone where there's an implementation of "Double Metaphone" for use with MYSQL.</p>

Title: Has Soundex been improved?


问:
GuzzleHttp\Client JSON Return as String
I have very simple question, how to convert this strings to JSON ?

This string i am getting from Guzzle POST Request and here is code :

```<code>return $body->getBody()->getContents();
</code>```

Result:

```<code>""k\n\n{\"success\":true,\"payload\":{\"id\":\"txn_ngS2aS9FY7raxy8JTUivAZCtWJy7EeznwPE8\"}}""
</code>```

with var_dump result and what is that k before ?

```<code>string(79) "k {"success":true,"payload":{"id":"txn_eeM6T6Fvkq3Pr4AWtK2TKYmNwKmodNwVqJod"}}"
</code>```

答: The string is already json_encoded, you should simply return the $body->getBody()->getContents().

Title: GuzzleHttp\Client JSON Return as String

Body:
I have very simple question, how to convert this strings to JSON ?

This string i am getting from Guzzle POST Request and here is code :

return $body->getBody()->getContents();

Result:

""k\n\n{\"success\":true,\"payload\":{\"id\":\"txn_ngS2aS9FY7raxy8JTUivAZCtWJy7EeznwPE8\"}}""

with var_dump result and what is that k before ?

string(79) "k {"success":true,"payload":{"id":"txn_eeM6T6Fvkq3Pr4AWtK2TKYmNwKmodNwVqJod"}}"


问:
Query array using whereHas
I want to filter products by category (manyToMany relationship). Basically the user select which categories to show. The categories I want to filter are in $request->keywords. This is what I tried:

```<code>  $products = Product::all();
  foreach($request->keywords as $keyword) {
    $products = Product::whereHas('categories', function($q) use ($keyword){
      $q->where('title', '=', $keyword);
    })->get();
  }

  return response()->json($products);
</code>```

The problem is that this does not get all the categories, only the products with the last category in the array. I guess at this point: $q->where('title', '=', $keyword);, $q does not keep the results of the last loop iteration but always deletes the last loop results.
I also tried the same thing with $q->orWhere('title', '=', $keyword);, but that actually doesn't give me any results.

Thanks for your help!

答:
Changed your approach to fetch the data,</p>

```<code>$products = Product::all();
if (!empty($request->keywords)) { // if keywords not empty
    $keyword  = $request->keywords;
    $products = Product::whereHas('categories', function ($q) use ($keyword) {
        $q->whereIn('title', $keyword); // where in for array
    })->get(); // it won't override old data as there is no loop
}

return response()->json($products);
</code>```

Title: Query array using whereHas

Body:
I want to filter products by category (manyToMany relationship). Basically the user select which categories to show. The categories I want to filter are in $request->keywords. This is what I tried:

  $products = Product::all();
  foreach($request->keywords as $keyword) {
    $products = Product::whereHas('categories', function($q) use ($keyword){
      $q->where('title', '=', $keyword);
    })->get();
  }

  return response()->json($products);

The problem is that this does not get all the categories, only the products with the last category in the array. I guess at this point: $q->where('title', '=', $keyword);, $q does not keep the results of the last loop iteration but always deletes the last loop results.
I also tried the same thing with $q->orWhere('title', '=', $keyword);, but that actually doesn't give me any results.

Thanks for your help!

Body:
Changed your approach to fetch the data,

$products = Product::all();
if (!empty($request->keywords)) { // if keywords not empty
    $keyword  = $request->keywords;
    $products = Product::whereHas('categories', function ($q) use ($keyword) {
        $q->whereIn('title', $keyword); // where in for array
    })->get(); // it won't override old data as there is no loop
}

return response()->json($products);


问:
Is it possible to use CMD + CLICK Element A + CLICK Element B
I cannot use the Katalon recorder to click on the Element with CMD Key. Is it possible to click on two different items while the CMD key is pressed?

I tried to do that with sendKeys, controlKeyDown, keyDown Commands and then call Click Command on first element and then call Click Command on second element. But nothing happens.

Also, if we can simulate with CLICK Element A then CMD + CLICK Element B it can be ok for me.

答:
In Katalon Studio (not the recorder) switch to script mode:

Now you can write scripts in Groovy!

Next, try using Actions class, like this:

```<code>WebUI.openBrowser("url of the page you are testing")

WebDriver driver = DriverFactory.getWebDriver()

WebElement targetA = driver.findElement(By.cssSelector("element-a-selector"))
WebElement targetB = driver.findElement(By.cssSelector("element-b-selector"))

targetA.click()
Actions actions = new Actions(driver)

actions.keyDown(Keys.CONTROL).click(targetB).keyUp(Keys.CONTROL).perform()
</code>```

Note that this is your second scenario, first clicking element A (you will need to add the CSS selector or any other way of identifying it) and then holding CTRL and clicking element B.

The first one (press CTRL, click element a, click element b, release CTRL) is similar, just change the last line to:

```<code>actions.keyDown(Keys.CONTROL).click(targetA).click(targetB).keyUp(Keys.CONTROL).perform()
</code>```

and remove targetA.click().

You will need to import the following Selenium helper classes:

```<code>import org.openqa.selenium.By
import org.openqa.selenium.Keys
import org.openqa.selenium.WebDriver
import org.openqa.selenium.WebElement as WebElement
import org.openqa.selenium.interactions.Actions
</code>```

Body:
In Katalon Studio (not the recorder) switch to script mode:

Now you can write scripts in Groovy!

Next, try using Actions class, like this:

WebUI.openBrowser("url of the page you are testing")

WebDriver driver = DriverFactory.getWebDriver()

WebElement targetA = driver.findElement(By.cssSelector("element-a-selector"))
WebElement targetB = driver.findElement(By.cssSelector("element-b-selector"))

targetA.click()
Actions actions = new Actions(driver)

actions.keyDown(Keys.CONTROL).click(targetB).keyUp(Keys.CONTROL).perform()

Note that this is your second scenario, first clicking element A (you will need to add the CSS selector or any other way of identifying it) and then holding CTRL and clicking element B.

The first one (press CTRL, click element a, click element b, release CTRL) is similar, just change the last line to:

actions.keyDown(Keys.CONTROL).click(targetA).click(targetB).keyUp(Keys.CONTROL).perform()

and remove targetA.click().

You will need to import the following Selenium helper classes:

import org.openqa.selenium.By
import org.openqa.selenium.Keys
import org.openqa.selenium.WebDriver
import org.openqa.selenium.WebElement as WebElement
import org.openqa.selenium.interactions.Actions


问:
Cypress : How to get returned value from custom commands ? (Cypress-promise)
I'm searching a way to get back a return value returned by a custom Cypress commands.

I'm currently using Cypress and Cypress-promise lib (https://www.npmjs.com/package/cypress-promise)

Currently, result is that:
log1=CAR 1
log2=null

Where is my mistake ?

Test file:

```<code>it('Test 1', async function() {
     const carName = await promisify(cy.set_typeCarName());
     cy.log("log2 = " + carName );
});
</code>```

module:

```<code>set_typeCarName() {
     let carName = "CAR 1";
     cy.get('#newSiteCityInput').type(carName);
     cy.log("log1 = " + carName);
     return carName;
};

Cypress.Commands.add('set_typeCarName',() => {
    webnewsite.set_typeCarName();
});
</code>```

答:
I think this is what you want:

Testfile

```<code>            cy.set_typeCarName()
                .then((returned_value) => {
                    cy.log("log2 = " + returned_value)
                })
            });
</code>```

Module

```<code>    Cypress.Commands.add('set_typeCarName',() => {
            let carName = "CAR 1";
            cy.get('#newSiteCityInput').type(carName);
            cy.log("log1 = " + carName);
            return carName;
    });
</code>```

Body:
I'm searching a way to get back a return value returned by a custom Cypress commands.

I'm currently using Cypress and Cypress-promise lib (https://www.npmjs.com/package/cypress-promise)

Currently, result is that:
log1=CAR 1
log2=null

Where is my mistake ?

Test file:

it('Test 1', async function() {
     const carName = await promisify(cy.set_typeCarName());
     cy.log("log2 = " + carName );
});

module:

set_typeCarName() {
     let carName = "CAR 1";
     cy.get('#newSiteCityInput').type(carName);
     cy.log("log1 = " + carName);
     return carName;
};

Cypress.Commands.add('set_typeCarName',() => {
    webnewsite.set_typeCarName();
});

Body:
I think this is what you want:

Testfile

            cy.set_typeCarName()
                .then((returned_value) => {
                    cy.log("log2 = " + returned_value)
                })
            });

Module

    Cypress.Commands.add('set_typeCarName',() => {
            let carName = "CAR 1";
            cy.get('#newSiteCityInput').type(carName);
            cy.log("log1 = " + carName);
            return carName;
    });


问:
How can I make a copy of a table with a PK?
In an Oracle 10g database, I would like to make a copy of an existing table. I would like it to have the same data and rows as the original table. The original table uses a PK though, so I'm not sure how to copy it and keep them unique.</p>

答:
Or you can just do it all in one statement:

```<code>create table mike_temp_1 (
  col1,
  col2,
  col3,
  col4,
  col5,
  constraint xpk_mike_temp_1 primary key (col1)
)
as select *
from OLD_POLICY_TERM;
</code>```

I think the format of specifying column names when using create table as select is a bit fiddly in that I don't believe that you can specify data types (sort of obvious really) but you can specify constraints such as not null, primary key and foreign key.

Body:
Or you can just do it all in one statement:

create table mike_temp_1 (
  col1,
  col2,
  col3,
  col4,
  col5,
  constraint xpk_mike_temp_1 primary key (col1)
)
as select *
from OLD_POLICY_TERM;

I think the format of specifying column names when using create table as select is a bit fiddly in that I don't believe that you can specify data types (sort of obvious really) but you can specify constraints such as not null, primary key and foreign key.


问:
How to read the pdf file in a line by line string in Python/Django?
I am dealing with the text and pdf file equal or less than 5KB. If the file is a text file, I get a file from the form and get the required input in a string to summarize:

```<code> file = file.readlines()
 file = ''.join(file)
 result = summarize(file, num_sentences)
</code>```

It's easily done but for pdf file it turns out it's not that easy. Is there a way to get the sentences of pdf file as a string like I did with my txt file in Python/Django?

答:
In Django you can do this:

views.py :

```<code>def upload_pdf():
     if request.method == 'POST' and request.FILES['myfile']:
        pdfFileObj = request.FILES['myfile'].read()
        pdfReader = PyPDF2.PdfFileReader(io.BytesIO(pdfFileObj))
        NumPages = pdfReader.numPages
        i = 0
        content = []
        while (i<NumPages):
            text = pdfReader.getPage(i)
            content.append(text.extractText())
            i +=1
       # depends on what you want to do with the pdf parsing results
       return render(request, .....)
</code>```

html part:

```<code><form method="post" enctype="multipart/form-data" action="/url">
    {% csrf_token %}
      <input  type="file" name="myfile"> # the name is the same as the one you put in FILES['myfile']
    <button class="butto" type="submit">Upload</button>
</form>
</code>```

In Python you can simply do this :

```<code>fileName = "path/test.pdf"
pdfFileObj = open(fileName,'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
NumPages = pdfReader.numPages

i = 0
content = []
while (i<NumPages):
    text = pdfReader.getPage(i)
    content.append(text.extractText())
    i +=1
</code>```

Body:
I am dealing with the text and pdf file equal or less than 5KB. If the file is a text file, I get a file from the form and get the required input in a string to summarize:

 file = file.readlines()
 file = ''.join(file)
 result = summarize(file, num_sentences)

It's easily done but for pdf file it turns out it's not that easy. Is there a way to get the sentences of pdf file as a string like I did with my txt file in Python/Django?

Body:
In Django you can do this:

views.py :

def upload_pdf():
     if request.method == 'POST' and request.FILES['myfile']:
        pdfFileObj = request.FILES['myfile'].read()
        pdfReader = PyPDF2.PdfFileReader(io.BytesIO(pdfFileObj))
        NumPages = pdfReader.numPages
        i = 0
        content = []
        while (i<NumPages):
            text = pdfReader.getPage(i)
            content.append(text.extractText())
            i +=1
       # depends on what you want to do with the pdf parsing results
       return render(request, .....)

html part:

<form method="post" enctype="multipart/form-data" action="/url">
    {% csrf_token %}
      <input  type="file" name="myfile"> # the name is the same as the one you put in FILES['myfile']
    <button class="butto" type="submit">Upload</button>
</form>

In Python you can simply do this :

fileName = "path/test.pdf"
pdfFileObj = open(fileName,'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
NumPages = pdfReader.numPages

i = 0
content = []
while (i<NumPages):
    text = pdfReader.getPage(i)
    content.append(text.extractText())
    i +=1


问:
How to Hide nested HTTP Samples(Child samples) in the Jmeter HTML Report
I have generated the Jmeter HTML Report but in the Graphs Child samples data is displayed (But I checked Generate parent sample Check box in Transaction controller).Where do I need to change if I want only Transactions to be displayed in graphs
screenshot

I have used below command to run from Command line but Some graphs are empty and Request Summary is also empty but Child samples data is not displayed in the graphs

jmeter -Jjmeter.save.saveservice.subresults=false -n -t E:\apache-jmeter-5.1.1\bin\jp\BookWithTemplate.jmx -l E:\apache-jmeter-5.1.1\bin\CSV\BWT.csv  -e -o E:\apache-jmeter-5.1.1\bin\GeneratedReports

In reports I need to have the results only for Transactions not for Child samples.
In all the graphs Child samples should not be displayed.

答:
If you don't want child samples to appear in your HTML report:

In the listener page(where you have saved the result file as E:\apache-jmeter-5.1.1\bin\CSV\BWT.csv and which is the source file of HTML report) -> click on configure button -> uncheck the Save Sub Result option -> Hit Done button

Now do the execution and try to genertae HTML reports. It will not contain child samples(Sub Requests)

Reference :

Configure result file to customize HTML report

How to generate HTML report in JMeter


问:
Web scraping buttons and fields with same type name
I have a code for web scraping. It operates pretty well but after some operations I can't figure how to proceed as there is no unique parameters to connect VBA commands to.

Here is my current code:

```<code>Sub ChechAutomate()

    Dim ie As New InternetExplorer, url As String, ws As Worksheet

    Set ws = ThisWorkbook.Sheets("Other Data")

    url = "https://infra.com"

    With ie
        .Visible = True
        .Navigate2 url

        While .Busy Or .ReadyState < 4: DoEvents: Wend

        With .Document

        If .querySelectorAll("#login-bis-id-btn").Length > 0 Then

            .querySelector("[name=userName]").Value = "username"
            .querySelector("[name=password]").Value = "password"
            .querySelector("[type=submit]").Click

        Else

            Application.Wait (Now + TimeValue("00:00:01"))

            .querySelector("[id=companySearchKeyData]").Value = ws.Range("T24").Value
            .querySelector("[type=submit]").Click

            Application.Wait (Now + TimeValue("00:00:01"))

            .querySelector("[name=creditType] [value='17']").Selected = True

            Application.Wait (Now + TimeValue("00:00:01"))

            .querySelector("[id=legalForms] [value='EN']").Selected = True

        End If

        End With

    End With

End Sub
</code>```

1) After upper code is ready I need to click this button:

I have tried .querySelector("[name=#]").Click. Text "New decision" is changing within the language of the page. Also there are other type="button" buttons.

2) After (1) has been done, I need to input value to this field:

I have tried to use .querySelector("[name=questions[0].answer]").Value = "1000"
it gives an error.

3) After (1) and (2) I need to click a button:

答:
Caveat:

We really need to see more html. Without seeing the entire html (obfuscate private info) with problems like 1 and 3 I can only give general approaches to consider.

Problem 1)

For now, you have three other options at least:

1) grab the collection/nodelist and index in to get correct button/loop all items
checking for unique innerText/attribute if available

```<code>Set col = ie.document.getElementsByTagName("input")  'collection. For Each over
Set nodeList = ie.document.querySelectorAll("input") 'nodelist. For i = 0 to nodeList.Length -1
</code>```

Indexing:

```<code>col(0)  'example index
nodeList.item(0)  'example index
</code>```

2) Find a relationship between this element and another that captures this element. Or some combination of attributes to identify. See answer here for some further detail.

For example, perhaps adding parent div class

```<code>ie.document.querySelector("div.content [type=button]")
</code>```

3) Pass a list with Or syntax of the language variants

```<code>ie.document.querySelector("[value='New decision'], [value='Neue Entscheidung'],[value='Other language variant']")
</code>```

Problem 2)

You need to use single quotes inside of double quotes

```<code>ie.document.querySelector("[name='questions[0].answer']").value = 1000
</code>```

Problem 3)

As per problem 1.

Footnotes:

Remember querySelector returns first match for pattern, querySelectorAll returns all matches.

Body:
I have a code for web scraping. It operates pretty well but after some operations I can't figure how to proceed as there is no unique parameters to connect VBA commands to.

Here is my current code:

Sub ChechAutomate()

    Dim ie As New InternetExplorer, url As String, ws As Worksheet

    Set ws = ThisWorkbook.Sheets("Other Data")

    url = "https://infra.com"

    With ie
        .Visible = True
        .Navigate2 url

        While .Busy Or .ReadyState < 4: DoEvents: Wend

        With .Document

        If .querySelectorAll("#login-bis-id-btn").Length > 0 Then

            .querySelector("[name=userName]").Value = "username"
            .querySelector("[name=password]").Value = "password"
            .querySelector("[type=submit]").Click

        Else

            Application.Wait (Now + TimeValue("00:00:01"))

            .querySelector("[id=companySearchKeyData]").Value = ws.Range("T24").Value
            .querySelector("[type=submit]").Click

            Application.Wait (Now + TimeValue("00:00:01"))

            .querySelector("[name=creditType] [value='17']").Selected = True

            Application.Wait (Now + TimeValue("00:00:01"))

            .querySelector("[id=legalForms] [value='EN']").Selected = True

        End If

        End With

    End With

End Sub

1) After upper code is ready I need to click this button:

I have tried .querySelector("[name=#]").Click. Text "New decision" is changing within the language of the page. Also there are other type="button" buttons.

2) After (1) has been done, I need to input value to this field:

I have tried to use .querySelector("[name=questions[0].answer]").Value = "1000"
it gives an error.

3) After (1) and (2) I need to click a button:

Body:
Caveat:

We really need to see more html. Without seeing the entire html (obfuscate private info) with problems like 1 and 3 I can only give general approaches to consider.

Problem 1)

For now, you have three other options at least:

1) grab the collection/nodelist and index in to get correct button/loop all items
checking for unique innerText/attribute if available

Set col = ie.document.getElementsByTagName("input")  'collection. For Each over
Set nodeList = ie.document.querySelectorAll("input") 'nodelist. For i = 0 to nodeList.Length -1

Indexing:

col(0)  'example index
nodeList.item(0)  'example index

2) Find a relationship between this element and another that captures this element. Or some combination of attributes to identify. See answer here for some further detail.

For example, perhaps adding parent div class

ie.document.querySelector("div.content [type=button]")

3) Pass a list with Or syntax of the language variants

ie.document.querySelector("[value='New decision'], [value='Neue Entscheidung'],[value='Other language variant']")

Problem 2)

You need to use single quotes inside of double quotes

ie.document.querySelector("[name='questions[0].answer']").value = 1000

Problem 3)

As per problem 1.

Footnotes:

Remember querySelector returns first match for pattern, querySelectorAll returns all matches.


问:
add worklog to JIRA (with user and activity metadata) using the API
I am using jira-python and request API to log work to JIRA tickets with the user and activity info but can't figure out a way to do it . I have the following code : </p>

```<code>jira.add_worklog("issue number", timeSpent="2h", user="username")
</code>```

<p>but it seems to ignore the user keyword. I am also looking up JIRA API with request library but can't seem to find an API to log work with activity and user info. </p>

答:
It is not needed to add inside the arguments the user. you can use the following code:

```<code>jira.add_worklog("issue number", timeSpent="2h")
</code>```

Yo can add other arguments like:

adjustEstimate – (optional) allows the user to provide specific instructions to update the remaining time estimate of the issue. The value can either be new, leave, manual or auto (default).

newEstimate – the new value for the remaining estimate field. e.g. “2d”

reduceBy – the amount to reduce the remaining estimate by e.g. “2d”

started – Moment when the work is logged, if not specified will default to now

comment – optional worklog comment

You can find more info about it in jira python api

Body:
I am using jira-python and request API to log work to JIRA tickets with the user and activity info but can't figure out a way to do it . I have the following code :

jira.add_worklog("issue number", timeSpent="2h", user="username")

but it seems to ignore the user keyword. I am also looking up JIRA API with request library but can't seem to find an API to log work with activity and user info.

Body:
It is not needed to add inside the arguments the user. you can use the following code:

jira.add_worklog("issue number", timeSpent="2h")

Yo can add other arguments like:

adjustEstimate – (optional) allows the user to provide specific instructions to update the remaining time estimate of the issue. The value can either be new, leave, manual or auto (default).

newEstimate – the new value for the remaining estimate field. e.g. “2d”

reduceBy – the amount to reduce the remaining estimate by e.g. “2d”

started – Moment when the work is logged, if not specified will default to now

comment – optional worklog comment

You can find more info about it in jira python api


问:
What is the best way to give variable/argument from one class to another using C#
What are the "good practices" in passing argiments/variables between classes? Better is using get and set or maybe giving that for example class1.a = class2.b?

Maybe exists better ways? Thanks for help.

答:
That is architectural question and the answer can be large and it depends on the project and the specifics of the architecture that you use.

Generally for your example, exposing class's variables should be done via public/internal/protected Properties (i.e. via get; set;) and not via public variables. Using public variables is bad practice.

But even that is not a good in more advanced architecture.
E.g. Look at the SOLID principles.
Here is a good article which we use at work:

https://williamdurand.fr/2013/07/30/from-stupid-to-solid-code/


答:
Yes. As Wikipedia points out, there's Metaphone and Double Metaphone, NYSIIS and more.

Keep in mind that these only works for English, which has its own particular problems with its orthography. It's hardly needed for Spanish, and doesn't make sense for Chinese/Mandarin.

Title: Has Soundex been improved?

Body: Soundex seems to be implemented in some DBMS's, but have there been any algorithmic improvements that are definitively better than the current implementation of Soundex?


问:
bootstrap4 drop down menu only work once when I click it
I have a dropdown in my webpage. But it shows the menu items only once. ie-It shows the menu items only when I click it for the first time. If I reload the page again then it work again. Following is the code I have written for the dropdown menu.

```<code><!-- Dropdown -->
    <li class="nav-item dropdown">
      <a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown">
        Shop
      </a>
      <div class="dropdown-menu">
        <a class="dropdown-item" href="#">Shoes</a>
        <a class="dropdown-item" href="#">Handbags</a>
      </div>
    </li>
</code>```

Thank you.

And this is my header code

```<code><head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/main.css">
<title>My title</title>
</code>```

答:
Add role="button" to your toggle link:

Shop
```

Also, make sure you have loaded the Bootstrap JS file in your code.

Body:
I have a dropdown in my webpage. But it shows the menu items only once. ie-It shows the menu items only when I click it for the first time. If I reload the page again then it work again. Following is the code I have written for the dropdown menu.

        Shop

        Shoes
        Handbags

Thank you.

And this is my header code

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<link rel="stylesheet" type="text/css" href="css/main.css">
<title>My title</title>

Body:
Add role="button" to your toggle link:

<a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown" role="button">Shop</a>

Also, make sure you have loaded the Bootstrap JS file in your code.


答:
You can use Handler with a runnable.

```<code>private TextView textView;
private Handler handler;
</code>```

in your onCreate()

```<code>textView = findViewById(R.id.tv_bt_msg);
textView.setText("secondNumber");

handler = new Handler();
//Change the textview after 5 seconds
handler.postDelayed(runnable, 5000);
</code>```

Runnable to change text every 5 seconds

```<code>private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            String currentString = textView.getText().toString();
            if(currentString.equals("secondNumber")){
                currentString = "firstNumber";
            }else{
                currentString = "secondNumber";
            }
            final String tempString = currentString;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    textView.setText(tempString);
                }
            });
            //Change the textview again after 5 seconds
            handler.postDelayed(runnable, 5000);
        }
    };
</code>```

Use this to removeCallbacks

```<code>handler.removeCallbacks(runnable);
</code>```

Title: How to switch TextView between values every 5 seconds

Body:
I don't know if using Threads is the practice for what I am trying to achieve so please feel free to amend the code where you wish.

I am trying to implement a feature in my app where a TextView switches to 1 value and thereafter reverts back to the initial value every 5 seconds. I have implemented the following using on a thread:

    layoutDate.setText(firstNumber);

    Thread numberSwitch = new Thread() {
    @Override
    public void run() {
        while(!isInterrupted()) {
            try {

                Thread.sleep(5000);

                runOnUiThread(new Runnable () {
                    @Override
                    public void run() {

                        layoutDate.setText(secondNumber);

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

numberSwitch.start();

I have tried adding layoutDate.setText(firstNumber) just after the runUiOnThread and also after the nested run but it still doesn't work as I want it to.

I want to achieve something like the following:

Body:
You can use Handler with a runnable.

private TextView textView;
private Handler handler;

in your onCreate()

textView = findViewById(R.id.tv_bt_msg);
textView.setText("secondNumber");

handler = new Handler();
//Change the textview after 5 seconds
handler.postDelayed(runnable, 5000);

Runnable to change text every 5 seconds

private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            String currentString = textView.getText().toString();
            if(currentString.equals("secondNumber")){
                currentString = "firstNumber";
            }else{
                currentString = "secondNumber";
            }
            final String tempString = currentString;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    textView.setText(tempString);
                }
            });
            //Change the textview again after 5 seconds
            handler.postDelayed(runnable, 5000);
        }
    };

Use this to removeCallbacks

handler.removeCallbacks(runnable);


问:
Regex to get json data from the response
I have a json response like this

```<code>2019 May 28 10:03:56.586520 pacexg1v1 rdkbrowser2[4786]:  190528-10:03:56.586491 [mod=RDKBROWSER2, lvl=INFO] [tid=4786] onConsoleLog:rdkbrowser.cpp:926 [ConsoleAPI:144]: {"objectName":"com.comcast.BridgeObject_1","methodName":"JSMessageChanged","argv":["{\"action\":\"entitlementsAccountLink\",\"args\":{\"action\":\"appLaunch\",\"subscriptionEntitlements\":[{\"id\":\"Prime\",\"endDate\":1561629841000}]},\"pid\":7}"]}
</code>```

From this using regex how can i get the json alone

```<code>{"objectName":"com.comcast.BridgeObject_1","methodName":"JSMessageChanged","argv":["{\"action\":\"entitlementsAccountLink\",\"args\":{\"action\":\"appLaunch\",\"subscriptionEntitlements\":[{\"id\":\"Prime\",\"endDate\":1561629841000}]},\"pid\":7}"]}
</code>```

答:
The following regular expression will do the work ({[\s\S]*}) when you have only one JSON data in a response and your response cannot contain { and } characters outside of the JSON data.

Otherwise you cannot resolve it with regular expressions, because a JSON data mostly contains recursion, ex. {"obj1": {"obj1_1": "val1_1"}}.

If you have two JSON data in a response you cannot tell where the first one ends and where the second one begins with regular expression.

Body:
I have a json response like this

2019 May 28 10:03:56.586520 pacexg1v1 rdkbrowser2[4786]:  190528-10:03:56.586491 [mod=RDKBROWSER2, lvl=INFO] [tid=4786] onConsoleLog:rdkbrowser.cpp:926 [ConsoleAPI:144]: {"objectName":"com.comcast.BridgeObject_1","methodName":"JSMessageChanged","argv":["{\"action\":\"entitlementsAccountLink\",\"args\":{\"action\":\"appLaunch\",\"subscriptionEntitlements\":[{\"id\":\"Prime\",\"endDate\":1561629841000}]},\"pid\":7}"]}

From this using regex how can i get the json alone

{"objectName":"com.comcast.BridgeObject_1","methodName":"JSMessageChanged","argv":["{\"action\":\"entitlementsAccountLink\",\"args\":{\"action\":\"appLaunch\",\"subscriptionEntitlements\":[{\"id\":\"Prime\",\"endDate\":1561629841000}]},\"pid\":7}"]}


问:
Which Angular Material version should I install to be compatible with Angular4?
Which Angular Material version should I install to be compatible with Angular4?

I have used below command to install angular Material on the top of Angular 4 project.

```<code>npm install @angular/materail
npm install @angular/cdk
npm install @angular/animations
</code>```

While I try to run the app I am getting below error.

```<code>/node_modules/@angular/cdk/observers/typings/observe-content.d.ts (33,22): Type 'ElementRef' is not generic.
</code>```

答:
They have renamed as Angular/Components. May be you can try V2.0.0-beta.12 and check whether it helps.

npm install @angular/materail@2.0.0-beta.12
npm install @angular/cdk@2.0.0-beta.12
npm install @angular/animations

Body:
Which Angular Material version should I install to be compatible with Angular4?

I have used below command to install angular Material on the top of Angular 4 project.

npm install @angular/materail
npm install @angular/cdk
npm install @angular/animations

While I try to run the app I am getting below error.

/node_modules/@angular/cdk/observers/typings/observe-content.d.ts (33,22): Type 'ElementRef' is not generic.


答:
I would advise you to update your project to the latest version of angular. For stability, features and performance reasons. Also finding documentation/guides about such old version is a lot more difficult.

Besides that, if you want to install material for such an old angular version, you should use the 2.0.0-beta.12 version, which is compatible with angular 4:

```<code>npm install @angular/material@2.0.0-beta.12
</code>```

Title: Which Angular Material version should I install to be compatible with Angular4?

Body:
I would advise you to update your project to the latest version of angular. For stability, features and performance reasons. Also finding documentation/guides about such old version is a lot more difficult.

Besides that, if you want to install material for such an old angular version, you should use the 2.0.0-beta.12 version, which is compatible with angular 4:

npm install @angular/material@2.0.0-beta.12


问:
Collect values on grouped field
With given data

```<code>{
    "type": "INGESTION",
    "message": "Lorem"
}

{
    "type": "INGESTION",
    "message": "Ipsum"
}

{
    "type": "DISCHARGE",
    "message": "dolor"
}

{
    "type": "DISCHARGE",
    "message": "sit"
}
</code>```

I want to group by type and collecting all possible values of message into one single field.

The expected output should be something along the lines of

```<code>[{
    "type": "INGESTION",
    "messages": ["Lorem", "Ipsum"]
},
{
    "type": "DISCHARGE",
    "messages": ["dolor", "sit"]
}]
</code>```

I have tried several aggregation queries, none of which have led to a result that I could be satisfied with.

答:
There is an example on the doc which describes your same situation.</p>

```<code>db.your_collection.aggregate([
    {
        $group: {
            "_id": "$type",
            "messages": { $push: "$message" }
        }
    }
]);
</code>```

Title: Collect values on grouped field

Body:
With given data

{
    "type": "INGESTION",
    "message": "Lorem"
}

{
    "type": "INGESTION",
    "message": "Ipsum"
}

{
    "type": "DISCHARGE",
    "message": "dolor"
}

{
    "type": "DISCHARGE",
    "message": "sit"
}

I want to group by type and collecting all possible values of message into one single field.

The expected output should be something along the lines of

[{
    "type": "INGESTION",
    "messages": ["Lorem", "Ipsum"]
},
{
    "type": "DISCHARGE",
    "messages": ["dolor", "sit"]
}]

I have tried several aggregation queries, none of which have led to a result that I could be satisfied with.

Body:
There is an example on the doc which describes your same situation.

db.your_collection.aggregate([
    {
        $group: {
            "_id": "$type",
            "messages": { $push: "$message" }
        }
    }
]);


问:
How to force to lose focus of all fields in a form in jQuery
When a input field changes (onchange) I trigger a function to set a variable. The only problem is that the field first has to lose focus before the variable is set and I can check if the field(s) is changed, this is what I want to do when the user clicks on a tab so I can check if the user is forgotten to submit his form in the previous tab. Ho to force lose focus of all possible fields, so first the onchange event can take place?

答:
You don't need jQuery for this; vanillaJS can do this, too.

document.activeElement.blur();

Note: Usually, I would check for null-ness before calling a method, but activeElement will only ever return null if there is no ‹body› node, so this direct call is pretty safe.