问:
DynamoDB hierarchical one-to-many update-friendly pattern
I have heirarchical data that need to support CRUD operations on all levels. I have seen patterns like composite key with hash bangs mentioned in https://www.alexdebrie.com/posts/dynamodb-one-to-many/#composite-sort-keys-with-hierarchical-data , this is very smart for retrieving things but it doesn't seem efficient enough for updating things.

For example if I have to update a country name which has 50 states and those 50 states have 50 cities, the I need to update a whooping 2500 records just to update the country name. Same goes with updating a state name which needs 50 records to be updated.

A reasonable alternative to this seems to be maintaining Global Secondary indices for states and cities apart from a primary partition key on country. Is that the best way or am I missing a better approach?

Bonus: I need the best update-friendly approach for not just a 3 level heirarchy but a 4 or 5 or potentially a n level hierarchy

答:
It's worse than you think...

DDB doesn't allow you to update the key of an existing record.  You'd have to delete those 2500 records and re-add them.

Luckily, countries don't change their names that often..

Without knowing more about your actual data, I can't offer any suggestions other than you may want to consider Aurora instead of DDB.


来源: stackexchange

问:
aggregation at different levels, I need to get sum by type level in sql server
```<code>ID      TYPE        AMT         PERIOD
-------------------------------------------
1001     1          4500        2008-09-30
1001     2          2333        2008-09-30
1001     2         -2333        2008-09-30
1001     1          -200        2008-09-30
1001     2           300        2008-09-30
</code>```

Desired output:

```<code>ID      TYPE        AMT      PERIOD
------------------------------------
1001     1          4300    2008-09-30
1001     2           300    2008-09-30
</code>```

I need to get sum of the AMT but still needs to include other columns, please see the desired output as shown above.

I tried using grouping sets but can't get it right.

答:
```<code>SELECT ID,TYPE,SUM(AMT) as Total_Amt,PERIOD
FROM table
GROUP BY ID,TYPE,PERIOD
</code>```

ContentLicense: CC BY-SA 4.0

Body:
ID      TYPE        AMT         PERIOD
-------------------------------------------
1001     1          4500        2008-09-30
1001     2          2333        2008-09-30
1001     2         -2333        2008-09-30
1001     1          -200        2008-09-30
1001     2           300        2008-09-30

Desired output:

ID      TYPE        AMT      PERIOD
------------------------------------
1001     1          4300    2008-09-30
1001     2           300    2008-09-30

I need to get sum of the AMT but still needs to include other columns, please see the desired output as shown above.

I tried using grouping sets but can't get it right.


问:
Docker + Symfony - cache.WARNING: Failed to save key
Having var/cache and var/sessions mounted from the host to the container is causing a lot loading time. How could I ignore these directories so I wouldn't need to wait for var directory on my machine and container being synced?

```<code>version: "3"

volumes:
    var:
    vendor:

services:
    php:
        container_name: grozissaviems_php
        build:
            context: docker/php
            args:
                ENV: ${ENV}
                APP: symfony
        volumes:
            - .:/var/www/html:delegated
            - var:/var/www/html/var
            - vendor:/var/www/html/vendor
            - ./logs/symfony:/var/www/html/var/logs

    nginx:
        container_name: grozissaviems_nginx
        build:
            context: docker/nginx
            args:
                ENV: ${ENV}
        ports:
            - 5000:80
        volumes:
            - .:/var/www/html:delegated
            - var:/var/www/html/var
            - vendor:/var/www/html/vendor
            - ./logs/nginx:/var/log/nginx
        command: "nginx"
</code>```

After running container if I enter I get an error for cache permissions being incorrect.

If I launch a script to give var/* permissions

```<code>docker exec -it grozissaviems_php bash -c 'mkdir -p var/cache var/logs var/sessions'
docker exec -it grozissaviems_php bash -c 'chmod -R 777 var/cache var/logs var/sessions'
</code>```

now for some reason page is loaded (with a broken layout, but no error), but in dev.log I get:

cache.WARNING: Failed to save key
  "%5BSymfony%5CBundle%5CWebProfilerBundle%5CController%5CProfilerController%5D%5B1%5D"
  (array)
  {"key":"%5BSymfony%5CBundle%5CWebProfilerBundle%5CController%5CProfilerController%5D%5B1%5D","type":"array","exception":"[object]
  (ErrorException(code: 0):
  rename(/var/www/html/var/cache/dev/pools/zjgXxX8mSM/5ed64142f0b543.18899510,/var/www/html/var/cache/dev/pools/zjgXxX8mSM/J/P/W1NfrOIzF1l75zOKFhaN):
  No such file or directory at
  /var/www/html/vendor/symfony/symfony/src/Symfony/Component/Cache/Traits/FilesystemCommonTrait.php:93)"}
  []

Is there something wrong with my docker-compose.yml? Is there something I missed?

答:
First, you are mounting the var directory. That's not only unnecessary, but can be a potential problem setting permissions correctly and consistently between the host and the container.

Also, you have multiple redundant mounts. You mount the whole project first (.:/var/www/html:delegated), and then you mount var and vendor.

Instead of doing that, just mount exclusively what you need.

(Tangentially, you are also mounting var and vendor inside your nginx container. Neither of those are necessary inside the web-server container, so just remove them. On the webserver you only need the public directory).

Finally, instead of chmoding your var directory, just make the directory owned by the same user that runs the PHP process (www-data, most of the time).

You do not show your Dockerfile, but since you have a build context and do not have an image name, you must be using one.

In my projects, what I do is to first create the needed directories:

```<code>RUN set -eux; \
        mkdir -p var/cache var/log var/session
</code>```

And then, near the end of the build change their ownership:

```<code>RUN chmod g+s /var/www/html/var
RUN chown -R www-data /var/www/html/var;
</code>```

This way any other directory created under var will inherit this permissions.

Body:
Having var/cache and var/sessions mounted from the host to the container is causing a lot loading time. How could I ignore these directories so I wouldn't need to wait for var directory on my machine and container being synced?

version: "3"

volumes:
    var:
    vendor:

services:
    php:
        container_name: grozissaviems_php
        build:
            context: docker/php
            args:
                ENV: ${ENV}
                APP: symfony
        volumes:
            - .:/var/www/html:delegated
            - var:/var/www/html/var
            - vendor:/var/www/html/vendor
            - ./logs/symfony:/var/www/html/var/logs

    nginx:
        container_name: grozissaviems_nginx
        build:
            context: docker/nginx
            args:
                ENV: ${ENV}
        ports:
            - 5000:80
        volumes:
            - .:/var/www/html:delegated
            - var:/var/www/html/var
            - vendor:/var/www/html/vendor
            - ./logs/nginx:/var/log/nginx
        command: "nginx"

After running container if I enter I get an error for cache permissions being incorrect.

If I launch a script to give var/* permissions

docker exec -it grozissaviems_php bash -c 'mkdir -p var/cache var/logs var/sessions'
docker exec -it grozissaviems_php bash -c 'chmod -R 777 var/cache var/logs var/sessions'

now for some reason page is loaded (with a broken layout, but no error), but in dev.log I get:

cache.WARNING: Failed to save key
  "%5BSymfony%5CBundle%5CWebProfilerBundle%5CController%5CProfilerController%5D%5B1%5D"
  (array)
  {"key":"%5BSymfony%5CBundle%5CWebProfilerBundle%5CController%5CProfilerController%5D%5B1%5D","type":"array","exception":"[object]
  (ErrorException(code: 0):
  rename(/var/www/html/var/cache/dev/pools/zjgXxX8mSM/5ed64142f0b543.18899510,/var/www/html/var/cache/dev/pools/zjgXxX8mSM/J/P/W1NfrOIzF1l75zOKFhaN):
  No such file or directory at
  /var/www/html/vendor/symfony/symfony/src/Symfony/Component/Cache/Traits/FilesystemCommonTrait.php:93)"}
  []

Is there something wrong with my docker-compose.yml? Is there something I missed?

Body:
First, you are mounting the var directory. That's not only unnecessary, but can be a potential problem setting permissions correctly and consistently between the host and the container.

Also, you have multiple redundant mounts. You mount the whole project first (.:/var/www/html:delegated), and then you mount var and vendor.

Instead of doing that, just mount exclusively what you need.

(Tangentially, you are also mounting var and vendor inside your nginx container. Neither of those are necessary inside the web-server container, so just remove them. On the webserver you only need the public directory).

Finally, instead of chmoding your var directory, just make the directory owned by the same user that runs the PHP process (www-data, most of the time).

You do not show your Dockerfile, but since you have a build context and do not have an image name, you must be using one.

In my projects, what I do is to first create the needed directories:

RUN set -eux; \
        mkdir -p var/cache var/log var/session

And then, near the end of the build change their ownership:

RUN chmod g+s /var/www/html/var
RUN chown -R www-data /var/www/html/var;

This way any other directory created under var will inherit this permissions.


问:
setstate object:{array:[]} in reactjs how could i add the **key and value inside the array which is in the state object**?

key and value inside the array which is in the state object

this.state = {
   frequency: {
  days: [],
  startdate: "",
  customdate: "" },
     };

how could i add the key ad value inside the days array?

答:
You can modify your state by using setState like this:

```<code>this.setState({frequency: {...this.state.frequency, days: [...this.state.frequency.days, day]}});
</code>```

Body:
You can modify your state by using setState like this:

this.setState({frequency: {...this.state.frequency, days: [...this.state.frequency.days, day]}});


问:
save hidden values in header after redirect
I have a form with 2 pages that retrieve information, that information is stored in my header file as hidden values.  After the second page the user is directed to a third party payment system.  Then they are redirected back to the third page of the form.  However, my header does not have the hidden values anymore.  how do i gain access to those values, as i do nee them for database purposes.</p>

答:
If the third party payment system you speak of is PayPal, there's a way to set values that they'll send back to you.

However, if the payment system does not have such an API, then I think you're out of luck.  It would be their system that generates the headers that would come back to you. It's highly unlikely that their API wouldn't have a way to do it though.

ContentLicense: CC BY-SA 3.0


问:
Unable to launch Jupyter lab from cmd in windows 7
The command 'jupyter lab' usually works fine in cmd. But today it isn't. I uninstall and reinstalled all jupyter components but no gain. Jupyter notebook seems to be working though.

C:\Users\Sarth.choudhary>jupyter lab
  Cannot open D:\Programs\Miniconda3\Scripts\jupyter-lab-script.py

I looked into the miniconda directory, jupyter-lab-script.py is indeed missing. I don't have this file anywhere in the miniconda directory.

Any help much appreciated.

答:
I created another environment and installed jupyter lab in it. Ensured everything worked fine. Copied the missing file and pasted it in the base env folder. After making sure that I can launch Jupiter lab from base environment I removed the new environment.
I think antivirus must have deleted that file so I created an exception in antivirus.</p>


问:
How do I clone a private git repo with ssh in vscode?
I'm using mac and I was wondering how can I clone a private github repo with ssh using vscode? I looked at code.visualstudio.com/docs/editor/versioncontrol but I couldn't find anything about cloning with ssh.

In vscode I go to the source control icon on the left and click clone repository. I enter git@github.com:username/project and it says permission denied. I do have my public and private key generated but where do I enter them?

答:
Ssh is something which you set in your ssh-agent and it works with bash. I have been using Vscode for quite some time and i always setup ssh using git bash which is easier. I clone a project into my workspace using git bash and then open it with vscode.

As far as I can see, there is no way you can setup ssh from vscode.

if you are looking to setup ssh from terminal, docs are here.


答:
function addKeyValue(key, value) {

  this.setState(state => ({
    ...state,
    frequency: {
       ...state.frequency,
       days: [...state.frequency.days, {[key]: value}]
    }
  })
}
```

<p>--Edit </p>

<p>Removing the key is a bit trickier.</p>

<pre class="lang-js prettyprint-override"><code>function removeKeyValue(key, value) {

  this.setState(state => {
    const days = state.frequency.days;
    const dayIndex = days.findIndex(pr => pr[key] === value);
    const day = {...days[dayIndex]};
    delete day[key];

    return {
      ...state,
      frequency: {
         ...state.frequency,
         days: [...days.slice(0, dayIndex),
            day,
            ...days.slice(dayIndex + 1)]
      }
    }
  }
}
</code>```

Title: setstate object:{array:[]} in reactjs how could i add the **key and value inside the array which is in the state object**?

Body:
key and value inside the array which is in the state object

this.state = {
   frequency: {
  days: [],
  startdate: "",
  customdate: "" },
     };

how could i add the key ad value inside the days array?

Body:
function addKeyValue(key, value) {

  this.setState(state => ({
    ...state,
    frequency: {
       ...state.frequency,
       days: [...state.frequency.days, {[key]: value}]
    }
  })
}

--Edit

Removing the key is a bit trickier.

function removeKeyValue(key, value) {

  this.setState(state => {
    const days = state.frequency.days;
    const dayIndex = days.findIndex(pr => pr[key] === value);
    const day = {...days[dayIndex]};
    delete day[key];

    return {
      ...state,
      frequency: {
         ...state.frequency,
         days: [...days.slice(0, dayIndex),
            day,
            ...days.slice(dayIndex + 1)]
      }
    }
  }
}


问:
using regex to capture setences containing word for each word in a list python
I am using python and regex to try to grab all sentences in a list of tweets containing a certain word for each word within a series of a pandas df.

My df stocks_df contains certain stock names e.g.

```<code>  Symbol
0   $GSX
1  $NVDA
2  $MBRX
5  $BBBY
6   $DIS
</code>```

I want all sentences in the tweets that contain these strings. My attempted solution follows another regex question I had: Key error when using regex quantifier python

However my solution mostly grabs sentences the symbol at the start of the sentence and doesn't grab it if in the middle of the sentence. It also seems to match only symbols without getting the rest of the sentence. My code is as such:

pattern2 = r'(?:{}) (?:[^.]*[^.]*\.)'.format("|".join(map(re.escape, stocks_df['Symbol'])))

Does anyone understand why full sentences are not being matched?

答:
If you do not have to deal with abbreviations and other messy formats, you may match those strings using

```<code>r'[^.?!]*(?:{})\b[^.?!]*[.?!]'.format("|".join(map(re.escape, stocks_df['Symbol'])))
</code>```

The pattern will look like [^.?!]*(?:\$GSX|\$NVDA|...)\b[^.?!]*[.?!] and will match

[^.?!]* - 0 or more chars other than !, ? and .

(?:\$GSX|\$NVDA) - a word from the Symbol column

\b - whole word is required, \b is a word boundary

[^.?!]* - 0 or more chars other than !, ? and .

[.?!] - a ?, ! or .

Body:
I am using python and regex to try to grab all sentences in a list of tweets containing a certain word for each word within a series of a pandas df.

My df stocks_df contains certain stock names e.g.

  Symbol
0   $GSX
1  $NVDA
2  $MBRX
5  $BBBY
6   $DIS

I want all sentences in the tweets that contain these strings. My attempted solution follows another regex question I had: Key error when using regex quantifier python

However my solution mostly grabs sentences the symbol at the start of the sentence and doesn't grab it if in the middle of the sentence. It also seems to match only symbols without getting the rest of the sentence. My code is as such:

pattern2 = r'(?:{}) (?:[^.]*[^.]*\.)'.format("|".join(map(re.escape, stocks_df['Symbol'])))

Does anyone understand why full sentences are not being matched?

Body:
If you do not have to deal with abbreviations and other messy formats, you may match those strings using

r'[^.?!]*(?:{})\b[^.?!]*[.?!]'.format("|".join(map(re.escape, stocks_df['Symbol'])))

The pattern will look like [^.?!]*(?:\$GSX|\$NVDA|...)\b[^.?!]*[.?!] and will match

[^.?!]* - 0 or more chars other than !, ? and .

(?:\$GSX|\$NVDA) - a word from the Symbol column

\b - whole word is required, \b is a word boundary

[^.?!]* - 0 or more chars other than !, ? and .

[.?!] - a ?, ! or .


问:
Decrease Paramiko maximal request size
I have a Python Runbook and I would like to set the MAX_REQUEST_SIZE = 1024 instead of 32768 (default value) in the Paramiko's sftp_file.py.

Have you any idea about how can we do it??

I'am trying to transfer files from SFTP to local. And for some reasons, the transfer of files with more than 30MB is suspended automatically when achieving the 27-28 MB without getting any error message. When I changed locally the max_request_size to 1024, it worked.

答:
Try slowing down the transfer instead. A very trivial implementation of transfer throttling can be like:

```<code>import time
</code>```

```<code>bytes_per_second = 512*1024
start_time = time.time()

def callback(transferred, total):
    while (transferred / (time.time() - start_time)) > bytes_per_second:
        time.sleep(0.1)

sftp.get(filepath, os.path.join(localFilePath, entry.filename), callback)
</code>```

Alternatively, just control the request size by re-implementing the download:

```<code>with sftp.open(filepath, "rb") as fr, \
     open(os.path.join(localFilePath, entry.filename), "wb") as fl:
    while True:
        data = fr.read(1024)
        fl.write(data)
        if len(data) == 0:
            break
</code>```

The above is a stripped down version of what SFTPClient.get does internally.

Title: Decrease Paramiko maximal request size

Body:
Try slowing down the transfer instead. A very trivial implementation of transfer throttling can be like:

import time

bytes_per_second = 512*1024
start_time = time.time()

def callback(transferred, total):
    while (transferred / (time.time() - start_time)) > bytes_per_second:
        time.sleep(0.1)

sftp.get(filepath, os.path.join(localFilePath, entry.filename), callback)

Alternatively, just control the request size by re-implementing the download:

with sftp.open(filepath, "rb") as fr, \
     open(os.path.join(localFilePath, entry.filename), "wb") as fl:
    while True:
        data = fr.read(1024)
        fl.write(data)
        if len(data) == 0:
            break

The above is a stripped down version of what SFTPClient.get does internally.


问:
Making jQuery slideUp when clicking off
I am using jQuery to make a nav slideDown. I want when people click anywhere outside of the nav it slideUp.

The problem is that with my code it slideUp even if I click on the element. I basically want it to slideUp if the user clicks anywhere other than the element which slideDown

```<code> //News Drop Down
$(document).ready(function () {
$('li.newsDrop').mouseenter(function () {
    $('div.newsadviceDrop').slideDown('medium');
});
});

$('body').click(function() {
    $('div.newsadviceDrop').slideUp('slow', function() {
    // Animation complete.
   });
});
</code>```

答:
This it wath I would do:   </p>

```<code>$('*').not("li.newsDrop").click(function() {
    $('div.newsadviceDrop').slideUp('slow', function() {
    // Animation complete.
});
</code>```

Title: Making jQuery slideUp when clicking off

Body:
I am using jQuery to make a nav slideDown. I want when people click anywhere outside of the nav it slideUp.

The problem is that with my code it slideUp even if I click on the element. I basically want it to slideUp if the user clicks anywhere other than the element which slideDown

 //News Drop Down
$(document).ready(function () {
$('li.newsDrop').mouseenter(function () {
    $('div.newsadviceDrop').slideDown('medium');
});
});

$('body').click(function() {
    $('div.newsadviceDrop').slideUp('slow', function() {
    // Animation complete.
   });
});

Body:
This it wath I would do:

$('*').not("li.newsDrop").click(function() {
    $('div.newsadviceDrop').slideUp('slow', function() {
    // Animation complete.
});


问:
How can I check FindGameObjectsWithTag during runtime?
I'm having troubles with my enemy NavMeshAgent AI, First it searches for GameObjects tagged with "Defenses", then I set the first destination based in how close the defense is by my enemy, when the defense is destroyed, the array value is increased by one and it changes the destination to the next defense.

My problem is, my player can create (Instance) new defenses during the game, when all my defenses are destroyed, my enemy turns crazy, so, i need a way to add those new defenses to my array, below is my enemy script.

```<code> public class NavMeshEnemy : MonoBehaviour
 {
     [Header("References", order = 0)]
     [SerializeField] NavMeshAgent enemyAgent;
     [Space(10)]
     [SerializeField] GameObject[] destinations;
     [Space(10)]
     [SerializeField] float distanceObjects;
     [SerializeField] int arrayElements = 0;

     void Awake()
     {
         enemyAgent = GetComponent<NavMeshAgent>();
         destinations = GameObject.FindGameObjectsWithTag("Defenses");
     }

     void Start()
     {
         destinations = destinations.OrderBy((d) => (d.transform.position - this.transform.position).sqrMagnitude).ToArray();
     }

     void Update()
     {
         distanceObjects = Vector3.Distance(this.transform.position, destinations[arrayElements].transform.position);

         enemyAgent.destination = destinations[arrayElements].transform.position;

         CheckArray();
     }

     void CheckArray()
     {
         if (destinations[arrayElements].gameObject.activeInHierarchy == false)
         {
             if (arrayElements < destinations.Length - 1)
             {
                 arrayElements++;
                 enemyAgent.destination = destinations[arrayElements].transform.position;
             }
             else
             {
                 arrayElements = 0;
             }
         }
     }
 }
</code>```

Thank you for reading! :)

答:
I would rather implement a component on your prefab with a static list like e.g.

public class NavMeshDestination : MonoBehaviour
{
    public static HashSet<Transform> existingDestinations = new HashSet<Transform>();

    private void Awake()
    {
       if(!existingDestinations.Contains(this)) existingDestinations.Add(this);
    }

    private void OnDestroy()
    {
        if(existingDestinations.Contains(this)) existingDestinations.Remove(this);
    }
}
```

<p>And then don't even go by tag but simply do</p>

<pre class="lang-c# prettyprint-override"><code>public class NavMeshEnemy : MonoBehaviour
{
    [Header("References", order = 0)]
    [SerializeField] NavMeshAgent enemyAgent;
    [Space(10)]
    [SerializeField] float distanceObjects;
    [SerializeField] int arrayElements = 0;

    void Awake()
    {
        if(!enemyAgent) enemyAgent = GetComponent<NavMeshAgent>();
    }

    void Update()
    {
        destinations = NavMeshDestination.existingDestinations.OrderBy(d => (d.transform.position - this.transform.position).sqrMagnitude).ToArray();

        distanceObjects = Vector3.Distance(this.transform.position, destinations[arrayElements].transform.position);

        enemyAgent.destination = destinations[arrayElements].transform.position;

        CheckArray();
    }

    void CheckArray()
    {
        if (destinations[arrayElements].gameObject.activeInHierarchy == false)
        {
            if (arrayElements < destinations.Length - 1)
            {
                arrayElements++;
                enemyAgent.destination = destinos[arrayElements].transform.position;
            }
            else
            {
                arrayElements = 0;
            }
        }
    }
}
</code>```

Note however that this still won't fix your issues with no available destination. So you probably should stop the execution if the array is empty like

if(NavMeshDestination.existingDestinations.Count == 0)
{
    // Stop the enemyAgent
    return;
}
```

Body:
I'm having troubles with my enemy NavMeshAgent AI, First it searches for GameObjects tagged with "Defenses", then I set the first destination based in how close the defense is by my enemy, when the defense is destroyed, the array value is increased by one and it changes the destination to the next defense.

My problem is, my player can create (Instance) new defenses during the game, when all my defenses are destroyed, my enemy turns crazy, so, i need a way to add those new defenses to my array, below is my enemy script.

 public class NavMeshEnemy : MonoBehaviour
 {
     [Header("References", order = 0)]
     [SerializeField] NavMeshAgent enemyAgent;
     [Space(10)]
     [SerializeField] GameObject[] destinations;
     [Space(10)]
     [SerializeField] float distanceObjects;
     [SerializeField] int arrayElements = 0;

     void Awake()
     {
         enemyAgent = GetComponent<NavMeshAgent>();
         destinations = GameObject.FindGameObjectsWithTag("Defenses");
     }

     void Start()
     {
         destinations = destinations.OrderBy((d) => (d.transform.position - this.transform.position).sqrMagnitude).ToArray();
     }

     void Update()
     {
         distanceObjects = Vector3.Distance(this.transform.position, destinations[arrayElements].transform.position);

         enemyAgent.destination = destinations[arrayElements].transform.position;

         CheckArray();
     }

     void CheckArray()
     {
         if (destinations[arrayElements].gameObject.activeInHierarchy == false)
         {
             if (arrayElements < destinations.Length - 1)
             {
                 arrayElements++;
                 enemyAgent.destination = destinations[arrayElements].transform.position;
             }
             else
             {
                 arrayElements = 0;
             }
         }
     }
 }

Thank you for reading! :)

Body:
I would rather implement a component on your prefab with a static list like e.g.

public class NavMeshDestination : MonoBehaviour
{
    public static HashSet<Transform> existingDestinations = new HashSet<Transform>();

    private void Awake()
    {
       if(!existingDestinations.Contains(this)) existingDestinations.Add(this);
    }

    private void OnDestroy()
    {
        if(existingDestinations.Contains(this)) existingDestinations.Remove(this);
    }
}

And then don't even go by tag but simply do

public class NavMeshEnemy : MonoBehaviour
{
    [Header("References", order = 0)]
    [SerializeField] NavMeshAgent enemyAgent;
    [Space(10)]
    [SerializeField] float distanceObjects;
    [SerializeField] int arrayElements = 0;

    void Awake()
    {
        if(!enemyAgent) enemyAgent = GetComponent<NavMeshAgent>();
    }

    void Update()
    {
        destinations = NavMeshDestination.existingDestinations.OrderBy(d => (d.transform.position - this.transform.position).sqrMagnitude).ToArray();

        distanceObjects = Vector3.Distance(this.transform.position, destinations[arrayElements].transform.position);

        enemyAgent.destination = destinations[arrayElements].transform.position;

        CheckArray();
    }

    void CheckArray()
    {
        if (destinations[arrayElements].gameObject.activeInHierarchy == false)
        {
            if (arrayElements < destinations.Length - 1)
            {
                arrayElements++;
                enemyAgent.destination = destinos[arrayElements].transform.position;
            }
            else
            {
                arrayElements = 0;
            }
        }
    }
}

Note however that this still won't fix your issues with no available destination. So you probably should stop the execution if the array is empty like

if(NavMeshDestination.existingDestinations.Count == 0)
{
    // Stop the enemyAgent
    return;
}


问:
How to justify content within ion-item
Im trying to justify content of an ion-item in ionic4. If I set .input-wrapper { justify-content: space-around; } from the browser console I get the desired result but what's the proper way of doing it?

```<code><ion-item class="ion-justify-content-around">
  <ion-badge slot="start" class="list-badge">
    <ion-icon name="git-network-outline"></ion-icon>
  </ion-badge>
  <ion-text>Description</ion-text>
  <ion-text color="medium">500</ion-text>
</ion-item>
</code>```

答:
add the content in a div and slot it to center. like this:

```<code><ion-item class="ion-justify-content-around">
  <div slot="center" style="width: fit-content">
    <ion-badge slot="start" class="list-badge">
      <ion-icon name="git-network-outline"></ion-icon>
    </ion-badge>
    <ion-text>Description</ion-text>
    <ion-text color="medium">500</ion-text>
  </div>
</ion-item>
</code>```

Something like this.

Title: How to justify content within ion-item

Body:
Im trying to justify content of an ion-item in ionic4. If I set .input-wrapper { justify-content: space-around; } from the browser console I get the desired result but what's the proper way of doing it?

<ion-item class="ion-justify-content-around">
  <ion-badge slot="start" class="list-badge">
    <ion-icon name="git-network-outline"></ion-icon>
  </ion-badge>
  <ion-text>Description</ion-text>
  <ion-text color="medium">500</ion-text>
</ion-item>

Body:
add the content in a div and slot it to center. like this:

<ion-item class="ion-justify-content-around">
  <div slot="center" style="width: fit-content">
    <ion-badge slot="start" class="list-badge">
      <ion-icon name="git-network-outline"></ion-icon>
    </ion-badge>
    <ion-text>Description</ion-text>
    <ion-text color="medium">500</ion-text>
  </div>
</ion-item>

Something like this.


问:
AutoCompleteTextView item selection programmatically
I have an AutoCompleteTextView that is filled with cities from an sqlite database that calls an AsyncTask on item click, recently I added an option to detect my location using the gps, so the problem is I can detect the city (i.e Beirut) and set the text for the AutoCompleteTextView but the thing is that the dropdown filter opens showing Beirut (which is correct) but I still need to click on the list item to invoke the listener, how to do so programmatically

How to:

Enter the Activity (DONE)

Detect location (DONE)

set text of text view (DONE)

show textview dropdown list(DONE)

choose the item that will be returned, since it will only return one city (NOT DONE)

答:
Using the Nilton Vasques solution it can be so:

```<code>with(autoComplete) {
    setAdapter(this@YourFragment.adapter)
    setText(itemText)
    showDropDown()
    listSelection = if (itemIndex > 0) itemIndex - 1 else 0 // Because AutoCompleteTextView shows the next row.
    performCompletion()
}
</code>```

Notice, that it will show a drop-down list, otherwise listSelection won't work. If you call dismissDropDown(), the item won't be selected. If you don't want to show the drop-down list, you can use setOnTouchListener to capture opening the list, but it hardly will help (you should resolve a filtering problem).

```<code>setOnTouchListener { _, event ->
    if (event.action == MotionEvent.ACTION_DOWN) {
        showDropDown()
        listSelection = if (itemIndex > 0) itemIndex - 1 else 0
        performCompletion()
        requestFocus()
    }
    false
}
</code>```

Body:
Using the Nilton Vasques solution it can be so:

with(autoComplete) {
    setAdapter(this@YourFragment.adapter)
    setText(itemText)
    showDropDown()
    listSelection = if (itemIndex > 0) itemIndex - 1 else 0 // Because AutoCompleteTextView shows the next row.
    performCompletion()
}

Notice, that it will show a drop-down list, otherwise listSelection won't work. If you call dismissDropDown(), the item won't be selected. If you don't want to show the drop-down list, you can use setOnTouchListener to capture opening the list, but it hardly will help (you should resolve a filtering problem).

setOnTouchListener { _, event ->
    if (event.action == MotionEvent.ACTION_DOWN) {
        showDropDown()
        listSelection = if (itemIndex > 0) itemIndex - 1 else 0
        performCompletion()
        requestFocus()
    }
    false
}


问:
How to display data in blade laravel blade with html tag
I am using a WYSIWG functionality in my application which works fine. And my problem now is in displaying its data in the user side. I'm trying to use {!! !!} but has no luck on making it work. This is my two data types the first one works with {!! !!} and the other one does not:

Works

```<code><p><strong>Lorem</strong> ipsum dolor asdjfgjasfgbjgj
gjbhgjgjgjkghkj; lkfakj ;ljljfl sdfadfasfd asera
        <br>sdjfhgbkjhb jhgasfd <br><img src="https://instagram.fmnl4-
4.fna.fbcdn.net/vp/9cc3e3163fa4c45e36ba06dab80a2a8b/5D0C4134/t51.2885-
15/e35/52578723_295046217837106_4438462673106962420_n.jpg?
_nc_ht=instagram.fmnl4-4.fna.fbcdn.net" height="500" width="500"></p> <br>
jdsfa bygjhsdg jkbv kjbv lvkbsal lkjb nlknasdkfl lkjbokhbkldjskljbhjlkhkjhkl
kjlkd aslkh l<br> jhasgdf jhdgywaegrhbkihn kjb klaSNDfckhb kjaghdfjbkjh
<br>adsf knihlkh lk j ojlojjk <h1>fg lknhl kh lkuh adji3wij;oji voi npo ;
posdjfopijnpaiywer <h1>
</code>```

NOT

```<code>        <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
    <html><body><p><strong>Lorem</strong> ipsum dolor <strong>asdjfgjasfgbjgj </strong>gjbhgjgjgjkghkj; lkfakj ;ljljfl sdfadfasfd asera
                <br>sdjfhgbkjhb jhgasfd <br><img src="https://instagram.fmnl4-4.fna.fbcdn.net/vp/9cc3e3163fa4c45e36ba06dab80a2a8b/5D0C4134/t51.2885-15/e35/52578723_295046217837106_4438462673106962420_n.jpg?_nc_ht=instagram.fmnl4-4.fna.fbcdn.net" height="500" width="500"></p> <br><p> jdsfa bygjhsdg jkbv kjbv lvkbsal lkjb nlknasdkfl lkjbokhbkldjskljbhjlkhkjhkl  kjlkd aslkh l</p><p> jhasgdf jhdgywaegrhbkihn kjb klaSNDfckhb kjaghdfjbkjh </p><p>adsf knihlkh lk j ojlojjk </p><h1>fg lknhl kh lkuh adji3wij;oji voi npo ; posdjfopijnpaiywer </h1><h1></h1></body></html>
</code>```

I parsed them this way:

```<code>{!! substr($new ->content, 0, 70) !!}
</code>```

And there result is like this:

The second one is working in using the blade unescaped tag. I want them to be both displaying first 70 characters only. I'm using Laravel trumbowyg WYSIWG plugin. Someone know how to display it in blade php?

答: In order to by pass blade's limitations you should use @php  @phpend and write your plain PHP code in there.</p>

Body:
I am using a WYSIWG functionality in my application which works fine. And my problem now is in displaying its data in the user side. I'm trying to use {!! !!} but has no luck on making it work. This is my two data types the first one works with {!! !!} and the other one does not:

Works

Lorem ipsum dolor asdjfgjasfgbjgj
gjbhgjgjgjkghkj; lkfakj ;ljljfl sdfadfasfd asera

sdjfhgbkjhb jhgasfd

jdsfa bygjhsdg jkbv kjbv lvkbsal lkjb nlknasdkfl lkjbokhbkldjskljbhjlkhkjhkl
kjlkd aslkh l
 jhasgdf jhdgywaegrhbkihn kjb klaSNDfckhb kjaghdfjbkjh

adsf knihlkh lk j ojlojjk
fg lknhl kh lkuh adji3wij;oji voi npo ;
posdjfopijnpaiywer

NOT

        <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

Lorem ipsum dolor asdjfgjasfgbjgj gjbhgjgjgjkghkj; lkfakj ;ljljfl sdfadfasfd asera

sdjfhgbkjhb jhgasfd

 jdsfa bygjhsdg jkbv kjbv lvkbsal lkjb nlknasdkfl lkjbokhbkldjskljbhjlkhkjhkl  kjlkd aslkh l

 jhasgdf jhdgywaegrhbkihn kjb klaSNDfckhb kjaghdfjbkjh

adsf knihlkh lk j ojlojjk

fg lknhl kh lkuh adji3wij;oji voi npo ; posdjfopijnpaiywer

I parsed them this way:

{!! substr($new ->content, 0, 70) !!}

And there result is like this:

The second one is working in using the blade unescaped tag. I want them to be both displaying first 70 characters only. I'm using Laravel trumbowyg WYSIWG plugin. Someone know how to display it in blade php?


问:
PowerBI - Join DirectQuery and Imported tables in DAX
I have a DirectQuery table (Weather) which is sourced from an Azure SQL server. I would like to join this with an Imported table (Buckles) from an Excel sheet sourced from SharePoint Online.

Both tables have a UID field that is made up of a concatenation between a SiteID and timestamp. The UID field is named differently for each table.

I have created a One-To-Many relationship between the two tables.

I have tried to create a new DAX table using a NATURALINNERJOIN on Weather and Buckles but I get this error:

"No common join columns detected. The join function 'NATURALINNERJOIN' requires at-least one common join column."

I am confident it is not a problem with the underlying data because I've created a new imported Excel table (Test) with a selection of the data from Weather and I'm able to successfully create the join on Test and Buckles.

Is the joining of DirectQuery and Imported tables supported? I feel like this may be a type casting issue, but as far as I can see, both UID fields are set as Text.

答:
The UID field is named differently for each table.

I suspect this may be the issue. NATURALINNERJOIN looks for matching column names
 and if the two tables have no common column names, an error is returned.

Note that if you create a calculated DAX table using a DirectQuery source, I don't think that table will still act like DirectQuery. If I understand correctly, it will materialize the calculated table into your model and DAX that references that calculated table no longer points back to the SQL server (and consequently will only update when the calculated table gets rebuilt).


问:
Updating an Activity from an AsyncTask
So I'm an iOS developer learning android, and I'm having a difficult time understanding some things. Right now I have a datamanager class. In that class it has an AsyncTask to update the data. OnPreExecute I pop an activity to show it is updating. I understand I could use extras to pass initial information to the UpdateActivity. My problem is I'm not sure how to send new information in OnProgressUpdate. Here is my code widdled down:</p>

```<code>    private class myTask extends AsyncTask<Integer,String,Void>{

    @Override
    protected void onCancelled() {
        super.onCancelled();
        isUpdating = false;
    }

    @Override
    protected Void doInBackground(Integer... params) {
        //My BG Code
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Remove updating view
        super.onPostExecute(result);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Intent myIntent = new Intent(mContext,UpdateActivity.class);
        mContext.startActivity(myIntent);
    }
}
</code>```

答:
You have two options:

1) Pass an instance of activity to your AsyncTask constructor in order to invoke some method on it:

```<code>new MyTask(this).execute();
</code>```

So, you can do:

```<code>  public MyTask (Activity activity) {
   this.activity = activity;
  }

  public void onPostExecute(...) {
   activity.someMethod();
  }
</code>```

2) Pass a Handler instance and send message from onPostExecute() to the activity.

Title: Updating an Activity from an AsyncTask

Body:
So I'm an iOS developer learning android, and I'm having a difficult time understanding some things. Right now I have a datamanager class. In that class it has an AsyncTask to update the data. OnPreExecute I pop an activity to show it is updating. I understand I could use extras to pass initial information to the UpdateActivity. My problem is I'm not sure how to send new information in OnProgressUpdate. Here is my code widdled down:

    private class myTask extends AsyncTask<Integer,String,Void>{

    @Override
    protected void onCancelled() {
        super.onCancelled();
        isUpdating = false;
    }

    @Override
    protected Void doInBackground(Integer... params) {
        //My BG Code
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Remove updating view
        super.onPostExecute(result);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Intent myIntent = new Intent(mContext,UpdateActivity.class);
        mContext.startActivity(myIntent);
    }
}

Body:
You have two options:

1) Pass an instance of activity to your AsyncTask constructor in order to invoke some method on it:

new MyTask(this).execute();

So, you can do:

  public MyTask (Activity activity) {
   this.activity = activity;
  }

  public void onPostExecute(...) {
   activity.someMethod();
  }

2) Pass a Handler instance and send message from onPostExecute() to the activity.


问:
Cannot redeclare block-scoped variable 'AppRoutes'
I am trying to achieve my angular application route to split in to 3 clear part.

App-Router Module => let it load the app scope module routes. ( at present i have 1 scope as "setup-config )

let Scope-Module take care of feature modules. ( at present i have 2 feature modules )

let the feature module take care of it's own feature components.

the reason to clarity and rescablility i am trying to achieve this. but getting an error as "Cannot redeclare block-scoped variable 'AppRoutes'."

Any one help me to sort this issue? if the way what i try is wrong, can any one please show me the correct way to achieve this?

Here is the live demo

答:
in your app.routes.ts file, you have AppRoutes as the name of your Routes array and the name of your class in the same file. Consider renaming the name of the Routes array.

```<code>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CommonModule } from '@angular/common';
import { ScopeModule } from './setup-config/setup-config.module';

const AppRoutes: Routes = [ // This is called AppRoutes

 {
    path:"",
    pathMatch:"full",
    loadChildren:() => import('./setup-config/setup-config.module').then(m => m.ScopeModule)
  }

]

@NgModule({
    declarations: [],
    imports: [
        CommonModule,
        ScopeModule,
        RouterModule.forRoot(AppRoutes, {
          scrollPositionRestoration: 'enabled',
          useHash: true
        })
    ],
    exports: []
})
export class AppRoutes { } // This is **also** called AppRoutes
</code>```

Body:
in your app.routes.ts file, you have AppRoutes as the name of your Routes array and the name of your class in the same file. Consider renaming the name of the Routes array.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CommonModule } from '@angular/common';
import { ScopeModule } from './setup-config/setup-config.module';

const AppRoutes: Routes = [ // This is called AppRoutes

 {
    path:"",
    pathMatch:"full",
    loadChildren:() => import('./setup-config/setup-config.module').then(m => m.ScopeModule)
  }

]

@NgModule({
    declarations: [],
    imports: [
        CommonModule,
        ScopeModule,
        RouterModule.forRoot(AppRoutes, {
          scrollPositionRestoration: 'enabled',
          useHash: true
        })
    ],
    exports: []
})
export class AppRoutes { } // This is **also** called AppRoutes


问:
How to disable Emacs Lisp auto-reformatting?
I absolutely despise that Emacs automatically reformats my init.el file. Every time I use the GUI to change a setting, when I look back at my init.el file, Emacs has warped all of the formatting I've done on the file (e.g. changing the indentation, moving things onto their own lines, etc.).

How do I disable this functionality?

答:
Your choice is to either avoid the customize GUI altogether (I am not
even sure that is possible because, e.g.,
packages
use them), or put something like this in your .emacs:

(custom-set-variables
 `(custom-file ,(expand-file-name "custom.el" user-emacs-directory)))

(when (file-readable-p custom-file)
  (message "ignoring and deleting `%s'!" custom-file)
  (delete-file custom-file))
```

This will make Emacs write all its custom forms to a file that you
never load and delete whenever you start Emacs.

This also means that you will have to manually move all your
customizations from custom-file to your .emacs yourself.

Body:
Your choice is to either avoid the customize GUI altogether (I am not
even sure that is possible because, e.g.,
packages
use them), or put something like this in your .emacs:

(custom-set-variables
 `(custom-file ,(expand-file-name "custom.el" user-emacs-directory)))

(when (file-readable-p custom-file)
  (message "ignoring and deleting `%s'!" custom-file)
  (delete-file custom-file))

This will make Emacs write all its custom forms to a file that you
never load and delete whenever you start Emacs.

This also means that you will have to manually move all your
customizations from custom-file to your .emacs yourself.


问:
This app is not authorized to use Firebase Authentication.Please verify that the correct package name and SHA-1 are configured in the Firebase Console
Firebase auth was working fine, the debug build suddenly started failing without any change of code, logging the folloing message

D/PhoneAuthActivity( 7392): signInWithCredential:failure:com.google.firebase.auth.FirebaseAuthException: This app is not authorized to use Firebase Authentication. Please verifythat the correct package name and SHA-1 are configured in the Firebase Console. [ App validation failed ].

The only notable action inbetween a successful login and failure is android studio upgrade.

答:
This took me two days. I tried the accepted solution (by Nabin Bhandari) but that didn't work for me. Then finally managed to do it as follows.

Go to "Build> Generate Signed Bundle/APK".

If you wish to upload app to play store select "Android App Bundle", otherwise you can use "APK". Then go next.

Now in "Key store path" click "CREATE NEW". Enter the details in dialog box. When you click "OK", you have your key files generated.

Enter the key path, password etc.

Select "debug" or "release" as desired. After this, your signed apk is generated at [project Directory]\app\debug.

Now generate SHA-1 key using (as suggested by: Nabin):

keytool -list -v -keystore KEYSTORE_PATH -alias ALIAS_NAME

Use adb install app-debug.apk to install the app in the device. Now the app will work.

Dev/Debugging Tip: Install signed APK when Run is used.

When you click run again the signed app is overwritten and you might face the problem again. So there is a need to install signed apk when Run 'app' is clicked.

Add these values to your .gradle file (Module:app):

```<code>signingConfigs{
    debug{
        keyAlias 'your key alias'
        keyPassword 'your keypassword'
        storeFile file('keystore path')
        storePassword 'your storepassword'
    }
}
</code>```

Ref: see here

Body:
This took me two days. I tried the accepted solution (by Nabin Bhandari) but that didn't work for me. Then finally managed to do it as follows.

Go to "Build> Generate Signed Bundle/APK".

If you wish to upload app to play store select "Android App Bundle", otherwise you can use "APK". Then go next.

Now in "Key store path" click "CREATE NEW". Enter the details in dialog box. When you click "OK", you have your key files generated.

Enter the key path, password etc.

Select "debug" or "release" as desired. After this, your signed apk is generated at [project Directory]\app\debug.

Now generate SHA-1 key using (as suggested by: Nabin):

keytool -list -v -keystore KEYSTORE_PATH -alias ALIAS_NAME

Use adb install app-debug.apk to install the app in the device. Now the app will work.

Dev/Debugging Tip: Install signed APK when Run is used.

When you click run again the signed app is overwritten and you might face the problem again. So there is a need to install signed apk when Run 'app' is clicked.

Add these values to your .gradle file (Module:app):

signingConfigs{
    debug{
        keyAlias 'your key alias'
        keyPassword 'your keypassword'
        storeFile file('keystore path')
        storePassword 'your storepassword'
    }
}

Ref: see here


问:
How to get the changelist number of perforce?
I managed to create an empty changelist in my perforce client workspace following the steps below :

```<code>>>> from P4 import P4,P4Exception
>>> p4 = P4()
>>> p4.connect()
P4 [ciastro@ciastromac perforce:1666] connected
>>> change = p4.fetch_change()
>>> change
{'Status': 'new', 'Client': 'ciastromac', 'User': 'ciastro', 'Change': 'new', 'Description': '<enter description here>\n'}
>>> change[ "Description" ] = "Autosubmitted 3rd changelist"
>>> p4.input = change
>>> p4.run_submit( "-i" )
</code>```

this does add a changelist but I do not get the changelist number to add files to the changelist. I need the changelist number to submit to depot as well.

答:
You don't need to define a new changelist spec at all in order to submit the default changelist.  Just do:

```<code>p4.run_submit("-d", "Autosubmitted 3rd changelist")
</code>```

If you don't provide a changelist number, p4 submit will automatically take the files from the default changelist, put them into a new numbered changelist, and submit it.  (If you supply the -d flag with a description, it will use the description instead of prompting you to edit the changelist spec.)  The output of p4 submit will tell you what number the changelist ended up with.

Body:
I managed to create an empty changelist in my perforce client workspace following the steps below :

>>> from P4 import P4,P4Exception
>>> p4 = P4()
>>> p4.connect()
P4 [ciastro@ciastromac perforce:1666] connected
>>> change = p4.fetch_change()
>>> change
{'Status': 'new', 'Client': 'ciastromac', 'User': 'ciastro', 'Change': 'new', 'Description': '<enter description here>\n'}
>>> change[ "Description" ] = "Autosubmitted 3rd changelist"
>>> p4.input = change
>>> p4.run_submit( "-i" )

this does add a changelist but I do not get the changelist number to add files to the changelist. I need the changelist number to submit to depot as well.

Body:
You don't need to define a new changelist spec at all in order to submit the default changelist.  Just do:

p4.run_submit("-d", "Autosubmitted 3rd changelist")

If you don't provide a changelist number, p4 submit will automatically take the files from the default changelist, put them into a new numbered changelist, and submit it.  (If you supply the -d flag with a description, it will use the description instead of prompting you to edit the changelist spec.)  The output of p4 submit will tell you what number the changelist ended up with.


问:
Limiting PHP's file access according to logged-in user's access permissions
I have a PHP web application (running on Apache/Linux) that, among other things, allows some browsing of local files on the web server. Since Apache is running as a special "www" user, PHP has access to everything that "www" can access, whichever user is logged into the application. </p>

<p>What is the best way to limit the access to files according to the Unix filesystem privileges for the logged-in user? Ideally, I could spawn off a new process with user ID being the logged in user, but I'm not sure if that's possible. Alternatively, is there a standard PHP library somewhere that will do the permission checking and access the files? </p>

答:
This can be accomplished via a three-step process:

Create a rewrite rule (via .htaccess or the Apache config file) to redirect all requests for your "local files" to a PHP script.

Check the authentication status of the user in the script.

Use the script to load and output the file if the user is authenticated.

Body:
I have a PHP web application (running on Apache/Linux) that, among other things, allows some browsing of local files on the web server. Since Apache is running as a special "www" user, PHP has access to everything that "www" can access, whichever user is logged into the application.

What is the best way to limit the access to files according to the Unix filesystem privileges for the logged-in user? Ideally, I could spawn off a new process with user ID being the logged in user, but I'm not sure if that's possible. Alternatively, is there a standard PHP library somewhere that will do the permission checking and access the files?


问:
IntelliJ IDEA 2020 support for webdriverio selectors
I have this kind of code:

```<code>get alcoholLink() {
    return $('a=Alcohol');
}
</code>```

which is valid webriverio selector for getting an element with text 'Alcohol'.

But IntelliJ IDEA underlines it red and displays "unexpected token" error.

Does anybody know how to tweak IntelliJ settings in order to recognize the code as valid webdriverio selector?

Thanks,
mismas

答: IDEA treats $ as jQuery and thus jQuery-CSS language is auto-injected in $() calls. And 'a=Alcohol' is not a valid CSS selector syntax - thus the error; deselecting the js: JQuery selectors language injection in Settings | Editor | Language Injections should help to get rid of the issue:

Body:
I have this kind of code:

get alcoholLink() {
    return $('a=Alcohol');
}

which is valid webriverio selector for getting an element with text 'Alcohol'.

But IntelliJ IDEA underlines it red and displays "unexpected token" error.

Does anybody know how to tweak IntelliJ settings in order to recognize the code as valid webdriverio selector?

Thanks,
mismas


答:
You have AppRoutes declared twice in your file. You should probably name one appRoutes:

```<code>const appRoutes: Routes = [{
  path:"",
  pathMatch:"full",
  loadChildren:() => import('./setup-config/setup-config.module').then(m => m.ScopeModule)
}]

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    ScopeModule,
    RouterModule.forRoot(appRoutes, {
      scrollPositionRestoration: 'enabled',
      useHash: true
    })
  ],
  exports: []
})
export class AppRoutes {}
</code>```

working stackblitz

working one with routing

Body:
I am trying to achieve my angular application route to split in to 3 clear part.

App-Router Module => let it load the app scope module routes. ( at present i have 1 scope as "setup-config )

let Scope-Module take care of feature modules. ( at present i have 2 feature modules )

let the feature module take care of it's own feature components.

the reason to clarity and rescablility i am trying to achieve this. but getting an error as "Cannot redeclare block-scoped variable 'AppRoutes'."

Any one help me to sort this issue? if the way what i try is wrong, can any one please show me the correct way to achieve this?

Here is the live demo

Body:
You have AppRoutes declared twice in your file. You should probably name one appRoutes:

const appRoutes: Routes = [{
  path:"",
  pathMatch:"full",
  loadChildren:() => import('./setup-config/setup-config.module').then(m => m.ScopeModule)
}]

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    ScopeModule,
    RouterModule.forRoot(appRoutes, {
      scrollPositionRestoration: 'enabled',
      useHash: true
    })
  ],
  exports: []
})
export class AppRoutes {}

working stackblitz

working one with routing


问:
set about:config parameter of Firefox
I am using Mozilla Firefox 5.0.
I want change value of "signed.applets.codebase_principal_support" parameter of about:config using JavaScript code.
Is it possible?</p>

答:
I cannot comment yet, so i wrote this in an answer.
Please do NOT change prefs.js, as the beginning of the file and the official website tell. You can either change user.js, which will override all settings made in about:config on startup of firefox, or use the API (i dont know much about it, look it up yourself) or simulate the access of about:config in the browser.</p>

Title: set about:config parameter of Firefox


问:
SQL Server - How to record which entries are duplicates?
I am working on a project in SQL Server to create an audit database from 3 different criteria. The 3 separate queries each work exactly how I want them to and are used to populate respective temp tables. From that I used a union to bring those 3 into one final aggregated temp table. The problem I am having is that some of my entries meet the criteria of more than one of my initial queries, creating duplicates. I want to remove these duplicates, but also be able to record that the entries came up on multiple bases.

```<code>SELECT * INTO #all_audits FROM
(SELECT * FROM #audita
UNION ALL
SELECT * FROM #auditb
UNION ALL
SELECT * FROM #auditc) as tmp
</code>```

I started by adding a column in each initial temp table with the name of the audit. This worked without a hitch to be able to tell on the union. Now I was thinking that I should add another column for audit type 2, to record the second audit that an entry was flagged on, but I'm not quite sure how to go about it. I know an update set sequence would probably work for my current format that I was thinking of.

```<code>ALTER TABLE #all_audits  ADD AuditType2 varchar(255)
</code>```

Each of these tables above shares the same primary key. Tables also each have a column "AuditType" that labels which audit they are from.

Now this is probably simple, but the code to actually perform that match and still remove duplicates is where I am stuck. Something like this?

```<code>UPDATE #all_audits
SET AuditType2 = AuditType
FROM #all_audits
WHERE Primary_Key IN
        (SELECT Primary_Key
        FROM #all_audits
        GROUP BY Primary Key HAVING COUNT(*)>1)
</code>```

答:
I would suggest creating the table as:

```<code>SELECT a.*,
       STRING_AGG(this_audit, ',') OVER (PARTITION BY primarykey) as all_audits
INTO #all_audits
FROM (SELECT a.*, 'a' as this_audit FROM #audita a
      UNION ALL
      SELECT a.*, 'b' as this_audit FROM #auditb a
      UNION ALL
      SELECT a.*, 'c' as this_audit FROM #auditc a
     ) a;
</code>```

This concatenates all the audits together, so it does not assume that a "primary key" is only in one audit.

Body:
I am working on a project in SQL Server to create an audit database from 3 different criteria. The 3 separate queries each work exactly how I want them to and are used to populate respective temp tables. From that I used a union to bring those 3 into one final aggregated temp table. The problem I am having is that some of my entries meet the criteria of more than one of my initial queries, creating duplicates. I want to remove these duplicates, but also be able to record that the entries came up on multiple bases.

SELECT * INTO #all_audits FROM
(SELECT * FROM #audita
UNION ALL
SELECT * FROM #auditb
UNION ALL
SELECT * FROM #auditc) as tmp

I started by adding a column in each initial temp table with the name of the audit. This worked without a hitch to be able to tell on the union. Now I was thinking that I should add another column for audit type 2, to record the second audit that an entry was flagged on, but I'm not quite sure how to go about it. I know an update set sequence would probably work for my current format that I was thinking of.

ALTER TABLE #all_audits  ADD AuditType2 varchar(255)

Each of these tables above shares the same primary key. Tables also each have a column "AuditType" that labels which audit they are from.

Now this is probably simple, but the code to actually perform that match and still remove duplicates is where I am stuck. Something like this?

UPDATE #all_audits
SET AuditType2 = AuditType
FROM #all_audits
WHERE Primary_Key IN
        (SELECT Primary_Key
        FROM #all_audits
        GROUP BY Primary Key HAVING COUNT(*)>1)

Body:
I would suggest creating the table as:

SELECT a.*,
       STRING_AGG(this_audit, ',') OVER (PARTITION BY primarykey) as all_audits
INTO #all_audits
FROM (SELECT a.*, 'a' as this_audit FROM #audita a
      UNION ALL
      SELECT a.*, 'b' as this_audit FROM #auditb a
      UNION ALL
      SELECT a.*, 'c' as this_audit FROM #auditc a
     ) a;

This concatenates all the audits together, so it does not assume that a "primary key" is only in one audit.


问:
Creating nested array from flat array - Data Structure
I need to create a nested array using the path as reference for the children.
E.g: 4.1 is a child of 4, 4.1.1 is a child of 4.1, 4.2 is a child of 4...
I have this flat array, with all the data and paths. How would be the best approach to create a nested array where the children are nested to its parent based on its path.

Input:

```<code>const list = [
  {
    location: 1,
    path: '4'
  },
  {
    location: 2,
    path: '4.1'
  },
  {
    location: 3,
    path: '4.1.1'
  },
  {
    location: 4,
    path: '4.1.2'
  },
  {
    location: 5,
    path: '4.2'
  },
  {
    location: 6,
    path: '4.2.1'
  },
  {
    location: 7,
    path: '4.3'
  },
  {
    location: 8,
    path: '4.3.1'
  }
];
</code>```

Output:

```<code>const  list = [
  {
    location: 1,
    path: '4',
        children: [
            {
            location: 2,
            path: '4.1',
            children: [
                {
                    location: 3,
                    path: '4.1.1'
                },
                {
                    location: 4,
                    path: '4.1.2'
                },
            ]
        },
            {
                location: 5,
                path: '4.2',
                children: [
                    {
                        location: 6,
                        path: '4.2.1'
                    },
                ]
            },
            {
                location: 7,
                path: '4.3',
                children: [
                    {
                        location: 8,
                        path: '4.3.1'
                    }
                ]
            },
        ]
  },
];
</code>```

The best approach would be something recursive.
Any suggestions for this algorithm?

答:
One way to do this is to use an intermediate index mapping paths to objects, then folding your list into a structure by looking up each node and its parent in the index.  If there is no parent, then we add it to the root object.  In the end, we return the children of our root object.  Here's some code for that:

const restructure = (list) => {
  const index = list .reduce(
    (a, {path, ...rest}) => ({...a, [path]: {path, ...rest}}),
    {}
  )

  return list .reduce((root, {path}) => {
    const node = index [path]
    const parent = index [path .split('.') .slice(0, -1) .join('.')] || root
    parent.children = [...(parent.children || []), node]
    return root
  }, {children: []}) .children
}

const list = [{location: 1, path: '4'}, {location: 2, path: '4.1' }, {location: 3, path: '4.1.1'}, {location: 4, path: '4.1.2'}, {location: 5, path: '4.2'}, {location: 6, path: '4.2.1'}, {location: 7, path: '4.3'}, {location: 8, path: '4.3.1'}]

console.log (restructure (list))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {min-height: 100% !important; top: 0}</code>```

Using the index means that we don't have to sort anything; the input can be in any order.

Finding the parent involves replacing, for instance, "4.3.1" with "4.3" and looking that up in the index.  And when we try "4", it looks up the empty string, doesn't find it and uses the root node.

If you prefer regex, you could use this slightly shorter line instead:

    const parent = index [path.replace (/(^|\.)[^.]+$/, '')] || root
```

But, you might also want to look at a more elegant technique in a recent answer on a similar question.  My answer here, gets the job done (with a bit of ugly mutation) but that answer will teach you a lot about effective software development.

Body:
I need to create a nested array using the path as reference for the children.
E.g: 4.1 is a child of 4, 4.1.1 is a child of 4.1, 4.2 is a child of 4...
I have this flat array, with all the data and paths. How would be the best approach to create a nested array where the children are nested to its parent based on its path.

Input:

const list = [
  {
    location: 1,
    path: '4'
  },
  {
    location: 2,
    path: '4.1'
  },
  {
    location: 3,
    path: '4.1.1'
  },
  {
    location: 4,
    path: '4.1.2'
  },
  {
    location: 5,
    path: '4.2'
  },
  {
    location: 6,
    path: '4.2.1'
  },
  {
    location: 7,
    path: '4.3'
  },
  {
    location: 8,
    path: '4.3.1'
  }
];

Output:

const  list = [
  {
    location: 1,
    path: '4',
        children: [
            {
            location: 2,
            path: '4.1',
            children: [
                {
                    location: 3,
                    path: '4.1.1'
                },
                {
                    location: 4,
                    path: '4.1.2'
                },
            ]
        },
            {
                location: 5,
                path: '4.2',
                children: [
                    {
                        location: 6,
                        path: '4.2.1'
                    },
                ]
            },
            {
                location: 7,
                path: '4.3',
                children: [
                    {
                        location: 8,
                        path: '4.3.1'
                    }
                ]
            },
        ]
  },
];

The best approach would be something recursive.
Any suggestions for this algorithm?

Body:
One way to do this is to use an intermediate index mapping paths to objects, then folding your list into a structure by looking up each node and its parent in the index.  If there is no parent, then we add it to the root object.  In the end, we return the children of our root object.  Here's some code for that:

const restructure = (list) => {
  const index = list .reduce(
    (a, {path, ...rest}) => ({...a, [path]: {path, ...rest}}),
    {}
  )

  return list .reduce((root, {path}) => {
    const node = index [path]
    const parent = index [path .split('.') .slice(0, -1) .join('.')] || root
    parent.children = [...(parent.children || []), node]
    return root
  }, {children: []}) .children
}

const list = [{location: 1, path: '4'}, {location: 2, path: '4.1' }, {location: 3, path: '4.1.1'}, {location: 4, path: '4.1.2'}, {location: 5, path: '4.2'}, {location: 6, path: '4.2.1'}, {location: 7, path: '4.3'}, {location: 8, path: '4.3.1'}]

console.log (restructure (list))

.as-console-wrapper {min-height: 100% !important; top: 0}

Using the index means that we don't have to sort anything; the input can be in any order.

Finding the parent involves replacing, for instance, "4.3.1" with "4.3" and looking that up in the index.  And when we try "4", it looks up the empty string, doesn't find it and uses the root node.

If you prefer regex, you could use this slightly shorter line instead:

    const parent = index [path.replace (/(^|\.)[^.]+$/, '')] || root

But, you might also want to look at a more elegant technique in a recent answer on a similar question.  My answer here, gets the job done (with a bit of ugly mutation) but that answer will teach you a lot about effective software development.


问:
Does dividing float by int always give float? C++
I been programming on C and C++ for some time, and was always sure that double dividing int gives double, or double dividing int also give double (only int by int gives int) and same with adding. I was doing my assignment and was sure that 1 + (f*f + 10) / k, where f is double and k is int would always return double.
I was using g++ -std=gnu++11 command on mac (so it's clang compiler probably) and I got tests passed (I indeed got float number as a result), but my teacher says that it not for sure that it will be float (he is using windows). Is that behavior platform specific? Is there any C++ standard that describes double on int division? Thank you!
My code:

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

int main() {
    int  N;
    double f, P = 0;
    cin >> N >> f;
    for (double k = 1; k <= N; k++){
      P += 1 + (f*f + 10) / k;
    }
    cout << P;
    return 0;
}
</code>```

答:
If an expression contains two arguments, and one is a double, and the other an int, then the type of that expression is always a double.

If an expression contains two arguments, and one is a float, and the other an int, then the type of that expression is always a float.

In many ways, the second statement is becoming anachronistic (as 64 bit int is perhaps just round the corner). Note that in your snippet you are using a double rather than a float.

Some template metaprogramming code (!) for you to show your teacher:

```<code>#include <iostream>
#include <type_traits>
int main(){
    // Will output 1 if the types are the same, 0 otherwise
    std::cout << std::is_same<decltype(int{} + double{}), double>::value;
}
</code>```

Where you can replace double and int with types of your own choosing at your leisure: what the code does is compare the type of int{} + double{} with double.

Body:
I been programming on C and C++ for some time, and was always sure that double dividing int gives double, or double dividing int also give double (only int by int gives int) and same with adding. I was doing my assignment and was sure that 1 + (f*f + 10) / k, where f is double and k is int would always return double.
I was using g++ -std=gnu++11 command on mac (so it's clang compiler probably) and I got tests passed (I indeed got float number as a result), but my teacher says that it not for sure that it will be float (he is using windows). Is that behavior platform specific? Is there any C++ standard that describes double on int division? Thank you!
My code:

#include <iostream>
using namespace std;

int main() {
    int  N;
    double f, P = 0;
    cin >> N >> f;
    for (double k = 1; k <= N; k++){
      P += 1 + (f*f + 10) / k;
    }
    cout << P;
    return 0;
}

Body:
If an expression contains two arguments, and one is a double, and the other an int, then the type of that expression is always a double.

If an expression contains two arguments, and one is a float, and the other an int, then the type of that expression is always a float.

In many ways, the second statement is becoming anachronistic (as 64 bit int is perhaps just round the corner). Note that in your snippet you are using a double rather than a float.

Some template metaprogramming code (!) for you to show your teacher:

#include <iostream>
#include <type_traits>
int main(){
    // Will output 1 if the types are the same, 0 otherwise
    std::cout << std::is_same<decltype(int{} + double{}), double>::value;
}

Where you can replace double and int with types of your own choosing at your leisure: what the code does is compare the type of int{} + double{} with double.


问:
Asynchronous Mysql connector
Do any asynchronous connectors exist for Mysql that can be used within a C or C++ application? I'm looking for something that can be plugged into a reactor pattern written in Boost.Asio.

[Edit:] Running a synchronous connector in threads is not an option.

答:
MySQL Connector/C++ is a C++ implementation of JDBC 4.0

The reference customers who use MySQL Connector/C++ are:
- OpenOffice - MySQL Workbench

Learn more: http://forums.mysql.com/read.php?167,221298

Title: Asynchronous Mysql connector

LastEditorDisplayName: Thomas Watnedal

OwnerDisplayName: MySQL Workbench

ContentLicense: CC BY-SA 2.5


问:
Prestashop 1.6 display custom field in Feature Add/Edit form
I am able to display my custom field in Feature Value Add/Edit form by overriding AdminFeaturesController and overriding initFormFeatureValue() function.

I want to do the same for Feature Add/Edit form but cannot find function to override. I tried renderForm() function but didn't work.

Which file/class/controller/function should I look into to override Feature Add/Edit form to display my custom field?

答: use $this->fields_form_override instead of $this->fields_form in the override and return parent::renderForm();


问:
Pandoc HTML to DOCX: how to correctly specify the alternative text of an image
When converting an HTML file to a DOCX file with Pandoc, I would have expected that the alt attribute of an image would be converted to the image caption (with "Image Caption" style) in a DOCX file. But this doesn't seem to be the case.

It only seems to work for me with Markdown's syntax: with ![alt text](xxx.jpg), the alt text is converted to an "Image Caption" styled element in Word.

But I don't get it to work with HTML, even a
's
 is only converted to a standard paragraph, not to an "Image Caption" style in Word.

How should it be done in HTML?

答:
In newer versions of Pandoc (e.g. 2.9.x) the alt attribute is used as the alternative text, as expected.

So ![alt text](xxx.jpg) does work perfectly now. Thanks, Pandoc team!


问:
meteor connect to remote mongodb error self signed certificate
I want to connect my meteor app to mongodb cloud in scalegrid.

```<code>MONGO_URL=mongodb://admin:PASSWORD@SG-Brain-77777.servers.mongodirector.com:27017/admin?ssl=true meteor run
</code>```

but got error like this :

```<code>W20200510-10:53:22.340(7)? (STDERR) MongoNetworkError: failed to connect to server [sg-brain-77777.servers.mongodirector.com:27017] on first connect [Error: self signed certificate
W20200510-10:53:22.340(7)? (STDERR)     at TLSSocket.onConnectSecure (_tls_wrap.js:1473:34)
W20200510-10:53:22.340(7)? (STDERR)     at TLSSocket.emit (events.js:311:20)
W20200510-10:53:22.340(7)? (STDERR)     at TLSSocket.EventEmitter.emit (domain.js:482:12)
W20200510-10:53:22.340(7)? (STDERR)     at TLSSocket._finishInit (_tls_wrap.js:916:8)
W20200510-10:53:22.340(7)? (STDERR)     at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:686:12) {
W20200510-10:53:22.340(7)? (STDERR)   name: 'MongoNetworkError',
W20200510-10:53:22.341(7)? (STDERR)   [Symbol(mongoErrorContextSymbol)]: {}
W20200510-10:53:22.341(7)? (STDERR) }]

</code>```

error happen after I add
import '../imports/api/posts'; in main.js

---- EDITED from meteor forum

I have mongodb database cluster in scalegrid, but I can't connect to it with just like this :

```<code>MONGO_URL=mongodb://admin:password@SG-Brain-77777.servers.mongodirector.com:27017/admin?ssl=true meteor run
</code>```

I tried to use simple mongo connection in terminal

```<code>mongo mongodb://admin:password@SG-Brain-77777.servers.mongodirector.com:27017/admin?ssl=true
</code>```

and stil cant connect with same error :
SSL peer certificate validation failed: self signed certificate

and I tried to make it like this :

```<code>mongo mongodb://admin:password@SG-Brain-77777.servers.mongodirector.com:27017/admin?ssl=true --ssl --sslCAFile ./.crt
</code>```

and it works!!!

the problem now, i cant add --ssl --sslCAFile ./.crt in MONGO_URL like this, because it makes error :

```<code>MONGO_URL=mongodb://admin:password@SG-Brain-77777.servers.mongodirector.com:27017/admin?ssl=true --ssl --sslCAFile ./.crt meteor run
</code>```

how to add ssl cert to mongo url?

new update I tried :

```<code>MONGO_URL=mongodb://admin:password@SG-Brain-77777.servers.mongodirector.com:27017/admin?ssl=true,ssl_ca_certs=./.crt meteor run
</code>```

and got error :

```<code>MongoNetworkError: failed to connect to server [sg-brain-77777.servers.mongodirector.com:27017] on first connect [MongoNetworkError: connection 0 to sg-brain-77777.servers.mongodirector.com:27017 closed
</code>```

答:
The Solution:

You need to specify the MongoDB SSL CA Certificate in Meteor settings.

Step by Step Guide:

Login to Scalegrid and select the cluster for your Meteor app.

Scroll to the bottom, and click Get SSL CA Cert

Copy the text into a new file private/scalegrid-cert.pem

NOTE: it's safe to commit private/scalegrid-cert.pem to your repo
  because it contains a public key. Bear in mind some .pem files
  include private keys
  and should never be added to a repo.

Add the following to your Meteor settings environment variable

```<code>  "packages": {
    "mongo": {
      "options": {
        "tls": true,
        "tlsCAFileAsset": "scalegrid-cert.pem"
      }
    }
  }
</code>```

NOTE: it's "tlsCAFileAsset": "scalegrid-cert.pem"not "tlsCAFileAsset": "private/scalegrid-cert.pem". See the docs for why.

Body:
I want to connect my meteor app to mongodb cloud in scalegrid.

MONGO_URL=mongodb://admin:PASSWORD@SG-Brain-77777.servers.mongodirector.com:27017/admin?ssl=true meteor run

but got error like this :

W20200510-10:53:22.340(7)? (STDERR) MongoNetworkError: failed to connect to server [sg-brain-77777.servers.mongodirector.com:27017] on first connect [Error: self signed certificate
W20200510-10:53:22.340(7)? (STDERR)     at TLSSocket.onConnectSecure (_tls_wrap.js:1473:34)
W20200510-10:53:22.340(7)? (STDERR)     at TLSSocket.emit (events.js:311:20)
W20200510-10:53:22.340(7)? (STDERR)     at TLSSocket.EventEmitter.emit (domain.js:482:12)
W20200510-10:53:22.340(7)? (STDERR)     at TLSSocket._finishInit (_tls_wrap.js:916:8)
W20200510-10:53:22.340(7)? (STDERR)     at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:686:12) {
W20200510-10:53:22.340(7)? (STDERR)   name: 'MongoNetworkError',
W20200510-10:53:22.341(7)? (STDERR)   [Symbol(mongoErrorContextSymbol)]: {}
W20200510-10:53:22.341(7)? (STDERR) }]

error happen after I add
import '../imports/api/posts'; in main.js

---- EDITED from meteor forum

I have mongodb database cluster in scalegrid, but I can't connect to it with just like this :

MONGO_URL=mongodb://admin:password@SG-Brain-77777.servers.mongodirector.com:27017/admin?ssl=true meteor run

I tried to use simple mongo connection in terminal

mongo mongodb://admin:password@SG-Brain-77777.servers.mongodirector.com:27017/admin?ssl=true

and stil cant connect with same error :
SSL peer certificate validation failed: self signed certificate

and I tried to make it like this :

mongo mongodb://admin:password@SG-Brain-77777.servers.mongodirector.com:27017/admin?ssl=true --ssl --sslCAFile ./.crt

and it works!!!

the problem now, i cant add --ssl --sslCAFile ./.crt in MONGO_URL like this, because it makes error :

MONGO_URL=mongodb://admin:password@SG-Brain-77777.servers.mongodirector.com:27017/admin?ssl=true --ssl --sslCAFile ./.crt meteor run

how to add ssl cert to mongo url?

new update I tried :

MONGO_URL=mongodb://admin:password@SG-Brain-77777.servers.mongodirector.com:27017/admin?ssl=true,ssl_ca_certs=./.crt meteor run

and got error :

MongoNetworkError: failed to connect to server [sg-brain-77777.servers.mongodirector.com:27017] on first connect [MongoNetworkError: connection 0 to sg-brain-77777.servers.mongodirector.com:27017 closed

Body:
The Solution:

You need to specify the MongoDB SSL CA Certificate in Meteor settings.

Step by Step Guide:

Login to Scalegrid and select the cluster for your Meteor app.

Scroll to the bottom, and click Get SSL CA Cert

Copy the text into a new file private/scalegrid-cert.pem

NOTE: it's safe to commit private/scalegrid-cert.pem to your repo
  because it contains a public key. Bear in mind some .pem files
  include private keys
  and should never be added to a repo.

Add the following to your Meteor settings environment variable

  "packages": {
    "mongo": {
      "options": {
        "tls": true,
        "tlsCAFileAsset": "scalegrid-cert.pem"
      }
    }
  }

NOTE: it's "tlsCAFileAsset": "scalegrid-cert.pem"not "tlsCAFileAsset": "private/scalegrid-cert.pem". See the docs for why.


问:
How to get JSON data by POST method with Secret code in android studio
I need to get json data response based on SECRET CODE with POST method, would you please solve my issue, thanks in advance.

I have been facing  with many problems with this POST method of Secret Code to get the JSON Response

```<code> public class MainActivity extends AppCompatActivity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView = (ListView) findViewById(R.id.listViewHeroes);

    getQuestions();
}

private void getQuestions() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(ApiInterface.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
            .build();

    ApiInterface api = retrofit.create(ApiInterface.class);

    RequestModel requestModel = new RequestModel();
    requestModel.setSecretCode("341977082");

    Call<List<ModelObjects>> call = api.getQuestions();

   call.enqueue(new Callback<List<ModelObjects>>() {
       @Override
       public void onResponse(Call<List<ModelObjects>> call, Response<List<ModelObjects>> response) {
           List<ModelObjects> questionsList = response.body();

           String[] questions = new String[questionsList.size()];

           for (int i = 0; i < questionsList.size(); i++) {
               questions[i] = questionsList.get(i).getQues_No();
           }

           listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, questions));
       }

       @Override
       public void onFailure(Call<List<ModelObjects>> call, Throwable t) {
           Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
       }
   });}}
</code>```

Here is the interface and where I am passing the URL that contains parent and extension

```<code>public interface ApiInterface {

String BASE_URL = "";

@POST("QuestionsList")
Call<List<ModelObjects>> getQuestions();}
</code>```

Here is the response Model

```<code> public class ModelObjects {
@SerializedName("Ques_No")
private String Ques_No;

public ModelObjects(String ques_No) {
    Ques_No = ques_No;
}

public String getQues_No() {
    return Ques_No;
}

public void setQues_No(String ques_No) {
    Ques_No = ques_No;
}}
</code>```

Here is the Request Model

```<code> public class RequestModel {
private String SecretCode;

public RequestModel(String secretCode) {
    SecretCode = secretCode;
}

public RequestModel() {

}

public String getSecretCode() {
    return SecretCode;
}

public void setSecretCode(String secretCode) {
    SecretCode = secretCode;
}}
</code>```

答:
Here you have defined RequestModel but you are not passing it to the api call. Post request should have body.
So specify @Body while defining the api call as below.

```<code>@POST("QuestionsList")
Call<List<ModelObjects>> getQuestions(@Body RequestModel model);
</code>```

Then while calling the getQuestion() pass the model.

```<code>RequestModel requestModel = new RequestModel();
requestModel.setSecretCode("341977082");
Call<List<ModelObjects>> call = api.getQuestions(requestModel);
</code>```

Update :
update your ModelObject as below.

```<code>public class ModelObjects {
@SerializedName("Ques_No")
String Ques_No;
@SerializedName("Question")
String Ques;
@SerializedName("Answer")
String answer;
//same for other params as well
}
</code>```

Body:
I need to get json data response based on SECRET CODE with POST method, would you please solve my issue, thanks in advance.

I have been facing  with many problems with this POST method of Secret Code to get the JSON Response

 public class MainActivity extends AppCompatActivity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView = (ListView) findViewById(R.id.listViewHeroes);

    getQuestions();
}

private void getQuestions() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(ApiInterface.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
            .build();

    ApiInterface api = retrofit.create(ApiInterface.class);

    RequestModel requestModel = new RequestModel();
    requestModel.setSecretCode("341977082");

    Call<List<ModelObjects>> call = api.getQuestions();

   call.enqueue(new Callback<List<ModelObjects>>() {
       @Override
       public void onResponse(Call<List<ModelObjects>> call, Response<List<ModelObjects>> response) {
           List<ModelObjects> questionsList = response.body();

           String[] questions = new String[questionsList.size()];

           for (int i = 0; i < questionsList.size(); i++) {
               questions[i] = questionsList.get(i).getQues_No();
           }

           listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, questions));
       }

       @Override
       public void onFailure(Call<List<ModelObjects>> call, Throwable t) {
           Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
       }
   });}}

Here is the interface and where I am passing the URL that contains parent and extension

public interface ApiInterface {

String BASE_URL = "";

@POST("QuestionsList")
Call<List<ModelObjects>> getQuestions();}

Here is the response Model

 public class ModelObjects {
@SerializedName("Ques_No")
private String Ques_No;

public ModelObjects(String ques_No) {
    Ques_No = ques_No;
}

public String getQues_No() {
    return Ques_No;
}

public void setQues_No(String ques_No) {
    Ques_No = ques_No;
}}

Here is the Request Model

 public class RequestModel {
private String SecretCode;

public RequestModel(String secretCode) {
    SecretCode = secretCode;
}

public RequestModel() {

}

public String getSecretCode() {
    return SecretCode;
}

public void setSecretCode(String secretCode) {
    SecretCode = secretCode;
}}

Body:
Here you have defined RequestModel but you are not passing it to the api call. Post request should have body.
So specify @Body while defining the api call as below.

@POST("QuestionsList")
Call<List<ModelObjects>> getQuestions(@Body RequestModel model);

Then while calling the getQuestion() pass the model.

RequestModel requestModel = new RequestModel();
requestModel.setSecretCode("341977082");
Call<List<ModelObjects>> call = api.getQuestions(requestModel);

Update :
update your ModelObject as below.

public class ModelObjects {
@SerializedName("Ques_No")
String Ques_No;
@SerializedName("Question")
String Ques;
@SerializedName("Answer")
String answer;
//same for other params as well
}


问:
How to run your tests in class level parallelism only after one of your class has finished with it's tests
I got stucked in rather unique problem and I'm sure some of you might have faced similar problem at some point.

So I have total 10 Test classes in my testNg suite and I want them to run in parallel. This is easy but the problem is one of my class lets assume class Test A, not only sets up the test data but also tests some functionality of the application, hence I can not use it under BeforeSuite or BeforeTest annotation. The Test data created via the execution of tests under this class is important for other test classes to run, hence I'm really scratching my head how to implement Class level parallelism in such a way that the parallel run only initiate after the tests under Tests A class finishes it's execution.

Summary

Class Test A

```<code>public class TestsA {

   @BeforeClass
   public setupTestClass(){
   -----some code--------
  }
  @Test
  public test1(){
 ------some code---
}
</code>```

I want this TestA class to run first and then instantiate other test classes in parallel.
Any help regarding this would be really appreciated.

Thanks

答:
I've found the solution for the above problem. All I had to do is to have two different tests configured on my testng.xml suite. 1st test will have only Test class A and the other test will have other test classes having parallelism at class level. Since under 1st test there's only one class, the tests under that class will be executed first. In my case Test Class A which is responsible to test some functionality as well as setup some data. Then the next test of your testng.xml will instantiate the other classes in parallel.

Below is how my testng.xml looks

```<code>
    <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

    <suite name="Test_Suite_Name" verbose="1" parallel="classes" thread-count="4">
        <test name="TEST_TESTCLASSA" preserve-order="true">
            <parameter name="environment" value="macos"/>
            <groups>
                <run>
                    <include name="Smoke"/>
                    <exclude name="Sanity"/>
                    <exclude name="Exclude"/>
                </run>
            </groups>
            <classes>
                <class name="testpackage.TestClassA"/>
            </classes>
        </test>
        <test name="TEST_OTHER_TESTS" preserve-order="true">
            <parameter name="environment" value="macos"/>
            <groups>
                <run>
                    <include name="Smoke"/>
                    <exclude name="Sanity"/>
                    <exclude name="Exclude"/>
                </run>
            </groups>
            <classes>
                <class name="testpackage.TestClassB"/>
                <class name ="testpackage.TestClassC"/>
                <class name="testpackage.TestClassD"/>
                <class name="testpackage.TestClassE"/>
                <class name="testpackage.TestClassF"/>
                <class name="testpackage.TestClassG"/>
            </classes>
        </test>
    </suite>
</code>```

Body:
I got stucked in rather unique problem and I'm sure some of you might have faced similar problem at some point.

So I have total 10 Test classes in my testNg suite and I want them to run in parallel. This is easy but the problem is one of my class lets assume class Test A, not only sets up the test data but also tests some functionality of the application, hence I can not use it under BeforeSuite or BeforeTest annotation. The Test data created via the execution of tests under this class is important for other test classes to run, hence I'm really scratching my head how to implement Class level parallelism in such a way that the parallel run only initiate after the tests under Tests A class finishes it's execution.

Summary

Class Test A

public class TestsA {

   @BeforeClass
   public setupTestClass(){
   -----some code--------
  }
  @Test
  public test1(){
 ------some code---
}

I want this TestA class to run first and then instantiate other test classes in parallel.
Any help regarding this would be really appreciated.

Thanks

Body:
I've found the solution for the above problem. All I had to do is to have two different tests configured on my testng.xml suite. 1st test will have only Test class A and the other test will have other test classes having parallelism at class level. Since under 1st test there's only one class, the tests under that class will be executed first. In my case Test Class A which is responsible to test some functionality as well as setup some data. Then the next test of your testng.xml will instantiate the other classes in parallel.

Below is how my testng.xml looks

    <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

    <suite name="Test_Suite_Name" verbose="1" parallel="classes" thread-count="4">
        <test name="TEST_TESTCLASSA" preserve-order="true">
            <parameter name="environment" value="macos"/>
            <groups>
                <run>
                    <include name="Smoke"/>
                    <exclude name="Sanity"/>
                    <exclude name="Exclude"/>
                </run>
            </groups>
            <classes>
                <class name="testpackage.TestClassA"/>
            </classes>
        </test>
        <test name="TEST_OTHER_TESTS" preserve-order="true">
            <parameter name="environment" value="macos"/>
            <groups>
                <run>
                    <include name="Smoke"/>
                    <exclude name="Sanity"/>
                    <exclude name="Exclude"/>
                </run>
            </groups>
            <classes>
                <class name="testpackage.TestClassB"/>
                <class name ="testpackage.TestClassC"/>
                <class name="testpackage.TestClassD"/>
                <class name="testpackage.TestClassE"/>
                <class name="testpackage.TestClassF"/>
                <class name="testpackage.TestClassG"/>
            </classes>
        </test>
    </suite>


问:
Create table with values from one column and another column without intersection
I have a table like so:

```<code>userid | clothesid
-------|-----------
  1    |   1
  1    |   3
  2    |   1
  2    |   4
  2    |   5
</code>```

What I want from this table is a table like so:

```<code>userid | clothesid
-------|-----------
  1    |   4
  1    |   5
  2    |   3
</code>```

How can I do this?

I've tried it with one entry as:

```<code>select distinct r.clothesid from table r where r.clothes not in (select r1.clothes from table r1 where r1.userid=1);
</code>```

and this returns 4,5, but I'm not sure where to proceed from here

答:
You can cross join the list of  userids and the list of clothesid to generate all combinations, and then use not exists on the original table to identify the missing rows:

```<code>select u.userid, c.clothesid
from (select distinct userid from mytable) u
cross join (select distinct clothesid from mytable) c
where not exists(
    select 1 from mytable t on t.userid = u.userid and t.clothesid = c.clothesid
)
</code>```

Body:
I have a table like so:

userid | clothesid
-------|-----------
  1    |   1
  1    |   3
  2    |   1
  2    |   4
  2    |   5

What I want from this table is a table like so:

userid | clothesid
-------|-----------
  1    |   4
  1    |   5
  2    |   3

How can I do this?

I've tried it with one entry as:

select distinct r.clothesid from table r where r.clothes not in (select r1.clothes from table r1 where r1.userid=1);

and this returns 4,5, but I'm not sure where to proceed from here

Body:
You can cross join the list of  userids and the list of clothesid to generate all combinations, and then use not exists on the original table to identify the missing rows:

select u.userid, c.clothesid
from (select distinct userid from mytable) u
cross join (select distinct clothesid from mytable) c
where not exists(
    select 1 from mytable t on t.userid = u.userid and t.clothesid = c.clothesid
)


问:
How to Verify using C# if a XML file is broken
Is there anything built in to determine if an XML file is valid. One way would be to read the entire content and verify if the string represents valid XML content. Even then, how to determine if string contains valid XML data.</p>

答:
You can try to load the XML into XML document and catch the exception.
Here is the sample code:

```<code>var doc = new XmlDocument();
try {
  doc.LoadXml(content);
} catch (XmlException e) {
  // put code here that should be executed when the XML is not valid.
}
</code>```

Hope it helps.

Body:
You can try to load the XML into XML document and catch the exception.
Here is the sample code:

var doc = new XmlDocument();
try {
  doc.LoadXml(content);
} catch (XmlException e) {
  // put code here that should be executed when the XML is not valid.
}

Hope it helps.


问:
Execution python cron job on machines that has no "pip3 install" installed on them
The below code does a simple select query .
and I need this code to be executed on other Linux machines, but they don't have pymysql istalled .
they also dont have pip3 installed .
I can install all this manually , but those machined are getting redeployed every night and so I need to find a way to automatically install all the libs needed before the script execution. </p>

<p>I thought of "Requests.txt" , but again I dont have pip3 install .
I wanted to install pip3 using "Curl" but I don't have pyCurl installed .
I was thinking maybe creating some Linux bash script and call it before execution , but I hope there is some other more convenient way
So need some help in finding a solution </p>

```<code>import pymysql

connection = pymysql.connect(host='172.0.0.10',
                         port=3333,
                         user='myDB',
                         password='********',
                         db='dbName'
                         )

def SelectFromDB(SelectLine):

# Read a single record
with connection.cursor() as cursor:
    sql = SelectLine
    try:
        result = cursor.execute(sql)
        result = cursor.fetchone()
    except pymysql.Error as e:

res = SelectFromDB("SELECT ID FROM Customers ORDER BY ID DESC LIMIT 1")[0]
print("select res is " + str(res))
</code>```

答:
What I usually do when I need to execute some scripts with crontab is to put all the required setup inside a bash script and then executing in the crontab, just before executing the Python script.

It is a very clean way to do it, and in case you need to change something in the setup you can do it directly by changing the bash script, instead of changing the crontab.

Body:
The below code does a simple select query .
and I need this code to be executed on other Linux machines, but they don't have pymysql istalled .
they also dont have pip3 installed .
I can install all this manually , but those machined are getting redeployed every night and so I need to find a way to automatically install all the libs needed before the script execution.

I thought of "Requests.txt" , but again I dont have pip3 install .
I wanted to install pip3 using "Curl" but I don't have pyCurl installed .
I was thinking maybe creating some Linux bash script and call it before execution , but I hope there is some other more convenient way
So need some help in finding a solution

import pymysql

connection = pymysql.connect(host='172.0.0.10',
                         port=3333,
                         user='myDB',
                         password='********',
                         db='dbName'
                         )

def SelectFromDB(SelectLine):

# Read a single record
with connection.cursor() as cursor:
    sql = SelectLine
    try:
        result = cursor.execute(sql)
        result = cursor.fetchone()
    except pymysql.Error as e:

res = SelectFromDB("SELECT ID FROM Customers ORDER BY ID DESC LIMIT 1")[0]
print("select res is " + str(res))