问:
Install4j Windows Gui app does not create log file

Problem

"Windows Archive" generates log file and "Windows" not.

Setup

I'm using install4j to generate a windows gui application. I only have one launcher and redirected stderr and stdout.

Then I create two media files: "Windows" and "Windows Archive".

If I use the "windows archive" type the log files are created and filed with content.
If I use the "windows" type the log files are not created.

I know that in both cases the same error happened, so there should be the same output in both cases.

Thanks in advance

答:
If the redirection files are not writable, you have to specify a location where they can be written such as

```<code>${installer:sys.localAppdataDir}\mystderr.log
</code>```

Redirection files for generated launchers are configured on the "Executable info->Redirection" step of the launcher wizard.

Body:
If the redirection files are not writable, you have to specify a location where they can be written such as

${installer:sys.localAppdataDir}\mystderr.log

Redirection files for generated launchers are configured on the "Executable info->Redirection" step of the launcher wizard.


来源: stackexchange

问:
React Redux,Updation of particular item in state
The below Reducer supposed to update quantity of particular object in state when I dispatch {"id": 14, 'quantity':3} or {"id": 14, 'quantity':2}.

```<code>
const initialState={ items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':1},{"id": 25,'quantity':1}] }

const cart =(state=initialState,action)=>{
    switch(action.type){
        case 'UPDATECART':{

             //need updating code here

                 }
        default: return state
    }
}

export default cart
</code>```

How can I update particular object in state's array, keeping other values unaltered ?

The updation function increment quantity of existing object by 1 and id will be permanent.

Proposed work flow

```<code> CURRENT STATE : items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':1},{"id": 25,'quantity':1}]
    INCOMING OBJECT : {"id": 15,'quantity':2}
    EXPECTED RESULTANT STATE : items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':3},{"id": 25,'quantity':1}]
</code>```

答:
Try:

```<code>    case UPDATE CART:
      const items = state.items;
      const {id, quantity} = INCOMINGOBJECTORPAYLOAD; // destructure new object in 1 line
      const oldQuantity = items.filter(item => item.id === id)[0].quantity

      return {
        [...items, {"id": 15,'quantity':oldQuantity+quantity}]
      };
</code>```

Please note that ...items is the 'spread' operator used to populate the array with old items (which don't need any change)

ContentLicense: CC BY-SA 4.0

Body:
The below Reducer supposed to update quantity of particular object in state when I dispatch {"id": 14, 'quantity':3} or {"id": 14, 'quantity':2}.

const initialState={ items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':1},{"id": 25,'quantity':1}] }

const cart =(state=initialState,action)=>{
    switch(action.type){
        case 'UPDATECART':{

             //need updating code here

                 }
        default: return state
    }
}

export default cart

How can I update particular object in state's array, keeping other values unaltered ?

The updation function increment quantity of existing object by 1 and id will be permanent.

Proposed work flow

 CURRENT STATE : items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':1},{"id": 25,'quantity':1}]
    INCOMING OBJECT : {"id": 15,'quantity':2}
    EXPECTED RESULTANT STATE : items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':3},{"id": 25,'quantity':1}]

Body:
Try:

    case UPDATE CART:
      const items = state.items;
      const {id, quantity} = INCOMINGOBJECTORPAYLOAD; // destructure new object in 1 line
      const oldQuantity = items.filter(item => item.id === id)[0].quantity

      return {
        [...items, {"id": 15,'quantity':oldQuantity+quantity}]
      };

Please note that ...items is the 'spread' operator used to populate the array with old items (which don't need any change)


问:
how to have multiple relations between two models in django
im new to django and was trying to create models for a youtube like website.
im trying to create models such that a user has record of:

1) playlists he has uploaded.

2) playlists he has viewed. i tried the following models:

```<code>class User(models.Model):
name=models.CharField
email=models.EmailField
password=models.CharField
isTeacher=models.BooleanField
upvotes=models.IntegerField

class Playlists(models.Model):
creator=models.ForeignKey(User, on_delete=models.CASCADE)
viewed_by=models.ManyToManyField(User, on_delete=models.CASCADE)
name=models.CharField
size=models.IntegerField
</code>```

i hope you get what i want to do. obvoiusly this scheme doesn't work. but i want to do something on similar grounds

答:
That can work, but you need to specify different values for the related_name=… parameter [Django-doc], this is the name of the relation in reverse, so you can construct such model with:

```<code>from django.conf import settings

class Playlists(models.Model):
    creator = models.ForeignKey(
        <b>settings.AUTH_USER_MODEL,</b>
        on_delete=models.CASCADE,
        <b>related_name='created_playlists'</b>
    )
    viewed_by = models.ManyToManyField(
        <b>settings.AUTH_USER_MODEL,</b>
        <b>related_name='viewed_playlists'</b>
    )
    name = models.CharField(max_length=128)
    size = models.IntegerField()</code>```

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Body:
im new to django and was trying to create models for a youtube like website.
im trying to create models such that a user has record of:

1) playlists he has uploaded.

2) playlists he has viewed. i tried the following models:

class User(models.Model):
name=models.CharField
email=models.EmailField
password=models.CharField
isTeacher=models.BooleanField
upvotes=models.IntegerField

class Playlists(models.Model):
creator=models.ForeignKey(User, on_delete=models.CASCADE)
viewed_by=models.ManyToManyField(User, on_delete=models.CASCADE)
name=models.CharField
size=models.IntegerField

i hope you get what i want to do. obvoiusly this scheme doesn't work. but i want to do something on similar grounds

Body:
That can work, but you need to specify different values for the related_name=… parameter [Django-doc], this is the name of the relation in reverse, so you can construct such model with:

from django.conf import settings

class Playlists(models.Model):
    creator = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='created_playlists'
    )
    viewed_by = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        related_name='viewed_playlists'
    )
    name = models.CharField(max_length=128)
    size = models.IntegerField()

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.


问:
how to display data from database in card ui using javascript or jquery

Hi Everyone I am newbie to web development so can you help me to solve below questions

Questions to be solved

1) suggest me best UI design to implement in web as above in image.

2) And From the database,I need to display data as above image in html by using any one of the scripting language JavaScript and Jquery. if there any other scripting language that can be used to optimize performance please suggest me with a code

Thanks in advance.

答:
Maybe, you can use underscore.js or mustache.js. You can have a card ui that is templated with mustache.js and the data is filled in the card through json file. Where that json file lives is up to you. Mostly, it can live your server and then you can do an ajax call for the data.

https://mustache.github.io/

See demo:
https://mustache.github.io/#demo

// Mustache + HTML

```<code>    <h1>{{header}}</h1>
{{#bug}}
{{/bug}}

{{#items}}
  {{#first}}
    <li><strong>{{name}}</strong></li>
  {{/first}}
  {{#link}}
    <li><a href="{{url}}">{{name}}</a></li>
  {{/link}}
{{/items}}

{{#empty}}
  <p>The list is empty.</p>
{{/empty}}

//JSON
{
"header": "Colors",
  "items": [
      {"name": "red", "first": true, "url": "#Red"},
      {"name": "green", "link": true, "url": "#Green"},
      {"name": "blue", "link": true, "url": "#Blue"}
  ],
  "empty": false
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Maybe, you can use underscore.js or mustache.js. You can have a card ui that is templated with mustache.js and the data is filled in the card through json file. Where that json file lives is up to you. Mostly, it can live your server and then you can do an ajax call for the data.

https://mustache.github.io/

See demo:
https://mustache.github.io/#demo

// Mustache + HTML

    <h1>{{header}}</h1>
{{#bug}}
{{/bug}}

{{#items}}
  {{#first}}
    <li><strong>{{name}}</strong></li>
  {{/first}}
  {{#link}}
    <li><a href="{{url}}">{{name}}</a></li>
  {{/link}}
{{/items}}

{{#empty}}
  <p>The list is empty.</p>
{{/empty}}

//JSON
{
"header": "Colors",
  "items": [
      {"name": "red", "first": true, "url": "#Red"},
      {"name": "green", "link": true, "url": "#Green"},
      {"name": "blue", "link": true, "url": "#Blue"}
  ],
  "empty": false
}


问:
How can I make two components communicate in React?
I have just started using React and I am struggling to figure out how to make 2 components communicate between each other to exchange data. For example, I am trying to build a calculator which has component buttons with their values and component input field which is supposed to display the value of the buttons. I think I can figure out how to write the code, but I am strugging to understand, how to make them know about each other?
Thank you!</p>

答:
1) Define state and handler at parent component
2) send them to 2 child components as props.
3) Once the state is changed by either of 2 child components, the changes affect immediately.
I hope this will help you.</p>


问:
How can I inspect the window object for mobile safari?
How can I inspect the window object for mobile safari?

Or more specifically window.navigator - trying to convert to string doesn't work and I can't explore it within the console either.

Thanks!

EDIT:

console.log(window.navigator);

console.log(String(window.navigator));

console.log(JSON.stringify(window.navigator));

console.log(window.navigator.serialize());

Also tried sending all these variations over the socket to the server and logging them there.

Output is either [object Navigator], "{}", or nothing

答:
There isn't a Developer Tools window in mobile safari. There is a Debug Console, which will report errors in javascript, html and css, but it is nowhere near Developer Tools you'll find in a desktop browser. This debug console doesn't allow input of javascript (although this can be done in the address bar, eg javascript:alert("hi");)

To enable the Debug Console, open the settings app, go to the Safari menu, then Developer, and then turn on the debug console. Go back to Safari, scroll to the top of the page and it will be obvious what to do to get to the Debug Console.


问:
check if Kubernetes deployment was sucessful in CI/CD pipeline
I have an AKS cluster with Kubernetes version 1.14.7.

I have build CI/CD pipelines to deploy newly created images to the cluster.

I am using kubectl apply to update a specific deployment with the new image. sometimes and for many reasons, the deployment fails, for example ImagePullBackOff.

is there a command to run after the kubectl apply command to check if the pod creation and deployment was successful?

答:
It looks like kubediff tool is a perfect match for your task:

Kubediff is a tool for Kubernetes to show you the differences between your running configuration and your version controlled configuration.

The tool can be used from the command line and as a Pod in the cluster that continuously compares YAML files in the configured repository with the current state of the cluster.

```<code>$ ./kubediff
Usage: kubediff [options] <dir/file>...

Compare yaml files in <dir> to running state in kubernetes and print the
differences.  This is useful to ensure you have applied all your changes to the
appropriate environment.  This tools runs kubectl, so unless your
~/.kube/config is configured for the correct environment, you will need to
supply the kubeconfig for the appropriate environment.
</code>```

kubediff returns the status to stdout and non-zero exit code when difference is found. You can change this behavior using command line arguments.

You may also want to check the good article about validating YAML files:

Validating Kubernetes Deployment YAMLs

Body:
It looks like kubediff tool is a perfect match for your task:

Kubediff is a tool for Kubernetes to show you the differences between your running configuration and your version controlled configuration.

The tool can be used from the command line and as a Pod in the cluster that continuously compares YAML files in the configured repository with the current state of the cluster.

$ ./kubediff
Usage: kubediff [options] <dir/file>...

Compare yaml files in <dir> to running state in kubernetes and print the
differences.  This is useful to ensure you have applied all your changes to the
appropriate environment.  This tools runs kubectl, so unless your
~/.kube/config is configured for the correct environment, you will need to
supply the kubeconfig for the appropriate environment.

kubediff returns the status to stdout and non-zero exit code when difference is found. You can change this behavior using command line arguments.

You may also want to check the good article about validating YAML files:

Validating Kubernetes Deployment YAMLs


问:
can't change value by key
I'm new to JavaScript. I have a tree structure and I want to change "tags" property value from an array of strings to a string when the array length is bigger than 5.

```<code>ChangeTags(obj) {
    Object.keys(obj).forEach(key => {
      (key === 'tags' && obj[key].length > 5) && obj["tags"] = "some value" ||
      (obj[key] && typeof obj[key] === 'object') && this.removeEmptyNodes(obj[key]);
    });
    return obj;
  };
</code>```

The interpreter does not allow me to do the assignment in the 4th line. What am I doing wrong?

答:
This is invalid JavaScript:

```<code>(key === 'tags' && obj[key].length > 5) && obj["tags"] = "some value"
</code>```

The left-side of an assignment must be a variable or an object property.

It seems you are attempting to set obj.tags to "some value" when its array length is greater than 5. Here is a valid way to accomplish that:

```<code>(key === 'tags' && obj[key].length > 5) && (obj["tags"] = "some value")
</code>```

By surrounding obj["tags"] = "some value" with parentheses, the left-side of the assignment becomes simply obj["tags"], which is an object property.

Title: can't change value by key

Body:
I'm new to JavaScript. I have a tree structure and I want to change "tags" property value from an array of strings to a string when the array length is bigger than 5.

ChangeTags(obj) {
    Object.keys(obj).forEach(key => {
      (key === 'tags' && obj[key].length > 5) && obj["tags"] = "some value" ||
      (obj[key] && typeof obj[key] === 'object') && this.removeEmptyNodes(obj[key]);
    });
    return obj;
  };

The interpreter does not allow me to do the assignment in the 4th line. What am I doing wrong?

Body:
This is invalid JavaScript:

(key === 'tags' && obj[key].length > 5) && obj["tags"] = "some value"

The left-side of an assignment must be a variable or an object property.

It seems you are attempting to set obj.tags to "some value" when its array length is greater than 5. Here is a valid way to accomplish that:

(key === 'tags' && obj[key].length > 5) && (obj["tags"] = "some value")

By surrounding obj["tags"] = "some value" with parentheses, the left-side of the assignment becomes simply obj["tags"], which is an object property.


问:
VSCode Terminal suggestions not autocompleted
VSCode's PowerShell Terminal now offers a kind of suggestion in gray of what you might be wanting to type (presumably from the history?):

But there seems to be no way to actually accept the suggestion: pressing tab just does the normal PowerShell autocomplete (usually of a cmdlet or path).

What is this feature and can I "tab" to get the command tantilisingly shown?

答:
For me it was Shift + RightArrow.

If you have EditMode VI enabled, then make sure to define whatever key combination you would like to use for this to SelectForwardChar. To set SelectForwardChar to Shift + RightArrow insert the following line of code into your VSCode PowerShell Profile:

```<code>Set-PSReadLineKeyHandler -Key Shift+RightArrow -Function SelectForwardChar
</code>```

Body:
For me it was Shift + RightArrow.

If you have EditMode VI enabled, then make sure to define whatever key combination you would like to use for this to SelectForwardChar. To set SelectForwardChar to Shift + RightArrow insert the following line of code into your VSCode PowerShell Profile:

Set-PSReadLineKeyHandler -Key Shift+RightArrow -Function SelectForwardChar


问:
Split Comma separated Strings into Rows using Bigquery
I'm trying to split a column that contains Strings separated by commas into rows

Input -

Expected Output -

i tried using REGEXP_EXTRACT_ALL but wasn't able to get the above output

答:
Below is for BigQuery Standard SQL

```<code>#standardSQL
SELECT * EXCEPT(c) REPLACE(c AS country)
FROM `project.dataset.table`,
UNNEST(SPLIT(country)) c
</code>```

If to apply to sample data from your question as in below example

```<code>#standardSQL
WITH `project.dataset.table` AS (
  SELECT 'asia' region, 'india,china,japan' country, 100 revenue, 0.3 weight UNION ALL
  SELECT 'europe', 'uk,france,germany,italy', 75, 0.25
)
SELECT * EXCEPT(c) REPLACE(c AS country)
FROM `project.dataset.table`,
UNNEST(SPLIT(country)) c
</code>```

result is

```<code>Row region  country revenue weight
1   asia    india   100     0.3
2   asia    china   100     0.3
3   asia    japan   100     0.3
4   europe  uk      75      0.25
5   europe  france  75      0.25
6   europe  germany 75      0.25
7   europe  italy   75      0.25
</code>```

Body:
Below is for BigQuery Standard SQL

#standardSQL
SELECT * EXCEPT(c) REPLACE(c AS country)
FROM `project.dataset.table`,
UNNEST(SPLIT(country)) c

If to apply to sample data from your question as in below example

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 'asia' region, 'india,china,japan' country, 100 revenue, 0.3 weight UNION ALL
  SELECT 'europe', 'uk,france,germany,italy', 75, 0.25
)
SELECT * EXCEPT(c) REPLACE(c AS country)
FROM `project.dataset.table`,
UNNEST(SPLIT(country)) c

result is

Row region  country revenue weight
1   asia    india   100     0.3
2   asia    china   100     0.3
3   asia    japan   100     0.3
4   europe  uk      75      0.25
5   europe  france  75      0.25
6   europe  germany 75      0.25
7   europe  italy   75      0.25


问:
Why is Windows not considered suitable for real time systems/high performance servers?
I hope this question isn't too subjective, but why is Windows considered an unsuitable operating system for real time systems and high performance servers? Are there any technical papers or studies that gauge it's performance compared to *nix alternatives?

I've never actually heard any explanation of why developers are against using Windows for these types of systems, aside from the extremely common 'Windows is not a real time operating system' statement, as if it's some kind of well known fact that doesn't need to be justified.

Note that I'm asking about Windows CE/Windows Server, not the desktop versions of the operating system.

答:
Windows has a long-standing reputation about that, based primarily upon isolated bad experiences (everyone has a few, don't they?) which persists through major revisions that obsolete old reasons. Unfortunately, the vast majority of system administrators have never seen any of the performance tuning documents freely available from Microsoft, and even fewer have bothered to tune their systems appropriately.

Real-time critical systems can work on Windows. Look at call center solutions, for example - this is one of my areas of expertise, and I oversee several dozen servers doing exactly this. These machines can have hundreds of lines simultaneously processing voice recognition and speech synthesis at the same time, communicating with databases and programmable call routing systems. Delays in responding to the telephone company's equipment can cause some or all of those calls to be dropped or call quality to degrade severely. We still have to implement antivirus and other security measures, and these systems run.

The most important things you need to do are:
* Eliminate periodic automated jobs and processes, like checking for and applying updates, disk maintenance (such as defrag operations and cleanup) and full scans, and move them to regularly scheduled downtime for maintenance.
* Have enough memory so the system doesn't get bogged down with swapping
* Put your swap on its own partition so fragmentation doesn't interfere with the swapfile (some of my systems don't have this and still work)
* Work with the antivirus vendor to fine-tune their product such that it interferes with your server(s) as little as possible while still providing adequate protection - most antivirus software is meant for desktop use, not server use, and will require tuning
* Tune your group / local security policies

In the end, UN*X systems can have the same problems if you don't administer them properly: Scheduled jobs, inadequate swap configuration, and intrusive 3rd party security software. They also get overlooked when it comes to security so often that it's no more surprising when they are compromised than when a Windows server is compromised.

You've got to have balance. Both platforms can be equally mismanaged, and both platforms can be well-tuned. If you're talking primarily to UN*X platform people, well, they have reasons they like their platform and have a lot of bias against Windows and you'll get answers that reflect that. If you're talking to Microsoft people, you'll get the same from their angle.

The most important thing when you're choosing the platform should be vendor support for the APPLICATION you're running - which one are they more invested in, and which one have they favored in their development? What has been proven to work the best, and what will continue to be available in the future?


问:
ANDROID: Lifecycle not working properly when clicking notification from lockscreen
When We Click on LockScreen Notification, This lifecycle gets triggered.

```<code>2020-05-20 19:19:09.983 4091-4091/com.android.wikipediaassignment D/BANANA: onResume
2020-05-20 19:19:10.032 4091-4091/com.android.wikipediaassignment D/BANANA: onPause
2020-05-20 19:19:10.099 4091-4091/com.android.wikipediaassignment D/BANANA: onStop
2020-05-20 19:19:11.859 4091-4091/com.android.wikipediaassignment D/BANANA: onStart
2020-05-20 19:19:11.863 4091-4091/com.android.wikipediaassignment D/BANANA: onResume
</code>```

as far as I know, only onStart and onResume must be triggered.

```<code>private void func2() {
        Intent intent = prepareLaunchIntent3(getContext());
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 0,
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        Notification n = new Notification.Builder(getContext(), "789798789").setOngoing(true).setSmallIcon(R.drawable.go_icon).setAutoCancel(false)

                .setContentTitle("2").setContentIntent(pendingIntent).build();

        NotificationChannel channel = new NotificationChannel("789798789", "gf", NotificationManager.IMPORTANCE_DEFAULT);
        channel.setDescription("d");
        channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = getContext().getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
        notificationManager.notify(11355,n);
    }
</code>```

答: This is pretty common. When the phone is unlocked and your app is in front you will often get a barrage of calls (often more than one) to onResume(), onPause(), onStop() and onStart(). Your app should be able to handle this.

Body:
When We Click on LockScreen Notification, This lifecycle gets triggered.

2020-05-20 19:19:09.983 4091-4091/com.android.wikipediaassignment D/BANANA: onResume
2020-05-20 19:19:10.032 4091-4091/com.android.wikipediaassignment D/BANANA: onPause
2020-05-20 19:19:10.099 4091-4091/com.android.wikipediaassignment D/BANANA: onStop
2020-05-20 19:19:11.859 4091-4091/com.android.wikipediaassignment D/BANANA: onStart
2020-05-20 19:19:11.863 4091-4091/com.android.wikipediaassignment D/BANANA: onResume

as far as I know, only onStart and onResume must be triggered.

private void func2() {
        Intent intent = prepareLaunchIntent3(getContext());
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 0,
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        Notification n = new Notification.Builder(getContext(), "789798789").setOngoing(true).setSmallIcon(R.drawable.go_icon).setAutoCancel(false)

                .setContentTitle("2").setContentIntent(pendingIntent).build();

        NotificationChannel channel = new NotificationChannel("789798789", "gf", NotificationManager.IMPORTANCE_DEFAULT);
        channel.setDescription("d");
        channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = getContext().getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
        notificationManager.notify(11355,n);
    }


问:
Is it possible to Update the Build Definition name using YAML in Azure Pipelines
I am trying to update Build definition name based on the YAML runtime parameters. I am able to achieve this like below

```<code>name: ${{ parameters.source }} to ${{ parameters.target }} $(Date:yyyyMMdd).$(Rev:r)
</code>```

But I want to update the build name by providing conditional expressions.
Please let me know if this can be achieved.

答:
You can reference the documentation that describes how to set the run (build) number.

If defining your own variable, My.Variable, reference it the run number as:

```<code>$(Build.DefinitionName)_$(Build.DefinitionVersion)_$(Build.RequestedFor)_$(Build.BuildId)_$(My.Variable)
</code>```

Body:
I am trying to update Build definition name based on the YAML runtime parameters. I am able to achieve this like below

name: ${{ parameters.source }} to ${{ parameters.target }} $(Date:yyyyMMdd).$(Rev:r)

But I want to update the build name by providing conditional expressions.
Please let me know if this can be achieved.

Body:
You can reference the documentation that describes how to set the run (build) number.

If defining your own variable, My.Variable, reference it the run number as:

$(Build.DefinitionName)_$(Build.DefinitionVersion)_$(Build.RequestedFor)_$(Build.BuildId)_$(My.Variable)


问:
How can I get the link of an image from inside the tag in XML java
I am trying to read an XML file and store the value between the tags as a String. But for one tag <picture url="https://cloudstor.aarnet.edu.au/plus/s/62e0uExNviPanZE/download"/>

I need to get the URL of the image and store it so that I can use it in future.

I used

```<code>File stocks = new File("gui.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        dbFactory.setIgnoringElementContentWhitespace(true);
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(stocks);
        doc.getDocumentElement().normalize();
        System.out.println("root of xml file" + doc.getDocumentElement().getNodeName());
        NodeList nodes = doc.getElementsByTagName("billboard");
        System.out.println("==========================");
        Node node = nodes.item(0);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;
             //message = getValue("message", element);
             information = getValue("information", element).trim();
            String picture = getValue("picture url=", element);
        }
private static String getValue(String tag, Element element) {
    NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
    Node node = (Node) nodes.item(0);
    return node.getNodeValue();
}
</code>```

This would work for getting information out of normal tags, such as the information tag here. any idea how can I make it work for the picture tag.

<billboard class="nodarken">

              <information>
                     Billboard with an information tag and nothing else. Note that the text is word-wrapped. The quick brown fox jumped over the lazy dogs.
              </information>
              <picture url="https://cloudstor.aarnet.edu.au/plus/s/62e0uExNviPanZE/download"/>

       </billboard>```

答:
use <link><![CDATA[ your url goes here ]]></link> this format

<billboard class="nodarken">

              <information>
                     Billboard with an information tag and nothing else. Note that the text is word-wrapped. The quick brown fox jumped over the lazy dogs.
              </information>
              <picture><![CDATA[ https://cloudstor.aarnet.edu.au/plus/s/62e0uExNviPanZE/download"]]></picture>

       </billboard>```

Body:
I am trying to read an XML file and store the value between the tags as a String. But for one tag <picture url="https://cloudstor.aarnet.edu.au/plus/s/62e0uExNviPanZE/download"/>

I need to get the URL of the image and store it so that I can use it in future.

I used

File stocks = new File("gui.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        dbFactory.setIgnoringElementContentWhitespace(true);
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(stocks);
        doc.getDocumentElement().normalize();
        System.out.println("root of xml file" + doc.getDocumentElement().getNodeName());
        NodeList nodes = doc.getElementsByTagName("billboard");
        System.out.println("==========================");
        Node node = nodes.item(0);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;
             //message = getValue("message", element);
             information = getValue("information", element).trim();
            String picture = getValue("picture url=", element);
        }
private static String getValue(String tag, Element element) {
    NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
    Node node = (Node) nodes.item(0);
    return node.getNodeValue();
}

This would work for getting information out of normal tags, such as the information tag here. any idea how can I make it work for the picture tag.

<billboard class="nodarken">

              <information>
                     Billboard with an information tag and nothing else. Note that the text is word-wrapped. The quick brown fox jumped over the lazy dogs.
              </information>
              <picture url="https://cloudstor.aarnet.edu.au/plus/s/62e0uExNviPanZE/download"/>

       </billboard>


问:
How to remove the first character of a variable
HI All,

In my js file i am getting an array of records (negetive values ) like this

```<code>deletedDetailIds = $.map(eformDetailIds, function(e) { return e < 0 ? e : null; });
</code>```

For example the deletedDetailIds = -1234,-1235,-1256 like this.

Now i have to create an array and add these values with out negetive symbols. like

newArray = 1234,1235,1256.

Please help me in this

答:
Is this what you're looking for?</p>

```<code>deletedDetailIds = $.map(eformDetailIds, function(e) {
    return e < 0 ? Math.abs(e) : null;
})
</code>```

Body:
HI All,

In my js file i am getting an array of records (negetive values ) like this

deletedDetailIds = $.map(eformDetailIds, function(e) { return e < 0 ? e : null; });

For example the deletedDetailIds = -1234,-1235,-1256 like this.

Now i have to create an array and add these values with out negetive symbols. like

newArray = 1234,1235,1256.

Please help me in this

Body:
Is this what you're looking for?

deletedDetailIds = $.map(eformDetailIds, function(e) {
    return e < 0 ? Math.abs(e) : null;
})


问:
python script to convert nucleotide sequence in table to fasta format
I have performed ancestral sequence reconstructions to determine the nucleotide sequence for each node of a given phylogenetic tree. The output file is a table with the most probable nucleotide at each position for each node (see below):

```<code>#output file:
node_name, position, nucleotide
node1, 1, A
node1, 2, T
node1, 3, G
....
node2, 1, A
node2, 2, T
node2, 3, G
...
</code>```

I would like to convert this output file into a fasta file, like this:

```<code>>node1
ATG....
>node2
ATG....
.....
</code>```

How can I do this task with a python function, with R, or with a shell script (with awk and sed commands)?

Best regards,

Gabriel

答:
In Python 3:</p>

```<code>import csv

def csv_to_fasta(csv_file, fasta_file):

    seq = {}

    with open(csv_file) as fin:
        reader = csv.DictReader(fin, skipinitialspace=True)
        for row in reader:
            node_name = row['node_name']
            if node_name not in seq:
                seq[node_name] = ''
            seq[node_name] += row['nucleotide']

    with open(fasta_file, 'w') as fout:
        for node_name, nucleotides in seq.items():
            fout.write(f'>{node_name}\n{nucleotides}\n')

</code>```

Body:
I have performed ancestral sequence reconstructions to determine the nucleotide sequence for each node of a given phylogenetic tree. The output file is a table with the most probable nucleotide at each position for each node (see below):

#output file:
node_name, position, nucleotide
node1, 1, A
node1, 2, T
node1, 3, G
....
node2, 1, A
node2, 2, T
node2, 3, G
...

I would like to convert this output file into a fasta file, like this:

>node1
ATG....
>node2
ATG....
.....

How can I do this task with a python function, with R, or with a shell script (with awk and sed commands)?

Best regards,

Gabriel

Body:
In Python 3:

import csv

def csv_to_fasta(csv_file, fasta_file):

    seq = {}

    with open(csv_file) as fin:
        reader = csv.DictReader(fin, skipinitialspace=True)
        for row in reader:
            node_name = row['node_name']
            if node_name not in seq:
                seq[node_name] = ''
            seq[node_name] += row['nucleotide']

    with open(fasta_file, 'w') as fout:
        for node_name, nucleotides in seq.items():
            fout.write(f'>{node_name}\n{nucleotides}\n')


问:
A bug when creating parameters for request.get
I'm iterating this website and try to scrape the links of news articles.
https://www.usnews.com/search?q=China%20COVID-19#gsc.tab=0&gsc.q=China%20COVID-19&gsc.page=1

First, I need to get the links of the pages, so I used this code:

```<code>def scrape(url):
    user_agent = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko'}
    request = 0
    params = {
        'q': 'China%20COVID-19',
        'gsc.tab': '0',
        'gsc.q': 'China%20COVID-19',
    }
    pagelinks = []

    myarticle = []
    for page_no in range(1,3):
        try:# to avoid "No connection adapters were found for" error
            params['gsc.page'] = page_no
            response = requests.get(url=url,
                                    headers=user_agent,
                                    params=params)
            print(response.request.url)

        except Exception as e:
            print(e)
</code>```
```<code>scrape('https://www.usnews.com/search/')
</code>```

However, the results are not correct:

```<code>https://www.usnews.com/search?q=China%252520COVID-19&gsc.tab=0&gsc.q=China%252520COVID-19&gsc.page=1
https://www.usnews.com/search?q=China%252520COVID-19&gsc.tab=0&gsc.q=China%252520COVID-19&gsc.page=2
</code>```

The expected results should like this:

```<code>https://www.usnews.com/search?q=China%20COVID-19#gsc.tab=0&gsc.q=China%20COVID-19&gsc.page=1
https://www.usnews.com/search?q=China%20COVID-19#gsc.tab=0&gsc.q=China%20COVID-19&gsc.page=2
</code>```

Could someone help me solve this bug? I'd appreciate that very much!

答:
Searching in the browser results in 'hashed' URLs (https://www.usnews.com/search#...), you need to build the URL yourself.

Passing parameters to requests via requests.get(..., params=params) creates a regular query string (https://www.usnews.com/search?...) that leads to wrong pages (always the first).

```<code>import requests
from urllib.parse import urlencode, unquote

def scrape(url):
    user_agent = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko'}
    request = 0
    url = 'https://www.usnews.com/search'
    params = {
        'q': 'China COVID-19',
        'gsc.tab': '0',
        'gsc.q': 'China COVID-19'
    }
    pagelinks = []
    myarticle = []

    for page_no in range(1,4):
        params['gsc.page'] = page_no
        _url = '%s#%s' % (url, urlencode(params))

        try:# to avoid "No connection adapters were found for" error
            response = requests.get(url=_url,
                                    headers=user_agent)
            print(_url, '>>', _url == unquote(response.request.url))

        except Exception as e:
            print(e)

scrape('https://www.usnews.com/search/')
</code>```

Output:

```<code>https://www.usnews.com/search#q=China+COVID-19&gsc.tab=0&gsc.q=China+COVID-19&gsc.page=1 >> True
https://www.usnews.com/search#q=China+COVID-19&gsc.tab=0&gsc.q=China+COVID-19&gsc.page=2 >> True
https://www.usnews.com/search#q=China+COVID-19&gsc.tab=0&gsc.q=China+COVID-19&gsc.page=3 >> True
</code>```

Body:
I'm iterating this website and try to scrape the links of news articles.
https://www.usnews.com/search?q=China%20COVID-19#gsc.tab=0&gsc.q=China%20COVID-19&gsc.page=1

First, I need to get the links of the pages, so I used this code:

def scrape(url):
    user_agent = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko'}
    request = 0
    params = {
        'q': 'China%20COVID-19',
        'gsc.tab': '0',
        'gsc.q': 'China%20COVID-19',
    }
    pagelinks = []

    myarticle = []
    for page_no in range(1,3):
        try:# to avoid "No connection adapters were found for" error
            params['gsc.page'] = page_no
            response = requests.get(url=url,
                                    headers=user_agent,
                                    params=params)
            print(response.request.url)

        except Exception as e:
            print(e)

scrape('https://www.usnews.com/search/')

However, the results are not correct:

https://www.usnews.com/search?q=China%252520COVID-19&gsc.tab=0&gsc.q=China%252520COVID-19&gsc.page=1
https://www.usnews.com/search?q=China%252520COVID-19&gsc.tab=0&gsc.q=China%252520COVID-19&gsc.page=2

The expected results should like this:

https://www.usnews.com/search?q=China%20COVID-19#gsc.tab=0&gsc.q=China%20COVID-19&gsc.page=1
https://www.usnews.com/search?q=China%20COVID-19#gsc.tab=0&gsc.q=China%20COVID-19&gsc.page=2

Could someone help me solve this bug? I'd appreciate that very much!

Body:
Searching in the browser results in 'hashed' URLs (https://www.usnews.com/search#...), you need to build the URL yourself.

Passing parameters to requests via requests.get(..., params=params) creates a regular query string (https://www.usnews.com/search?...) that leads to wrong pages (always the first).

import requests
from urllib.parse import urlencode, unquote

def scrape(url):
    user_agent = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko'}
    request = 0
    url = 'https://www.usnews.com/search'
    params = {
        'q': 'China COVID-19',
        'gsc.tab': '0',
        'gsc.q': 'China COVID-19'
    }
    pagelinks = []
    myarticle = []

    for page_no in range(1,4):
        params['gsc.page'] = page_no
        _url = '%s#%s' % (url, urlencode(params))

        try:# to avoid "No connection adapters were found for" error
            response = requests.get(url=_url,
                                    headers=user_agent)
            print(_url, '>>', _url == unquote(response.request.url))

        except Exception as e:
            print(e)

scrape('https://www.usnews.com/search/')

Output:

https://www.usnews.com/search#q=China+COVID-19&gsc.tab=0&gsc.q=China+COVID-19&gsc.page=1 >> True
https://www.usnews.com/search#q=China+COVID-19&gsc.tab=0&gsc.q=China+COVID-19&gsc.page=2 >> True
https://www.usnews.com/search#q=China+COVID-19&gsc.tab=0&gsc.q=China+COVID-19&gsc.page=3 >> True


问:
Lambda or LINQ to Sort List<Employee> by Shift, C#
I have a List of Employee that I need to filter, and I'd like to see how to do this using a lambda and/or LINQ expression.

I want to return ALL of the Employees in the List, but I want them returned in order of Shift, Lastname, and Firstname.

```<code>List<Employee> empList = GetEmployeesInOtherCode();
// ...
int MAX_SHIFT = 5;
List<string> sortedNames = new List<string>(empList.Count);
for (int i = 0; i < MAX_SHIFT; i++) {
  List<string> localShift = new List<string>();
  for (int j = 0; j < empList.Count; j++) {
    Employee e = empList[j];
    if (e.Shift == i) {
      localShift.Add(string.Format("{0}, {1}", e.Lastname, e.Firstname));
    }
  }
  localShift.Sort();
  sortedNames.AddRange(localShift.ToArray());
}
foreach (string line in sortedNames) {
  Console.WriteLine(line);
}
</code>```

EDIT: Jeez you guys are fast! What do you use to generate this stuff? Are you hand coding it, or is there a tool out there that helps?

答:
OrderBy and ThenBy:</p>

```<code>empList.OrderBy(e => e.Shift).ThenBy(e => e.LastName).ThenBy(e => e.FirstName);
</code>```

Body:
I have a List of Employee that I need to filter, and I'd like to see how to do this using a lambda and/or LINQ expression.

I want to return ALL of the Employees in the List, but I want them returned in order of Shift, Lastname, and Firstname.

List<Employee> empList = GetEmployeesInOtherCode();
// ...
int MAX_SHIFT = 5;
List<string> sortedNames = new List<string>(empList.Count);
for (int i = 0; i < MAX_SHIFT; i++) {
  List<string> localShift = new List<string>();
  for (int j = 0; j < empList.Count; j++) {
    Employee e = empList[j];
    if (e.Shift == i) {
      localShift.Add(string.Format("{0}, {1}", e.Lastname, e.Firstname));
    }
  }
  localShift.Sort();
  sortedNames.AddRange(localShift.ToArray());
}
foreach (string line in sortedNames) {
  Console.WriteLine(line);
}

EDIT: Jeez you guys are fast! What do you use to generate this stuff? Are you hand coding it, or is there a tool out there that helps?

Body:
OrderBy and ThenBy:

empList.OrderBy(e => e.Shift).ThenBy(e => e.LastName).ThenBy(e => e.FirstName);


问:
Dynamic root url structure in Vue with vue-router, route guard & Vuex
I have a vue-router that looks like this:

```<code>const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      children: [
        {
        {
          path: 'main',
          name: 'main',
          component: () => import(/* webpackChunkName: "main" */ './views/main/Main.vue'),
          children: [
            {
              path: 'dashboard',
              name: 'main-dashboard',
              component: () => import(/* webpackChunkName: "main-dashboard" */ './views/main/Dashboard.vue'),
            },
...
</code>```

There are route guards in place so that once a user is logged in they are directed to /BASE_URL/main/dashboard.

```<code>  public beforeRouteEnter(to, from, next) {
    routeGuardMain(to, from, next);
  }

  public beforeRouteUpdate(to, from, next) {
    routeGuardMain(to, from, next);
  }

const routeGuardMain = async (to, from, next) => {
  if (to.name === 'main') {
    next({ name: 'main-dashboard'});
  } else {
    next();
  }
};
</code>```

I'm storing user_id and account_id in a Vuex state and I'd like to be able to create a url structure like:

BASE_URL/<account_id>/dashboard

But I'm having trouble accessing the account_id from the store (I have getters setup to get the relevant params) and passing it as a parameter during the redirect in the route guard (its null / undefined, so I think I need to await somewhere??).

I can set up dynamic urls for paths which don't have a route guard, but not sure how to do it with them in place.

I've read through the vue-router docs, but can't work it out.

Please can anyone suggest how I can achieve the target url structure? Apologies my frontend skills are lacking and I'm new to Vue.js

Thank you!

答:
Found a solution similar to this link:

Accessing Vuex state when defining Vue-Router routes

```<code>const startRouteGuard = async (to, from, next) => {
  await dispatchCheckLoggedIn(store);
  if (readIsLoggedIn(store)) {
      if (to.path === '/login' || to.path === '/') {
        if (store.getters.userMembership.account_id === null) {
          const watcher = store.watch(store.getters.userMembership.account_id, account_id => {
            watcher(); // stop watching
            next({ name: 'main', params: { account_id: account_id}});
          });
        } else {
          const account_id = store.getters.userMembership.account_id;
          next({ name: 'main', params: { account_id: account_id}});
        }
      } else {
        next();
      }
  } else if (readIsLoggedIn(store) === false) {
    if (to.path === '/' || (to.name as string).startsWith('main')) {
      next({name: 'login'});
    } else {
      next();
    }
  }
};
</code>```

Body:
I have a vue-router that looks like this:

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      children: [
        {
        {
          path: 'main',
          name: 'main',
          component: () => import(/* webpackChunkName: "main" */ './views/main/Main.vue'),
          children: [
            {
              path: 'dashboard',
              name: 'main-dashboard',
              component: () => import(/* webpackChunkName: "main-dashboard" */ './views/main/Dashboard.vue'),
            },
...

There are route guards in place so that once a user is logged in they are directed to /BASE_URL/main/dashboard.

  public beforeRouteEnter(to, from, next) {
    routeGuardMain(to, from, next);
  }

  public beforeRouteUpdate(to, from, next) {
    routeGuardMain(to, from, next);
  }

const routeGuardMain = async (to, from, next) => {
  if (to.name === 'main') {
    next({ name: 'main-dashboard'});
  } else {
    next();
  }
};

I'm storing user_id and account_id in a Vuex state and I'd like to be able to create a url structure like:

BASE_URL/<account_id>/dashboard

But I'm having trouble accessing the account_id from the store (I have getters setup to get the relevant params) and passing it as a parameter during the redirect in the route guard (its null / undefined, so I think I need to await somewhere??).

I can set up dynamic urls for paths which don't have a route guard, but not sure how to do it with them in place.

I've read through the vue-router docs, but can't work it out.

Please can anyone suggest how I can achieve the target url structure? Apologies my frontend skills are lacking and I'm new to Vue.js

Thank you!

Body:
Found a solution similar to this link:

Accessing Vuex state when defining Vue-Router routes

const startRouteGuard = async (to, from, next) => {
  await dispatchCheckLoggedIn(store);
  if (readIsLoggedIn(store)) {
      if (to.path === '/login' || to.path === '/') {
        if (store.getters.userMembership.account_id === null) {
          const watcher = store.watch(store.getters.userMembership.account_id, account_id => {
            watcher(); // stop watching
            next({ name: 'main', params: { account_id: account_id}});
          });
        } else {
          const account_id = store.getters.userMembership.account_id;
          next({ name: 'main', params: { account_id: account_id}});
        }
      } else {
        next();
      }
  } else if (readIsLoggedIn(store) === false) {
    if (to.path === '/' || (to.name as string).startsWith('main')) {
      next({name: 'login'});
    } else {
      next();
    }
  }
};


问:
Git equivalent to TFS Shelve before trying something risky
In TFS, I used to shelve my changes as a back-up before trying something risky or experimenting with something.

If everything went okay, I just deleted the shelve. Otherwise, I unshelved the back-up and continued.

I wasn't interested in sharing those changes with anybody.

What would be the equivalent operation in Git? I'm using VS2015 with GitHub extension, by the way.

答:
The closest thing to TFVC - Shelvesets in git I feel is stash. As others have already mentioned that it has it's own disadvantages, one being that it is not branch specific. But still it is a good alternative depending on your requirement.

In Visual Studio 2019 - if you are looking for a quick way not to commit your changes to the current branch yet, and want to save your change for later, you can use stash like this.

In Team Explorer, you have two options for stash:

Stash All - creates a stash that contains all the uncommitted changes, and it also undoes all the uncommitted changes in your branch

Stash All and Keep Staged (--keep-index) - creates a stash that contains all the uncommitted changes and also keep the changes in the branch that you have already staged for a commit

To get your stash back, you can right click on your stash under Stashes section. It will give you some options:

View Changes - shows all the changes in the stash

Apply - applies the changes to the branch and it will keep the stash

Pop -  Apply the stash and finally Drop it (see Drop below)

Drop - deletes the stash

Apply and Pop options have two sub-options:

Apply/Pop and Restore Staged - applies/pops the changes to your branch and ensures that files that were staged before are staged again

Apply/Pop All as Unstaged – applies/pops the changes to your branch and it won’t stage the files that you had staged before.

Credit: Thomas Claudius Huber's article. Link again.


问:
Reverse the filter 'blur' with Javascript
In short, i've got a button, which blurs an Image on my Website. It triggers this function:

function testblur() {imga.style.filter = 'blur(80px)';}

Works perfectly fine. Now I want to have a second button to reverse the blur effect. I tried to achieve this by Setting the the filter back to Zero:

function unblur1() {imga.stlye.filter = 'blur(0px)';}

Doesn't work at all. Reloading the Image is not really an Option, because i want the Transition effect to happen. Is there a way to reverse the filter? Or another way to get the blur Animation to Play backwards?

```<code><Body>
<button onClick="testblur()">blurOn</button>
<button onClick="unblur1()">blurOff</button>
<img id="img1" class="blifterimg" src="blifter/1.jpg" alt="1">
<script>
   var imga = document.getElementById('img1');
   function testblur() {imga.style.filter = 'blur(80px)';}
   function unblur1() {imga.stlye.filter = 'blur(0px)';}
</script>
</Body>
</code>```

答:
If I am understanding correctly, you want to add a secondary button that makes the image go back to normal after the blur. You can do this by changing your second function to imga.style.filter = 'none';

EX:

```<code><!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Try it</button><br><br>
<button onclick="myFunctionTwo()">Reverse it</button><br><br>

<img id="myImg" src="img.jpg">
<script>
function myFunction() {
  document.getElementById("myImg").style.filter = "blur(80px)";
}
function myFunctionTwo() {
  document.getElementById("myImg").style.filter = "none";
}
</script>

</body>
</html>

</code>```

Body:
In short, i've got a button, which blurs an Image on my Website. It triggers this function:

function testblur() {imga.style.filter = 'blur(80px)';}

Works perfectly fine. Now I want to have a second button to reverse the blur effect. I tried to achieve this by Setting the the filter back to Zero:

function unblur1() {imga.stlye.filter = 'blur(0px)';}

Doesn't work at all. Reloading the Image is not really an Option, because i want the Transition effect to happen. Is there a way to reverse the filter? Or another way to get the blur Animation to Play backwards?

<button onClick="testblur()">blurOn</button>
<button onClick="unblur1()">blurOff</button>

Body:
If I am understanding correctly, you want to add a secondary button that makes the image go back to normal after the blur. You can do this by changing your second function to imga.style.filter = 'none';

EX:

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Try it</button><br><br>
<button onclick="myFunctionTwo()">Reverse it</button><br><br>

<img id="myImg" src="img.jpg">
<script>
function myFunction() {
  document.getElementById("myImg").style.filter = "blur(80px)";
}
function myFunctionTwo() {
  document.getElementById("myImg").style.filter = "none";
}
</script>

</body>
</html>


问:
Python: Verify Credit Card digits
I  need to implement a function called “verify” that takes a single parameter
called “number” and then checks the following rules:

The first digit must be a 4.

The fourth digit must be one greater than the fifth digit; keep in mind that these
are separated by a dash since the format is ####-####-####.

The sum of all digits must be evenly divisible by 4.

If you treat the first two digits as a two-digit number, and the seventh and eighth
digits as a two-digit number, their sum must be 100

This is what I have come up with so far:

```<code>def verify(number): # do not change this line!

  list_number=list(number.split(''))
  Check=false

# write your code here so that it verifies the card number

    if list_number[0]==4:
    if list_number[3]==list_number[5]+1:
    if list_number.sum() % 4==0:
    if int(str(list_number[0])+str(list_number[1]))+int(str(list_number[7])+str(list_number[8])) ==100:

    Check = true

    else:
    check = false

input = "4094-3460-2754" # change this as you test your function
output = verify(input) # invoke the method using a test input
print(output) # prints the output
</code>```

答:
this is what you need. each if statement in the function corresponds to condition that you have specified.</p>

```<code>def verify(number):  # do not change this line!
    number_string = number.replace("-", "")
    list_number = [int(n) for n in number_string]

    if not list_number[0] == 4:
        return False

    if not list_number[3] - list_number[4] == 1:
        return False

    if not sum(list_number) % 4 == 0:
        return False

    if not int(number_string[0:2]) + int(number_string[6:8]) == 100:
        return False

    return True

input = "4094-3460-2754"
output = verify(input)
print(output)
# True

</code>```

Title: Python: Verify Credit Card digits

Body:
I  need to implement a function called “verify” that takes a single parameter
called “number” and then checks the following rules:

The first digit must be a 4.

The fourth digit must be one greater than the fifth digit; keep in mind that these
are separated by a dash since the format is ####-####-####.

The sum of all digits must be evenly divisible by 4.

If you treat the first two digits as a two-digit number, and the seventh and eighth
digits as a two-digit number, their sum must be 100

This is what I have come up with so far:

def verify(number): # do not change this line!

  list_number=list(number.split(''))
  Check=false

# write your code here so that it verifies the card number

    if list_number[0]==4:
    if list_number[3]==list_number[5]+1:
    if list_number.sum() % 4==0:
    if int(str(list_number[0])+str(list_number[1]))+int(str(list_number[7])+str(list_number[8])) ==100:

    Check = true

    else:
    check = false

input = "4094-3460-2754" # change this as you test your function
output = verify(input) # invoke the method using a test input
print(output) # prints the output

Body:
this is what you need. each if statement in the function corresponds to condition that you have specified.

def verify(number):  # do not change this line!
    number_string = number.replace("-", "")
    list_number = [int(n) for n in number_string]

    if not list_number[0] == 4:
        return False

    if not list_number[3] - list_number[4] == 1:
        return False

    if not sum(list_number) % 4 == 0:
        return False

    if not int(number_string[0:2]) + int(number_string[6:8]) == 100:
        return False

    return True

input = "4094-3460-2754"
output = verify(input)
print(output)
# True


问:
What is difference between "npx react-native run-android" vs "react-native run-android"
What is difference between npx react-native run-android vs react-native run-android

答:
There are currently two CLIs:

@react-native-community/cli – the one used directly by react-native. That makes it a transitive dependency of your project.

react-native-cli – an optional global convenience package, which is a proxy to @react-native-community/cli and global installation helper.

The global version is no longer recommended

npx executes  either from a local node_modules/.bin, or from a central cache, installing any packages needed in order for  to run.

When you run npx ... it picks up the cli package that is part of your project dependency


问:
How to return multiple time series graphs in python?
I have quite a large dataframe which looks something like this (this is dummy data as an example as there are more than 50 countries in the data):

```<code>Date          Country    Counts
----------------------------------
2019-01-21    Italy      920182
2019-01-22    Italy      82912
2019-01-23    Italy      27213
2019-01-24    Italy      28293
2019-01-21    Belgium    373732
2019-01-22    Belgium    17363
2019-01-23    Belgium    282913
2019-01-24    Belgium    2122
2019-01-21    China      234211
2019-01-22    China      1234
2019-01-23    China      13456
2019-01-24    China      8291
</code>```

Before I was manually creating plots separately for each country in this dataframe so I could have a trend line showing the counts overtime, while also having a red line represent the total average per country. The code I used to do this for each country separately was as follows:

```<code>Italy_df = df.loc[df['Country'] == 'Italy'] #search for all Italy data
Italy_df['Count'].mean() #total mean for Italy

x = Italy_df['Date']
y = Italy_df['Counts']

fig, ax = plt.subplots()

ax.plot(x, y)
plt.axhline(y=34927.23, color='r', linestyle='--') #y is the mean calculated for all Italy counts
plt.xticks(rotation=90)
plt.title("Weekly Sim Count average in Italy")
plt.xlabel('Week')
#plt.show()

a = '2020-01-13' #Key dates area
b = '2020-02-10'

plt.axvspan(a, b, color='gray', alpha=0.2, lw=0)
plt.plot(x, y, color='blue') #trend line over time
plt.show()
</code>```

The plot that is returned for Italy looks something like this, I would like this same graph style to be returned for every country in my data set separately:

In the plots, the key dates highlighted in the grey box will remain the same for all countries however 1) the red line will change according to the countries mean and 2) The blue line will also change to represent counts.

Instead of me repeating this code to create a plot for every country, is there a way I could create a loop that would create these plots separately for all countries in the dataframe? This would save me so much time :)

Many thanks

答:
The code below should plot all the time series for each unique value in Country.

Edit: the loop below now generates a new figure for each unique value in Country.

```<code>a = datetime(2019, 1, 22) #Key dates area
b = datetime(2019, 1, 23)

for _, d in df.set_index('Date').groupby('Country'):
    fig, ax = plt.subplots()
    d['Counts'].plot()
    plt.axhline(y=d['Counts'].mean(), color='r', linestyle='--')
    plt.xticks(rotation=90)
    plt.title(f"Weekly Sim Count for {d['Country'].iat[0]}")
    plt.xlabel('Week')

    plt.axvspan(a, b, color='gray', alpha=0.2, lw=0)
    plt.legend()
    plt.show()
</code>```

Body:
I have quite a large dataframe which looks something like this (this is dummy data as an example as there are more than 50 countries in the data):

Date          Country    Counts
----------------------------------
2019-01-21    Italy      920182
2019-01-22    Italy      82912
2019-01-23    Italy      27213
2019-01-24    Italy      28293
2019-01-21    Belgium    373732
2019-01-22    Belgium    17363
2019-01-23    Belgium    282913
2019-01-24    Belgium    2122
2019-01-21    China      234211
2019-01-22    China      1234
2019-01-23    China      13456
2019-01-24    China      8291

Before I was manually creating plots separately for each country in this dataframe so I could have a trend line showing the counts overtime, while also having a red line represent the total average per country. The code I used to do this for each country separately was as follows:

Italy_df = df.loc[df['Country'] == 'Italy'] #search for all Italy data
Italy_df['Count'].mean() #total mean for Italy

x = Italy_df['Date']
y = Italy_df['Counts']

fig, ax = plt.subplots()

ax.plot(x, y)
plt.axhline(y=34927.23, color='r', linestyle='--') #y is the mean calculated for all Italy counts
plt.xticks(rotation=90)
plt.title("Weekly Sim Count average in Italy")
plt.xlabel('Week')
#plt.show()

a = '2020-01-13' #Key dates area
b = '2020-02-10'

plt.axvspan(a, b, color='gray', alpha=0.2, lw=0)
plt.plot(x, y, color='blue') #trend line over time
plt.show()

The plot that is returned for Italy looks something like this, I would like this same graph style to be returned for every country in my data set separately:

In the plots, the key dates highlighted in the grey box will remain the same for all countries however 1) the red line will change according to the countries mean and 2) The blue line will also change to represent counts.

Instead of me repeating this code to create a plot for every country, is there a way I could create a loop that would create these plots separately for all countries in the dataframe? This would save me so much time :)

Many thanks

Body:
The code below should plot all the time series for each unique value in Country.

Edit: the loop below now generates a new figure for each unique value in Country.

a = datetime(2019, 1, 22) #Key dates area
b = datetime(2019, 1, 23)

for _, d in df.set_index('Date').groupby('Country'):
    fig, ax = plt.subplots()
    d['Counts'].plot()
    plt.axhline(y=d['Counts'].mean(), color='r', linestyle='--')
    plt.xticks(rotation=90)
    plt.title(f"Weekly Sim Count for {d['Country'].iat[0]}")
    plt.xlabel('Week')

    plt.axvspan(a, b, color='gray', alpha=0.2, lw=0)
    plt.legend()
    plt.show()


问:
unindent does not match any outer indentation level error when compiling the Python code
Error:

```<code>unindent does not match any outer indentation level
</code>```

Code:

```<code>def confirmation(self):
    if WebDriverWait(self.driver, 1000).until(
EC.visibility_of_element_located((By.CLASS_NAME, 'failed'))):
        print("Checkout Failed!")

     if WebDriverWait(self.driver, 1000).until(
EC.visibility_of_element_located((By.CLASS_NAME, 'succesful'))):
        print("Checkout Succesful!")
</code>```

How can I address the error?

答:
You have a new line after .until( python is considering this a new line of code thus throwing the error. Also your second if and print have an extra space before them.

```<code>def confirmation(self):
    if WebDriverWait(self.driver, 1000).until(
        EC.visibility_of_element_located((By.CLASS_NAME, 'failed'))):
            print("Checkout Failed!")

    if WebDriverWait(self.driver, 1000).until(
      EC.visibility_of_element_located((By.CLASS_NAME, 'succesful'))):
          print("Checkout Succesful!")
</code>```

Body:
Error:

unindent does not match any outer indentation level

Code:

def confirmation(self):
    if WebDriverWait(self.driver, 1000).until(
EC.visibility_of_element_located((By.CLASS_NAME, 'failed'))):
        print("Checkout Failed!")

     if WebDriverWait(self.driver, 1000).until(
EC.visibility_of_element_located((By.CLASS_NAME, 'succesful'))):
        print("Checkout Succesful!")

How can I address the error?

Body:
You have a new line after .until( python is considering this a new line of code thus throwing the error. Also your second if and print have an extra space before them.

def confirmation(self):
    if WebDriverWait(self.driver, 1000).until(
        EC.visibility_of_element_located((By.CLASS_NAME, 'failed'))):
            print("Checkout Failed!")

    if WebDriverWait(self.driver, 1000).until(
      EC.visibility_of_element_located((By.CLASS_NAME, 'succesful'))):
          print("Checkout Succesful!")


问:
Angular Jasmine TypeError: Cannot read property 'scroll' of null
I am getting below error while running jasmine unit test in angular

Error:

TypeError: Cannot read property 'scroll' of null
    at
    at BoxComponent.ngAfterViewInit (http://localhost:9876/_karma_webpack_/src/app/components/box/box.component.ts:289:14)

// component

ngAfterViewInit() {
    document.querySelector('.form-div .form-box').scroll(0, 0);
  }

//unit test

it('should call ngAfterViewInit', () => {
    component.ngAfterViewInit();
    spyOn(document.querySelector('.form-div .form-box'), 'scroll').withArgs(0, 0).and.callThrough();
    expect(document.querySelector('.form-div .form-box').scroll).toHaveBeenCalledWith(0, 0);
    expect(component.ngAfterViewInit).toBeTruthy();
  });

// Error

TypeError: Cannot read property 'scroll' of null
    at <Jasmine>
    at BoxComponent.ngAfterViewInit (http://localhost:9876/_karma_webpack_/src/app/components/box/box.component.ts:289:14)```

答:
I tried below code and it worked

el: ElementRef

 ngAfterViewInit() {
    if (this.el && this.el.nativeElement && this.el.nativeElement.parentElement) {
      this.el.nativeElement.parentElement.scrollTop = 0;
    }
  }```


问:
ETA of Cosmos DB Autopilot being available for existing database/ARM template
When will autopilot available for existing database and containers?
When will autopilot available to be configured by ARM template?
Is there ETA for these features? We need to decide whether to wait for the official autopilot or implement it by ourselves if it takes long time before GA.</p>

答:
This is now GA, the ARM template below works for me.

Create an Azure Cosmos DB account for Core (SQL) API with autoscale


问:
filling pandas dataframe columns based on another dataframe's columns
I have a dataframe that looks like this(df):

```<code>HOUSEID    PERSONID      WHY_TRP
20000017      1            1
20000017      1            1
20000017      1            1
20000017      2            1
20000017      2            3
20000231      1            11
20000231      1            11
20000231      2            11
20000521      1            11
20000521      2            11
20000521      2            3
</code>```

Each row describes a trip made by a person. I have another dataframe of the same kind in which each row describes a person(df_p):

```<code>    HOUSEID   PERSONID
    20000017      1
    20000017      2
    20000231      1
    20000231      2
    20000521      1
    20000521      2
</code>```

I want to make three new columns in the second dataframe to show the frequency of 1, 3 and 11 for each person. basically I already have a second dataframe (df_p) with other features so I shouldn't use groupby. for some reason the first and second dataframe don't have the same number of people. that's why I needed the strategy below. This is the code I tried but took hours to complete(1 million iterations):

```<code>df_p.insert(2, 'WHY_TRP_1', 0)
df_p.insert(3, 'WHY_TRP_2', 0)
df_p.insert(4, 'WHY_TRP_3', 0)

def trip_counter(i, r):
  if r[2] == 1:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] == r[1]), ['WHY_TRP_1']] += 1
  elif r[2] == 3:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] ==  r[1]), ['WHY_TRP_3']] += 1
  elif r[2] == 11:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] ==  r[1]), ['WHY_TRP_11']] += 1

for i ,r in df.iterrows():
  trip_counter(i ,r)
</code>```

output:

```<code>     HOUSEID   PERSONID   WHY_TRP_1     WHY_TRP_3      WHY_TRP_11
    20000017      1            3            0            0
    20000017      2            1            1            0
    20000231      1            0            0            2
    20000231      2            0            0            1
    20000521      1            0            0            1
    20000521      2            0            1            1
</code>```

Is there a faster way to do this?

thank you

答:
use pd.get_dummies, .groupby().sum() and pd.merge() to get it back into the original dataframe (EDIT: I added in pd.merge logic just now to fully answer your question after taking another look. Does this answer?)

```<code>df1 = pd.get_dummies(df, columns=['WHY_TRP']).groupby(['HOUSEID', 'PERSONID']).sum().reset_index()
df2 = pd.merge(df, df1, how='left', on=['HOUSEID', 'PERSONID'])
df2
</code>```

Body:
I have a dataframe that looks like this(df):

HOUSEID    PERSONID      WHY_TRP
20000017      1            1
20000017      1            1
20000017      1            1
20000017      2            1
20000017      2            3
20000231      1            11
20000231      1            11
20000231      2            11
20000521      1            11
20000521      2            11
20000521      2            3

Each row describes a trip made by a person. I have another dataframe of the same kind in which each row describes a person(df_p):

    HOUSEID   PERSONID
    20000017      1
    20000017      2
    20000231      1
    20000231      2
    20000521      1
    20000521      2

I want to make three new columns in the second dataframe to show the frequency of 1, 3 and 11 for each person. basically I already have a second dataframe (df_p) with other features so I shouldn't use groupby. for some reason the first and second dataframe don't have the same number of people. that's why I needed the strategy below. This is the code I tried but took hours to complete(1 million iterations):

df_p.insert(2, 'WHY_TRP_1', 0)
df_p.insert(3, 'WHY_TRP_2', 0)
df_p.insert(4, 'WHY_TRP_3', 0)

def trip_counter(i, r):
  if r[2] == 1:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] == r[1]), ['WHY_TRP_1']] += 1
  elif r[2] == 3:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] ==  r[1]), ['WHY_TRP_3']] += 1
  elif r[2] == 11:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] ==  r[1]), ['WHY_TRP_11']] += 1

for i ,r in df.iterrows():
  trip_counter(i ,r)

output:

     HOUSEID   PERSONID   WHY_TRP_1     WHY_TRP_3      WHY_TRP_11
    20000017      1            3            0            0
    20000017      2            1            1            0
    20000231      1            0            0            2
    20000231      2            0            0            1
    20000521      1            0            0            1
    20000521      2            0            1            1

Is there a faster way to do this?

thank you

Body:
use pd.get_dummies, .groupby().sum() and pd.merge() to get it back into the original dataframe (EDIT: I added in pd.merge logic just now to fully answer your question after taking another look. Does this answer?)

df1 = pd.get_dummies(df, columns=['WHY_TRP']).groupby(['HOUSEID', 'PERSONID']).sum().reset_index()
df2 = pd.merge(df, df1, how='left', on=['HOUSEID', 'PERSONID'])
df2


问:
Significantly higher testing accuracy on mnist with keras than tensorflow.keras
I was verifying with a basic example my TensorFlow (v2.2.0), Cuda (10.1), and cudnn (libcudnn7-dev_7.6.5.32-1+cuda10.1_amd64.deb) and I'm getting weird results...

When running the following example in Keras as shown in https://keras.io/examples/mnist_cnn/ I get the ~99% acc @validation. When I adapt the imports run via the TensorFlow I get only 86%.

I might be forgetting something.

To run using tensorflow:

```<code>from __future__ import print_function

import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras import backend as K

batch_size = 128
num_classes = 10
epochs = 12

# input image dimensions
img_rows, img_cols = 28, 28

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = tf.keras.utils.to_categorical(y_train, num_classes)
y_test = tf.keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=tf.keras.losses.categorical_crossentropy,
              optimizer=tf.optimizers.Adadelta(),
              metrics=['accuracy'])

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
</code>```

Sadly, I get the following output:

```<code>Epoch 2/12
469/469 [==============================] - 3s 6ms/step - loss: 2.2245 - accuracy: 0.2633 - val_loss: 2.1755 - val_accuracy: 0.4447
Epoch 3/12
469/469 [==============================] - 3s 7ms/step - loss: 2.1485 - accuracy: 0.3533 - val_loss: 2.0787 - val_accuracy: 0.5147
Epoch 4/12
469/469 [==============================] - 3s 6ms/step - loss: 2.0489 - accuracy: 0.4214 - val_loss: 1.9538 - val_accuracy: 0.6021
Epoch 5/12
469/469 [==============================] - 3s 6ms/step - loss: 1.9224 - accuracy: 0.4845 - val_loss: 1.7981 - val_accuracy: 0.6611
Epoch 6/12
469/469 [==============================] - 3s 6ms/step - loss: 1.7748 - accuracy: 0.5376 - val_loss: 1.6182 - val_accuracy: 0.7039
Epoch 7/12
469/469 [==============================] - 3s 6ms/step - loss: 1.6184 - accuracy: 0.5750 - val_loss: 1.4296 - val_accuracy: 0.7475
Epoch 8/12
469/469 [==============================] - 3s 7ms/step - loss: 1.4612 - accuracy: 0.6107 - val_loss: 1.2484 - val_accuracy: 0.7719
Epoch 9/12
469/469 [==============================] - 3s 6ms/step - loss: 1.3204 - accuracy: 0.6402 - val_loss: 1.0895 - val_accuracy: 0.7945
Epoch 10/12
469/469 [==============================] - 3s 6ms/step - loss: 1.2019 - accuracy: 0.6650 - val_loss: 0.9586 - val_accuracy: 0.8097
Epoch 11/12
469/469 [==============================] - 3s 7ms/step - loss: 1.1050 - accuracy: 0.6840 - val_loss: 0.8552 - val_accuracy: 0.8216
Epoch 12/12
469/469 [==============================] - 3s 7ms/step - loss: 1.0253 - accuracy: 0.7013 - val_loss: 0.7734 - val_accuracy: 0.8337
Test loss: 0.7734305262565613
Test accuracy: 0.8337000012397766
</code>```

Nowhere near 99.25% as when I import Keras.
What am I missing?

答:
Discrepancy in optimiser parameters between keras and tensorflow.keras

So the crux of the issue lies in the different default parameters for the Adadelta optimisers in Keras and Tensorflow. Specifically, the different learning rates. We can see this with a simple check. Using the Keras version of the code, print(keras.optimizers.Adadelta().get_config()) outpus

```<code>{'learning_rate': 1.0, 'rho': 0.95, 'decay': 0.0, 'epsilon': 1e-07}
</code>```

And in the Tensorflow version, print(tf.optimizers.Adadelta().get_config() gives us

```<code>{'name': 'Adadelta', 'learning_rate': 0.001, 'decay': 0.0, 'rho': 0.95, 'epsilon': 1e-07}
</code>```

As we can see, there is a discrepancy between the learning rates for the Adadelta optimisers. Keras has a default learning rate of 1.0 while Tensorflow has a default learning rate of 0.001 (consistent with their other optimisers).

Effects of a higher learning rate

Since the Keras version of the Adadelta optimiser has a larger learning rate, it converges much faster and achieves a high accuracy within 12 epochs, while the Tensorflow Adadelta optimiser requires a longer training time. If you increased the number of training epochs, the Tensorflow model could potentially achieve a 99% accuracy as well.

The fix

But instead of increasing the training time, we can simply initialise the Tensorflow model to behave in a similar way to the Keras model by changing the learning rate of Adadelta to 1.0. i.e.

```<code>model.compile(
    loss=tf.keras.losses.categorical_crossentropy,
    optimizer=tf.optimizers.Adadelta(learning_rate=1.0), # Note the new learning rate
    metrics=['accuracy'])
</code>```

Making this change, we get the following performance running on Tensorflow:

```<code>Epoch 12/12
60000/60000 [==============================] - 102s 2ms/sample - loss: 0.0287 - accuracy: 0.9911 - val_loss: 0.0291 - val_accuracy: 0.9907
Test loss: 0.029134796149221757
Test accuracy: 0.9907
</code>```

which is close to the desired 99.25% accuracy.

p.s. Incidentally, it seems that the different default parameters between Keras and Tensorflow is a known issue that was fixed but then reverted:
https://github.com/keras-team/keras/pull/12841 software development is hard.

Body:
I was verifying with a basic example my TensorFlow (v2.2.0), Cuda (10.1), and cudnn (libcudnn7-dev_7.6.5.32-1+cuda10.1_amd64.deb) and I'm getting weird results...

When running the following example in Keras as shown in https://keras.io/examples/mnist_cnn/ I get the ~99% acc @validation. When I adapt the imports run via the TensorFlow I get only 86%.

I might be forgetting something.

To run using tensorflow:

from __future__ import print_function

import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras import backend as K

batch_size = 128
num_classes = 10
epochs = 12

# input image dimensions
img_rows, img_cols = 28, 28

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = tf.keras.utils.to_categorical(y_train, num_classes)
y_test = tf.keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=tf.keras.losses.categorical_crossentropy,
              optimizer=tf.optimizers.Adadelta(),
              metrics=['accuracy'])

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

Sadly, I get the following output:

Epoch 2/12
469/469 [==============================] - 3s 6ms/step - loss: 2.2245 - accuracy: 0.2633 - val_loss: 2.1755 - val_accuracy: 0.4447
Epoch 3/12
469/469 [==============================] - 3s 7ms/step - loss: 2.1485 - accuracy: 0.3533 - val_loss: 2.0787 - val_accuracy: 0.5147
Epoch 4/12
469/469 [==============================] - 3s 6ms/step - loss: 2.0489 - accuracy: 0.4214 - val_loss: 1.9538 - val_accuracy: 0.6021
Epoch 5/12
469/469 [==============================] - 3s 6ms/step - loss: 1.9224 - accuracy: 0.4845 - val_loss: 1.7981 - val_accuracy: 0.6611
Epoch 6/12
469/469 [==============================] - 3s 6ms/step - loss: 1.7748 - accuracy: 0.5376 - val_loss: 1.6182 - val_accuracy: 0.7039
Epoch 7/12
469/469 [==============================] - 3s 6ms/step - loss: 1.6184 - accuracy: 0.5750 - val_loss: 1.4296 - val_accuracy: 0.7475
Epoch 8/12
469/469 [==============================] - 3s 7ms/step - loss: 1.4612 - accuracy: 0.6107 - val_loss: 1.2484 - val_accuracy: 0.7719
Epoch 9/12
469/469 [==============================] - 3s 6ms/step - loss: 1.3204 - accuracy: 0.6402 - val_loss: 1.0895 - val_accuracy: 0.7945
Epoch 10/12
469/469 [==============================] - 3s 6ms/step - loss: 1.2019 - accuracy: 0.6650 - val_loss: 0.9586 - val_accuracy: 0.8097
Epoch 11/12
469/469 [==============================] - 3s 7ms/step - loss: 1.1050 - accuracy: 0.6840 - val_loss: 0.8552 - val_accuracy: 0.8216
Epoch 12/12
469/469 [==============================] - 3s 7ms/step - loss: 1.0253 - accuracy: 0.7013 - val_loss: 0.7734 - val_accuracy: 0.8337
Test loss: 0.7734305262565613
Test accuracy: 0.8337000012397766

Nowhere near 99.25% as when I import Keras.
What am I missing?

Body:
Discrepancy in optimiser parameters between keras and tensorflow.keras

So the crux of the issue lies in the different default parameters for the Adadelta optimisers in Keras and Tensorflow. Specifically, the different learning rates. We can see this with a simple check. Using the Keras version of the code, print(keras.optimizers.Adadelta().get_config()) outpus

{'learning_rate': 1.0, 'rho': 0.95, 'decay': 0.0, 'epsilon': 1e-07}

And in the Tensorflow version, print(tf.optimizers.Adadelta().get_config() gives us

{'name': 'Adadelta', 'learning_rate': 0.001, 'decay': 0.0, 'rho': 0.95, 'epsilon': 1e-07}

As we can see, there is a discrepancy between the learning rates for the Adadelta optimisers. Keras has a default learning rate of 1.0 while Tensorflow has a default learning rate of 0.001 (consistent with their other optimisers).

Effects of a higher learning rate

Since the Keras version of the Adadelta optimiser has a larger learning rate, it converges much faster and achieves a high accuracy within 12 epochs, while the Tensorflow Adadelta optimiser requires a longer training time. If you increased the number of training epochs, the Tensorflow model could potentially achieve a 99% accuracy as well.

The fix

But instead of increasing the training time, we can simply initialise the Tensorflow model to behave in a similar way to the Keras model by changing the learning rate of Adadelta to 1.0. i.e.

model.compile(
    loss=tf.keras.losses.categorical_crossentropy,
    optimizer=tf.optimizers.Adadelta(learning_rate=1.0), # Note the new learning rate
    metrics=['accuracy'])

Making this change, we get the following performance running on Tensorflow:

Epoch 12/12
60000/60000 [==============================] - 102s 2ms/sample - loss: 0.0287 - accuracy: 0.9911 - val_loss: 0.0291 - val_accuracy: 0.9907
Test loss: 0.029134796149221757
Test accuracy: 0.9907

which is close to the desired 99.25% accuracy.

p.s. Incidentally, it seems that the different default parameters between Keras and Tensorflow is a known issue that was fixed but then reverted:
https://github.com/keras-team/keras/pull/12841 software development is hard.


问:
Creating a fixed light source that preserves its world coordinates
I want to put a light in the scene that is fixed at a certain spot. Here's what the OpenGL site has to say about this:

How can I make my light stay fixed relative to my scene? How can I put a light in the corner and make it stay there while I change my view?

As your view changes, your ModelView matrix also changes. This means you'll need to respecify the light position, usually at the start of every frame. A typical application will display a frame with the following pseudocode:

Set the view transform.

*Set the light position //glLightfv(GL_LIGHT_POSITION,…)*

Send down the scene or model geometry.

Swap buffers.

If your light source is part of a light fixture, you also may need to specify a modeling transform, so the light position is in the same location as the surrounding fixture geometry.

So I added this to the paintGL() function.

```<code>glMatrixMode(GL_MODELVIEW);
glPushMatrix();
gluLookAt(0.0, 5.0, 0.0,
    0.0, 0.0, 0.0,
    0.0, 1.0, 0.0);
GLfloat l0pos[] = {0.0, 0.0, 0.0, 1.0};
glLightfv(GL_LIGHT0, GL_POSITION, l0pos);
glPopMatrix();
</code>```

It seems okay when I'm standing still, but when I move the camera's eye position or the camera's center position, the light flickers. What am I doing wrong?

Update2: I ended up using this code, but I'm still having issues. The light no longer moves, but its position isn't accurate. The matrix on top of the stack is the matrix generated by a gluLookAt command that represents the camera position.

```<code>glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(xCoordinate, yCoordinate, zCoordinate);
GLfloat lpos[] = {0.0, 0.0, 0.0, w};
glLightfv(GL_LIGHT0, GL_POSITION, lpos);
glPopMatrix();
</code>```

答:
I'm not entirely sure if this is what is causing your symptoms, however:

```<code>glMatrixMode(GL_MODELVIEW);
glPushMatrix();
gluLookAt(0.0, 5.0, 0.0,
    0.0, 0.0, 0.0,
    0.0, 1.0, 0.0);
</code>```

There are a few things you would want to look at here.

First, according to the documentation online, gluLookAt multiplies the matrix at the top of the stack by a camera transformation matrix, rather than setting it (furthermore, glPushMatrix preserves the current matrix). For this reason, it's a good idea to make sure the current matrix is the identity matrix before doing your camera transformation. A push/pop is generally enough but if you call gluLookAt after or "within" any other transformation, bad things can happen.

Second, you'll want to use your actual camera coordinates, so that GL can transform the light position properly. Otherwise the light won't appear to move with the scene geometry. I'd suggest doing gluLookAt once, then transforming lights and drawing your geometry all in one go before popping the camera transformation matrix again. That way you can be certain that your lights and geometry stay together as expected.

Body:
I want to put a light in the scene that is fixed at a certain spot. Here's what the OpenGL site has to say about this:

How can I make my light stay fixed relative to my scene? How can I put a light in the corner and make it stay there while I change my view?

As your view changes, your ModelView matrix also changes. This means you'll need to respecify the light position, usually at the start of every frame. A typical application will display a frame with the following pseudocode:

Set the view transform.

*Set the light position //glLightfv(GL_LIGHT_POSITION,…)*

Send down the scene or model geometry.

Swap buffers.

If your light source is part of a light fixture, you also may need to specify a modeling transform, so the light position is in the same location as the surrounding fixture geometry.

So I added this to the paintGL() function.

glMatrixMode(GL_MODELVIEW);
glPushMatrix();
gluLookAt(0.0, 5.0, 0.0,
    0.0, 0.0, 0.0,
    0.0, 1.0, 0.0);
GLfloat l0pos[] = {0.0, 0.0, 0.0, 1.0};
glLightfv(GL_LIGHT0, GL_POSITION, l0pos);
glPopMatrix();

It seems okay when I'm standing still, but when I move the camera's eye position or the camera's center position, the light flickers. What am I doing wrong?

Update2: I ended up using this code, but I'm still having issues. The light no longer moves, but its position isn't accurate. The matrix on top of the stack is the matrix generated by a gluLookAt command that represents the camera position.

glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(xCoordinate, yCoordinate, zCoordinate);
GLfloat lpos[] = {0.0, 0.0, 0.0, w};
glLightfv(GL_LIGHT0, GL_POSITION, lpos);
glPopMatrix();

Body:
I'm not entirely sure if this is what is causing your symptoms, however:

glMatrixMode(GL_MODELVIEW);
glPushMatrix();
gluLookAt(0.0, 5.0, 0.0,
    0.0, 0.0, 0.0,
    0.0, 1.0, 0.0);

There are a few things you would want to look at here.

First, according to the documentation online, gluLookAt multiplies the matrix at the top of the stack by a camera transformation matrix, rather than setting it (furthermore, glPushMatrix preserves the current matrix). For this reason, it's a good idea to make sure the current matrix is the identity matrix before doing your camera transformation. A push/pop is generally enough but if you call gluLookAt after or "within" any other transformation, bad things can happen.

Second, you'll want to use your actual camera coordinates, so that GL can transform the light position properly. Otherwise the light won't appear to move with the scene geometry. I'd suggest doing gluLookAt once, then transforming lights and drawing your geometry all in one go before popping the camera transformation matrix again. That way you can be certain that your lights and geometry stay together as expected.


问:
TypeScript error when I perform addition to a number and pass as a prop?
I have a heading component which takes a level as a prop:

In Heading.tsx

```<code>type Props = {
  level?: 1 | 2 | 3 | 4 | 5 | 6;
  children: string;
};
</code>```

My other component needs to add a number to a prop it's given, and make that the level:

In MyComponent.tsx:

```<code>type Props = {
  componentLevel: 1 | 2 | 3;
};

const MyComponent = ({ componentLevel }) => (
  <Heading level={componentLevel + 1}>My Component Heading text</Heading>
)
</code>```

Logically I can see that Heading will always get the props that it needs, however TypeScript gives me an error:

TS2322: Type 'number' is not assignable to type '1 | 2 | 3 | 4 | 5 | 6'.

答:
You have some good answers already but I believe in this case you may be best to try and clearly delimit which values are possible; you aren't able to have typescript compute the possible types more specifically than number through the addition, so realistically the best you can do is:

type ComponentLevel = 1 | 2 | 3 | 4 | 5 | 6;
type HeadingLevel = 2 | 3 | 4 | 6 | 6 | 7;

const componentToHeadingLevel: (c: ComponentLevel) => HeadingLevel = c => c + 1 as HeadingLevel;
```

You might want to think of the type number as 1 | 2 | 3... etc. and so really we're just clearly defining what we want in the type.

Body:
I have a heading component which takes a level as a prop:

In Heading.tsx

type Props = {
  level?: 1 | 2 | 3 | 4 | 5 | 6;
  children: string;
};

My other component needs to add a number to a prop it's given, and make that the level:

In MyComponent.tsx:

type Props = {
  componentLevel: 1 | 2 | 3;
};

const MyComponent = ({ componentLevel }) => (
  <Heading level={componentLevel + 1}>My Component Heading text</Heading>
)

Logically I can see that Heading will always get the props that it needs, however TypeScript gives me an error:

TS2322: Type 'number' is not assignable to type '1 | 2 | 3 | 4 | 5 | 6'.

Body:
You have some good answers already but I believe in this case you may be best to try and clearly delimit which values are possible; you aren't able to have typescript compute the possible types more specifically than number through the addition, so realistically the best you can do is:

type ComponentLevel = 1 | 2 | 3 | 4 | 5 | 6;
type HeadingLevel = 2 | 3 | 4 | 6 | 6 | 7;

const componentToHeadingLevel: (c: ComponentLevel) => HeadingLevel = c => c + 1 as HeadingLevel;

You might want to think of the type number as 1 | 2 | 3... etc. and so really we're just clearly defining what we want in the type.


问:
Reading multiple ints from the same line in Kotlin?
I am doing the 30 Days of Code in Kotlin on Hackerrank and I am stuck at Day 7.

How do you read multiple integers on a single line?

How is it added to an array and displayed in reverse?

I have solved it in Java but lack the syntax needed in Kotlin

Input:

4

1 4 3 2

My Code:

```<code>fun main(args: Array<String>) {

   val n = readLine()!!.toInt()
   var arr = Array(n)
   for(i in 0 until n)
   {
      arr[i] = readLine()!!.toInt() //Not Working? nor does readLine()!!.split(' ').toInt()

   }
   for(item in arr.size - 1 downTo 0)
   {
      print("${item} ")
   }
}
</code>```

答:
Actually, you can refer to the official Kotlin tutorial: https://kotlinlang.org/docs/tutorials/competitive-programming.html

as mentioned in tutorial:

To make reading the input in competitive programming tasks like this more concise, you can have the following list of helper input-reading functions:

```<code>private fun readLn() = readLine()!! // string line
private fun readInt() = readLn().toInt() // single int
private fun readStrings() = readLn().split(" ") // list of strings
private fun readInts() = readStrings().map { it.toInt() } // list of ints
</code>```

for your case, you can try use as below:

```<code>fun main() {
    val n = readInt()
    val x = readInts()
    for (j in x.reversed()) {
        print(j); print(" ")
    }
    println()
}

private fun readLn() = readLine()!! // string line
private fun readInt() = readLn().toInt() // single int
private fun readStrings() = readLn().split(" ") // list of strings
private fun readInts() = readStrings().map { it.toInt() } // list of ints
</code>```

Body:
I am doing the 30 Days of Code in Kotlin on Hackerrank and I am stuck at Day 7.

How do you read multiple integers on a single line?

How is it added to an array and displayed in reverse?

I have solved it in Java but lack the syntax needed in Kotlin

Input:

4

1 4 3 2

My Code:

fun main(args: Array<String>) {

   val n = readLine()!!.toInt()
   var arr = Array(n)
   for(i in 0 until n)
   {
      arr[i] = readLine()!!.toInt() //Not Working? nor does readLine()!!.split(' ').toInt()

   }
   for(item in arr.size - 1 downTo 0)
   {
      print("${item} ")
   }
}

Body:
Actually, you can refer to the official Kotlin tutorial: https://kotlinlang.org/docs/tutorials/competitive-programming.html

as mentioned in tutorial:

To make reading the input in competitive programming tasks like this more concise, you can have the following list of helper input-reading functions:

private fun readLn() = readLine()!! // string line
private fun readInt() = readLn().toInt() // single int
private fun readStrings() = readLn().split(" ") // list of strings
private fun readInts() = readStrings().map { it.toInt() } // list of ints

for your case, you can try use as below:

fun main() {
    val n = readInt()
    val x = readInts()
    for (j in x.reversed()) {
        print(j); print(" ")
    }
    println()
}

private fun readLn() = readLine()!! // string line
private fun readInt() = readLn().toInt() // single int
private fun readStrings() = readLn().split(" ") // list of strings
private fun readInts() = readStrings().map { it.toInt() } // list of ints


问:
react-bootstrap-table: hand over parent function to rowEvent
I have a bootstrap table, and want to open a modal once a row is clicked. The row event is triggered, however the parent function within the row event, which I use to open the modal, is not triggered. It seems that I can access the props in this object, since I get the console output below. Why is the function not triggered?

```<code>const rowEvents = {
onClick: (e, row, rowIndex) => {
  console.log("row event triggered, here is my function:", this.props)
  this.props.onClickShowModal
}}

<BootstrapTable { ...props.baseProps } hover={true} striped={true} { ...paginationTableProps } rowEvents={rowEvents}/>
</code>```

console output:

```<code>row event triggered, here is my function: {onClickShowModal: ƒ}
</code>```

答:
it works now, when I add the parentheses at the end. I assume that this is needed, so that the function is handed over, and not an object, but I dont understand the difference yet.</p>

```<code> const rowEvents = {
    onClick: (e, row, rowIndex) => {
      this.props.onClickShowModal()
      }
    }
</code>```

Body:
I have a bootstrap table, and want to open a modal once a row is clicked. The row event is triggered, however the parent function within the row event, which I use to open the modal, is not triggered. It seems that I can access the props in this object, since I get the console output below. Why is the function not triggered?

const rowEvents = {
onClick: (e, row, rowIndex) => {
  console.log("row event triggered, here is my function:", this.props)
  this.props.onClickShowModal
}}

<BootstrapTable { ...props.baseProps } hover={true} striped={true} { ...paginationTableProps } rowEvents={rowEvents}/>

console output:

row event triggered, here is my function: {onClickShowModal: ƒ}

Body:
it works now, when I add the parentheses at the end. I assume that this is needed, so that the function is handed over, and not an object, but I dont understand the difference yet.

 const rowEvents = {
    onClick: (e, row, rowIndex) => {
      this.props.onClickShowModal()
      }
    }