问:
change stylesheet by button click for specific element only
So, this question is based on a piece of homework that I'm currently working on. I was provided with an HTML document and two stylesheets. The HTML document is really simple:

```<code><html>
<head>
   <title>DOM-scripting: change style</title>
   <link rel="stylesheet" href="style/style1.css" id="stylesheet"/>
</head>
<body>
    <nav class="chooseStyle">
        <input type="button" id="style1Button" value="Style 1"/>
        <input type="button" id="style2Button" value="Style 2"/>
    </nav>
    <article>
        <h1>Style change using DOM-scripting</h1>
        <p> sample text </p>
        <p> sample text </p>
        <p> sample text </p>
    </article>
    <nav class="links">
        <ul>
            <li><a href="link">school name</a></li>
            <li><a href="link">school name</a></li>
       </nav>

    <script src="scriptToUse.js"></script>
</body>
</html>
</code>```

style1.css consists of the following:

```<code>body {
    background-color: #676632;
}

input[type="button"] {
    color: #F5F265;
    background-color: #9B9302;
}

article {
    margin-left: 150px;
    margin-right: 150px;
    text-indent: 20px;
    color: #C9C892;
}

h1 {
    color: #EEF1BA;
    text-align: center;
}

a {
    color: #A1FA56;
    text-decoration: none;
    font-weight: bold;
}

ul {
    padding: 0;
}

li {
    list-style-type: none;
}
</code>```

Style2.css consists of the following:

```<code>body {
    color: #EEEEAA;
}

input[type="button"] {
    color: #9B9302;
    background-color: #F5F265;
}

article {
    margin-left: auto;
    margin-right: auto;
    text-align: justify;

    color: #A3A163;
}

h1 {
    color: #AAAA66;
    text-align: left;
}

a {
    color: #CDCF9B;
}

ul {
    padding: 0;
}

li {
    list-style-type: none;
}
</code>```

The first part of the exercise states that I need to create a javascript file which allows the stylesheet for the webpage to change according to the button that was clicked. The first button refers to the first stylesheet and the second refers to the second stylesheet. I figured this out fairly easy and everything works fine.

However, the second part of the exercise states the following: "Now edit the javascript file so that only the style of the article is changed when the buttons are clicked. DO NOT edit the CSS file." Meaning that the href for the stylesheets should still be changed, like in the first part, but now it may only affect the style of the article element instead of the style of the whole page.

I have been searching for related questions for the past hour but nothing seems to really provide a solution. I have read some questions stating that it is impossible to apply a stylesheet only to a specific element without changing anything in the stylesheet itself. Keep in mind that I am only in my first year of college and have only just begun learning javascript, meaning that a solution should not be that hard to find. I guess?

The Javascript code I wrote so far:

```<code>'use strict';

const handleLoad = () => {
    let style1 = document.getElementById('style1Button');
    let style2 = document.getElementById('style2Button');
    style1.addEventListener('click', handleClick);
    style2.addEventListener('click', handleClick);
};

const handleClick = (event) => {
    if(event.target.value === "Style 1") {
        document.getElementById("stylesheet").href = "style/style1.css";
        // should only change article style
        // currently still referring to the whole document
    } else {
        document.getElementById("stylesheet").href = "style/style2.css";
        // should also only change article style
        // also still referring to the whole document
    }
};

window.addEventListener('load', handleLoad);
</code>```

Is there any way I could block the CSS rules for all elements except the article element? Or maybe change the classes or ID's for the elements that should not be affected?

Thanks a lot in advance :)

This is what finally solved it. (code is probably not as compact and correct as it could be but it works so I'm more than happy :D):

```<code>'use strict';

const handleLoad = () => {
    let style1 = document.getElementById('style1Button');
    let style2 = document.getElementById('style2Button');
    style1.addEventListener('click', handleClick);
    style2.addEventListener('click', handleClick);
    makeShadow();
};

const handleClick = (event) => {
    let article = document.querySelector('article');
    let shadow = article.shadowRoot;

    let style = event.target.value === "Style 1" ? "style/style2.css" : "style/style1.css";

    for(let node of shadow.childNodes) {
        if(node.hasAttribute('href')){
            node.href = style;
        }
    }
};

const makeShadow = () => {
    let article = document.querySelector('article');
    let articleClone = makeClone(article);

    let shadow = article.attachShadow({mode:'open'});

    let link = document.createElement('link');
    link.rel = "stylesheet";
    link.href = 'style/style1.css';

    shadow.appendChild(articleClone);
    shadow.prepend(link);
};

const makeClone = (article) => {
    let clone = article.cloneNode();
    clone.innerHTML = article.innerHTML;
    return clone;
};

window.addEventListener('load', handleLoad);
</code>```

答:
Very very simple example for you.  You said it was new in Javascript. That's why I'm giving you an example that's so easy to understand. In fact, a more logical solution can be produced by looping around the buttons, figuring out which button they are on, defining the elements that need to be changed according to it, but this is the simplest example at this stage. You'll have to investigate and learn for yourself. Good Luck!

const style1Button = document.getElementById("style1Button");
style1Button.addEventListener("click", styleArticle);

function styleArticle(e) {
  let article = document.getElementById("article"); // full article
  // with querySelector, you can access the elements in the main element in this way.
  article.querySelector(".article-title").style.color = "red";
  article.querySelector(".text1").style.color = "blue";
  article.querySelector(".text2").style.color = "orange";
  article.querySelector(".text3").style.color = "gray";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="chooseStyle">
  <input type="button" id="style1Button" value="Style 1" />
  <input type="button" id="style2Button" value="Style 2" />
</nav>
<article id="article">.
  <!-- you can add a class or id to each of them to get specific with javascript. -->

  <h1 class="article-title">Style change using DOM-scripting</h1>
  <p class="text1"> sample text </p>
  <p class="text2"> sample text </p>
  <p class="text3"> sample text </p>
</article>
<nav class="links">
  <ul>
    <li>school name</li>
    <li>school name</li>
</nav></code>```

Updated Answer :

I think you just made a letter mistake.

```<code> const handleLoad = () => {
      let style1 = document.getElementById('style1Button');
      let style2 = document.getElementById('style2Button');
      style1.addEventListener('click', handleClick);
      style2.addEventListener('click', handleClick);
    }

    //handleclick to --- handleClick
    const handleClick = (event) => {
      if (event.target.value === "Style 1") {
        document.getElementById("styleSheet").href = "style/style.css";
        // should only change article style
        // currently still referring to the whole document
      } else {
        document.getElementById("styleSheet").href = "style/style2.css";
        // should also only change article style
        // also still referring to the whole document
      }
    };

    window.addEventListener('load', handleLoad);
</code>```

Body:
So, this question is based on a piece of homework that I'm currently working on. I was provided with an HTML document and two stylesheets. The HTML document is really simple:

   <title>DOM-scripting: change style</title>
   <link rel="stylesheet" href="style/style1.css" id="stylesheet"/>

        <input type="button" id="style1Button" value="Style 1"/>
        <input type="button" id="style2Button" value="Style 2"/>

Style change using DOM-scripting

 sample text

 sample text

 sample text

school name

school name

style1.css consists of the following:

body {
    background-color: #676632;
}

input[type="button"] {
    color: #F5F265;
    background-color: #9B9302;
}

article {
    margin-left: 150px;
    margin-right: 150px;
    text-indent: 20px;
    color: #C9C892;
}

h1 {
    color: #EEF1BA;
    text-align: center;
}

a {
    color: #A1FA56;
    text-decoration: none;
    font-weight: bold;
}

ul {
    padding: 0;
}

li {
    list-style-type: none;
}

Style2.css consists of the following:

body {
    color: #EEEEAA;
}

input[type="button"] {
    color: #9B9302;
    background-color: #F5F265;
}

article {
    margin-left: auto;
    margin-right: auto;
    text-align: justify;

    color: #A3A163;
}

h1 {
    color: #AAAA66;
    text-align: left;
}

a {
    color: #CDCF9B;
}

ul {
    padding: 0;
}

li {
    list-style-type: none;
}

The first part of the exercise states that I need to create a javascript file which allows the stylesheet for the webpage to change according to the button that was clicked. The first button refers to the first stylesheet and the second refers to the second stylesheet. I figured this out fairly easy and everything works fine.

However, the second part of the exercise states the following: "Now edit the javascript file so that only the style of the article is changed when the buttons are clicked. DO NOT edit the CSS file." Meaning that the href for the stylesheets should still be changed, like in the first part, but now it may only affect the style of the article element instead of the style of the whole page.

I have been searching for related questions for the past hour but nothing seems to really provide a solution. I have read some questions stating that it is impossible to apply a stylesheet only to a specific element without changing anything in the stylesheet itself. Keep in mind that I am only in my first year of college and have only just begun learning javascript, meaning that a solution should not be that hard to find. I guess?

The Javascript code I wrote so far:

'use strict';

const handleLoad = () => {
    let style1 = document.getElementById('style1Button');
    let style2 = document.getElementById('style2Button');
    style1.addEventListener('click', handleClick);
    style2.addEventListener('click', handleClick);
};

const handleClick = (event) => {
    if(event.target.value === "Style 1") {
        document.getElementById("stylesheet").href = "style/style1.css";
        // should only change article style
        // currently still referring to the whole document
    } else {
        document.getElementById("stylesheet").href = "style/style2.css";
        // should also only change article style
        // also still referring to the whole document
    }
};

window.addEventListener('load', handleLoad);

Is there any way I could block the CSS rules for all elements except the article element? Or maybe change the classes or ID's for the elements that should not be affected?

Thanks a lot in advance :)

This is what finally solved it. (code is probably not as compact and correct as it could be but it works so I'm more than happy :D):

'use strict';

const handleLoad = () => {
    let style1 = document.getElementById('style1Button');
    let style2 = document.getElementById('style2Button');
    style1.addEventListener('click', handleClick);
    style2.addEventListener('click', handleClick);
    makeShadow();
};

const handleClick = (event) => {
    let article = document.querySelector('article');
    let shadow = article.shadowRoot;

    let style = event.target.value === "Style 1" ? "style/style2.css" : "style/style1.css";

    for(let node of shadow.childNodes) {
        if(node.hasAttribute('href')){
            node.href = style;
        }
    }
};

const makeShadow = () => {
    let article = document.querySelector('article');
    let articleClone = makeClone(article);

    let shadow = article.attachShadow({mode:'open'});

    let link = document.createElement('link');
    link.rel = "stylesheet";
    link.href = 'style/style1.css';

    shadow.appendChild(articleClone);
    shadow.prepend(link);
};

const makeClone = (article) => {
    let clone = article.cloneNode();
    clone.innerHTML = article.innerHTML;
    return clone;
};

window.addEventListener('load', handleLoad);

Body:
Very very simple example for you.  You said it was new in Javascript. That's why I'm giving you an example that's so easy to understand. In fact, a more logical solution can be produced by looping around the buttons, figuring out which button they are on, defining the elements that need to be changed according to it, but this is the simplest example at this stage. You'll have to investigate and learn for yourself. Good Luck!

const style1Button = document.getElementById("style1Button");
style1Button.addEventListener("click", styleArticle);

function styleArticle(e) {
  let article = document.getElementById("article"); // full article
  // with querySelector, you can access the elements in the main element in this way.
  article.querySelector(".article-title").style.color = "red";
  article.querySelector(".text1").style.color = "blue";
  article.querySelector(".text2").style.color = "orange";
  article.querySelector(".text3").style.color = "gray";
}

<nav class="chooseStyle">
  <input type="button" id="style1Button" value="Style 1" />
  <input type="button" id="style2Button" value="Style 2" />
</nav>
<article id="article">.
  <!-- you can add a class or id to each of them to get specific with javascript. -->

  <h1 class="article-title">Style change using DOM-scripting</h1>
  <p class="text1"> sample text </p>
  <p class="text2"> sample text </p>
  <p class="text3"> sample text </p>
</article>
<nav class="links">
  <ul>
    <li><a href="link">school name</a></li>
    <li><a href="link">school name</a></li>
</nav>

Updated Answer :

I think you just made a letter mistake.

 const handleLoad = () => {
      let style1 = document.getElementById('style1Button');
      let style2 = document.getElementById('style2Button');
      style1.addEventListener('click', handleClick);
      style2.addEventListener('click', handleClick);
    }

    //handleclick to --- handleClick
    const handleClick = (event) => {
      if (event.target.value === "Style 1") {
        document.getElementById("styleSheet").href = "style/style.css";
        // should only change article style
        // currently still referring to the whole document
      } else {
        document.getElementById("styleSheet").href = "style/style2.css";
        // should also only change article style
        // also still referring to the whole document
      }
    };

    window.addEventListener('load', handleLoad);


来源: stackexchange

问:
How to access dynamic ref-tagged html elements in Vue.js 3?
Using the Vue.js 2 api-composition, you have a .ref attribute on the setupContext argument of setup(). As stated in many articles and in this thread : https://github.com/vuejs/composition-api/issues/226 it will NOT be available in vue.js 3, and you should declare attributes of the same name as the ref-ed element :

```<code><div ref='name'/>

setup() {
  return {
    name : ref(null)
  }
}
</code>```

However, what about when you do not know the ref name at the setup() ?

Like this "minimum" example :

```<code><div v-for="e in elements" @click="elements.push({name:Math.random(), content:Math.random()})">
  <div :ref="e.name">e.content</div>
</div>

setup(){
   return {
     a_function_called_later(){
       // I can use this.$refs but is there a more "vuejs3" way to do it ?
     }
     // ...???
   }
}
</code>```

答:
I had the same problem and was asking in the Vue.js Discord about it. Luckily Carlos Rodrigues could help me out.

<template>

 { divs[i] = el }">
    {{ item }}

</template>

```

You can read more about it in the official documentation: https://composition-api.vuejs.org/api.html#template-refs or on my blog: https://markus.oberlehner.net/blog/refs-and-the-vue-3-composition-api/

ContentLicense: CC BY-SA 4.0

Body:
Using the Vue.js 2 api-composition, you have a .ref attribute on the setupContext argument of setup(). As stated in many articles and in this thread : https://github.com/vuejs/composition-api/issues/226 it will NOT be available in vue.js 3, and you should declare attributes of the same name as the ref-ed element :

setup() {
  return {
    name : ref(null)
  }
}

However, what about when you do not know the ref name at the setup() ?

Like this "minimum" example :

e.content

setup(){
   return {
     a_function_called_later(){
       // I can use this.$refs but is there a more "vuejs3" way to do it ?
     }
     // ...???
   }
}

Body:
I had the same problem and was asking in the Vue.js Discord about it. Luckily Carlos Rodrigues could help me out.

<template>
  <div v-for="(item, i) in list" :ref="el => { divs[i] = el }">
    {{ item }}
  </div>
</template>

<script>
  import { ref, reactive, onBeforeUpdate } from 'vue'

  export default {
    setup() {
      const list = reactive([1, 2, 3])
      const divs = ref([])

      // make sure to reset the refs before each update
      onBeforeUpdate(() => {
        divs.value = []
      })

      return {
        list,
        divs
      }
    }
  }
</script>

You can read more about it in the official documentation: https://composition-api.vuejs.org/api.html#template-refs or on my blog: https://markus.oberlehner.net/blog/refs-and-the-vue-3-composition-api/


问:
What is the difference between signed and unsigned variables?
I have seen these mentioned in the context of C and C++, but what is the difference between signed and unsigned variables? </p>

答:
Signed variables can be 0, positive or negative.

Unsigned variables can be 0 or positive.

Unsigned variables are used sometimes because more bits can be used to represent the actual value.  Giving you a larger range.  Also you can ensure that a negative value won't be passed to your function for example.

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Brian R. Bondy

ContentLicense: CC BY-SA 2.5


问:
A shorter way of specifying a set in MDX
Is there a briefer way of specifying a set in MDX?

I know I can do something like :

```<code>{[Debtor].[TRADING DEBTOR CODE].&[AU-000013],[Debtor].[TRADING DEBTOR CODE].&[AU-000020]}
</code>```

but once you get over a few members, it becomes incredibly verbose.

I'm looking for something like

```<code>MagicFunctionToMakeASet([Debtor].[TRADING DEBTOR CODE],'AU-000013,AU-000015,AU-000013,AU-000015,...')
</code>```

答:
Are they in sequence at all? If so, could you do

```<code>{
      [Debtor].[TRADING DEBTOR CODE].&[AU-000013] :
      [Debtor].[TRADING DEBTOR CODE].&[AU-000020]
}
</code>```

To give you a set of codes 13 though to 20 inclusive?

Failing that, take a look at InStr and see if it can help, it looks like it might - Or you could create some subsets using it and then combine into your final set?

http://msdn.microsoft.com/en-us/library/ms145487.aspx

From the above MSDN:

```<code>WITH SET [ChardonnayChablis] AS
   'Filter([Product].Members, (InStr(1, [Product].CurrentMember.Name, "chardonnay") <> 0) OR (InStr(1, [Product].CurrentMember.Name, "chablis") <> 0))'

SELECT
   [ChardonnayChablis] ON COLUMNS,
   {Measures.[Unit Sales]} ON ROWS
FROM Sales
</code>```

Body:
Is there a briefer way of specifying a set in MDX?

I know I can do something like :

{[Debtor].[TRADING DEBTOR CODE].&[AU-000013],[Debtor].[TRADING DEBTOR CODE].&[AU-000020]}

but once you get over a few members, it becomes incredibly verbose.

I'm looking for something like

MagicFunctionToMakeASet([Debtor].[TRADING DEBTOR CODE],'AU-000013,AU-000015,AU-000013,AU-000015,...')

Body:
Are they in sequence at all? If so, could you do

{
      [Debtor].[TRADING DEBTOR CODE].&[AU-000013] :
      [Debtor].[TRADING DEBTOR CODE].&[AU-000020]
}

To give you a set of codes 13 though to 20 inclusive?

Failing that, take a look at InStr and see if it can help, it looks like it might - Or you could create some subsets using it and then combine into your final set?

http://msdn.microsoft.com/en-us/library/ms145487.aspx

From the above MSDN:

WITH SET [ChardonnayChablis] AS
   'Filter([Product].Members, (InStr(1, [Product].CurrentMember.Name, "chardonnay") <> 0) OR (InStr(1, [Product].CurrentMember.Name, "chablis") <> 0))'

SELECT
   [ChardonnayChablis] ON COLUMNS,
   {Measures.[Unit Sales]} ON ROWS
FROM Sales


答:
You can select elements with javascript and style them without changing a stylesheet.

There are different ways to do this, but if you cannot alter this HTML file this should do the trick for changing the text color inside the article element:

```<code>document.querySelector('article').style.color = 'red';
</code>```

You can style other things than the color and you can also select the H1 or paragraph elements inside of the article using querySelector but i'll let you figure that out ;)

Title: change stylesheet by button click for specific element only

Body:
You can select elements with javascript and style them without changing a stylesheet.

There are different ways to do this, but if you cannot alter this HTML file this should do the trick for changing the text color inside the article element:

document.querySelector('article').style.color = 'red';

You can style other things than the color and you can also select the H1 or paragraph elements inside of the article using querySelector but i'll let you figure that out ;)


问:
You attempted to use a firebase module that's not installed on your Android project by calling firebase.app() - Jest testing
I'm trying to test my app using jest but encountered an error "You attempted to use a firebase module that's not installed on your Android project by calling firebase.app()". Below is my code

```<code>import firebase from '@react-native-firebase/app';

test('renders correctly', () => {
  Platform.OS = 'android';
  firebase.initializeApp({//credentials hidden
  });
  const _firestore = firebase.firestore();
  const personStore = new PersonStore(_firestore);
  const app = renderer
    .create(
      <Provider {...personStore}>
        <PersonInfo />
      </Provider>,
    )
    .getInstance();
});
</code>```

What am I missing?
I've tried this solution https://rnfirebase.io/install-android but to no avail
And @react-native-firebase/app is working if I'm not in test mode

答:
Try the getting started steps: Getting Started

The solution you tried is a secondary step.
Also firebase is segmented in modules, so you should install the required modules separated. if you are going to use the firestore you have to install the module.
Firestore Module

Body:
I'm trying to test my app using jest but encountered an error "You attempted to use a firebase module that's not installed on your Android project by calling firebase.app()". Below is my code

import firebase from '@react-native-firebase/app';

test('renders correctly', () => {
  Platform.OS = 'android';
  firebase.initializeApp({//credentials hidden
  });
  const _firestore = firebase.firestore();
  const personStore = new PersonStore(_firestore);
  const app = renderer
    .create(
      <Provider {...personStore}>
        <PersonInfo />
      </Provider>,
    )
    .getInstance();
});

What am I missing?
I've tried this solution https://rnfirebase.io/install-android but to no avail
And @react-native-firebase/app is working if I'm not in test mode


问:
Angular - the best approach to keep variables in a project
I'm wondering what's the best approach to keep variables in Angular project.

I have an example, let's suppose I have a component which includes many variables, but I don't like that it makes my component so long and less transparent.

```<code>...
@Component({
    selector: 'app-ballance',
    templateUrl: './balance.component.html',
    styleUrls: ['./balance.component.scss']
})
export class BalanceComponent implements OnInit {

    list = [];
    list3 = [];
    errorMsg;
    numbOfElem = 0;
    numbOfElem2 = 0;
    items: Array<any>;
    items2: Array<any>;
    pageOfItems: Array<any>;
    pageOfItems2: Array<any>;
    clickData = false;
    datas: any;
    correctBalance = false;
    wrongBalance = false;
    extraBalance  = false;
    administrator = false;
    doubleBalance = true;
    individualBalance  = false;
    groupBallance = false;
    verifiedBallance = true;
    blockedBallance = false;
    deletedBallance = false;
    unverifiedBallance = false;
    prepaidBallance = false;
...
    ballanceSelect: any[] = [{
        label: 'xxx',
        name: this.showName,
        inputName: 'showName',
        status: this.showName.status,
    }, {
        label: 'xxx',
        name: this.showEmail,
        inputName: 'showEmail',
        status: this.showEmail.status,
    }, {
        label: 'xxx',
        name: this.showMobilePhone,
        inputName: 'showMobilePhone',
        status: this.showMobilePhone.status,
    },
    ];
...
</code>```

My code is working but it doesn't look beautiful, is there some way to create extra file which would store my variables, objects, arrays etc and  how to connect that with component?

答:
You could create a class in a seperate file to hold your data.

```<code>export class BalanceData{
correctBalance = false;
wrongBalance = false;
extraBalance  = false;
administrator = false;
doubleBalance = true;
individualBalance  = false;
groupBallance = false;
verifiedBallance = true;
blockedBallance = false;
deletedBallance = false;
unverifiedBallance = false;
prepaidBallance = false;
}
</code>```

You'll need to import the seperate file

```<code>import { BalanceData} from '../balanceData.ts';
</code>```

Then instead of declaring all your variables create an instance of your class.

```<code>data:BalanceData;
</code>```

Then access the variables like this.

```<code>data.correctBalance
</code>```

Body:
I'm wondering what's the best approach to keep variables in Angular project.

I have an example, let's suppose I have a component which includes many variables, but I don't like that it makes my component so long and less transparent.

...
@Component({
    selector: 'app-ballance',
    templateUrl: './balance.component.html',
    styleUrls: ['./balance.component.scss']
})
export class BalanceComponent implements OnInit {

    list = [];
    list3 = [];
    errorMsg;
    numbOfElem = 0;
    numbOfElem2 = 0;
    items: Array<any>;
    items2: Array<any>;
    pageOfItems: Array<any>;
    pageOfItems2: Array<any>;
    clickData = false;
    datas: any;
    correctBalance = false;
    wrongBalance = false;
    extraBalance  = false;
    administrator = false;
    doubleBalance = true;
    individualBalance  = false;
    groupBallance = false;
    verifiedBallance = true;
    blockedBallance = false;
    deletedBallance = false;
    unverifiedBallance = false;
    prepaidBallance = false;
...
    ballanceSelect: any[] = [{
        label: 'xxx',
        name: this.showName,
        inputName: 'showName',
        status: this.showName.status,
    }, {
        label: 'xxx',
        name: this.showEmail,
        inputName: 'showEmail',
        status: this.showEmail.status,
    }, {
        label: 'xxx',
        name: this.showMobilePhone,
        inputName: 'showMobilePhone',
        status: this.showMobilePhone.status,
    },
    ];
...

My code is working but it doesn't look beautiful, is there some way to create extra file which would store my variables, objects, arrays etc and  how to connect that with component?

Body:
You could create a class in a seperate file to hold your data.

export class BalanceData{
correctBalance = false;
wrongBalance = false;
extraBalance  = false;
administrator = false;
doubleBalance = true;
individualBalance  = false;
groupBallance = false;
verifiedBallance = true;
blockedBallance = false;
deletedBallance = false;
unverifiedBallance = false;
prepaidBallance = false;
}

You'll need to import the seperate file

import { BalanceData} from '../balanceData.ts';

Then instead of declaring all your variables create an instance of your class.

data:BalanceData;

Then access the variables like this.

data.correctBalance


问:
Prevent FlatList re-rendering causing performance problems
I'm building a React Native App using Hooks and ES6.

The Home screen fetches some data from API and display it as image galleries.
The Home screen is the parent component which includes a slideshow gallery and a Flatlist as children.

1) Slideshow - image gallery autoplay that run some operations (fetching URL in case user clicks on them) on each image iteration (every 3 secs) - This causes the re-render on the entire parent components and its children but it renders every 3 secs as supposed

2) Flatlist - just a simple Flatlist that takes an array of images - this should only rendered once when the parent component is initially loaded first

The problem

Every 3 seconds a new image is displayed in the slideshow, a function runs to fetch some props for the image displayed, the parent component is re-rendered but there is no need for Flatlist in the second gallery to run again since the array of images is the same as initially loaded (not changed)

This is my Parent code

```<code>const getTopTenMovies = (state) => state.moviescreen.popularmovies    //fetching data from Redux
const upcomingMovies = (state) => state.moviescreen.upcomingmovies

const MoviesScreen = (props) => {
  const topTenMovies = useSelector(getTopTenMovies);
  const [imageIndex, setImageIndex] = useState("");

  /* useEffect below runs every time imageIndex changes (a new image is displayed every 3 secs) */
  useEffect(() => {
      setCarouselMovieId(selectedImageItem.id);
      setCarouselMovieTitle(selectedImageItem.title);
  }, [imageIndex]);

  /* user clicks on an image and is taken to another screen
  const fetchMovieHandler = async (movieId, movieTitle) => {
      props.navigation.navigate({
        routeName: "MovieDetail",
        params: {
          assetId: movieId,
          assetName: movieTitle,
        },
      });
  };

  return (
    <ImageGallery
      data={topTenMovies}
      currentImage=setImageIndex(index)
      ...
    />

    <View style={styles.containerRow}>
          <FlatList
            horizontal={true}
            data={upcomingMovies}
            initialNumToRender={5}
            windowSize={10}
            removeClippedSubviews={true}
            keyExtractor={(item) => item.id.toString()}
            renderItem={(itemData) => (
              <HomeItem
                id={itemData.item.id}
                poster={itemData.item.poster_path}
                onAssetSelection={fetchMovieHandler}
              />
            )}
          />
        </View>
      </View>
  )
}
</code>```

The  component renders the individual images within the Flatlist and passes the parameters (movieId, movieTitle) to the fetchMovieHandler function.

HomeItem code below...

```<code>class HomeItem extends React.PureComponent {
  render() {
    const assetHandler = async () => {
      this.props.onAssetSelection(this.props.id, this.props.title);
    };
    console.log("HomeItem is called");
    return (
      <TouchableOpacity onPress={assetHandler}>
          <View>
              <Image
                key={this.props.id}
                source={{
                  uri: `https://*******${this.props.poster}`,
                }}
              />
          </View>
      </TouchableOpacity>
    );
  }
}

export default React.memo(HomeItem);
</code>```

Every 3 seconds the HomeItem is called and I see 10 log entries (one for each image and render - upcomingMovies has 10 images). From the UI everything looks fines since the images dont seems to change probably because I've defined the HomeItem as PureComponent and using React.memo(HomeItem) but it is causing performance issues since I'm getting the following error:

VirtualizedList: You have a large list that is slow to update - make sure your renderItem function renders components that follow React performance best practices like PureComponent, shouldComponentUpdate, etc

I tried to include the Flatlist inside the HomeItem component but the problem persists.

答:
If I were you I would change the following:

Don't place inline functions in FlatList (keyExtractor, renderItem)! Place it to separated function.

Use simple Component extension instead of PureComponent and compare your props with `shouldComponentUpdate. (I think the passed function called onAssetSelection causes the re-render. Check it.)

You don't need to use React.memo because it is for functional components.

Body:
I'm building a React Native App using Hooks and ES6.

The Home screen fetches some data from API and display it as image galleries.
The Home screen is the parent component which includes a slideshow gallery and a Flatlist as children.

1) Slideshow - image gallery autoplay that run some operations (fetching URL in case user clicks on them) on each image iteration (every 3 secs) - This causes the re-render on the entire parent components and its children but it renders every 3 secs as supposed

2) Flatlist - just a simple Flatlist that takes an array of images - this should only rendered once when the parent component is initially loaded first

The problem

Every 3 seconds a new image is displayed in the slideshow, a function runs to fetch some props for the image displayed, the parent component is re-rendered but there is no need for Flatlist in the second gallery to run again since the array of images is the same as initially loaded (not changed)

This is my Parent code

const getTopTenMovies = (state) => state.moviescreen.popularmovies    //fetching data from Redux
const upcomingMovies = (state) => state.moviescreen.upcomingmovies

const MoviesScreen = (props) => {
  const topTenMovies = useSelector(getTopTenMovies);
  const [imageIndex, setImageIndex] = useState("");

  /* useEffect below runs every time imageIndex changes (a new image is displayed every 3 secs) */
  useEffect(() => {
      setCarouselMovieId(selectedImageItem.id);
      setCarouselMovieTitle(selectedImageItem.title);
  }, [imageIndex]);

  /* user clicks on an image and is taken to another screen
  const fetchMovieHandler = async (movieId, movieTitle) => {
      props.navigation.navigate({
        routeName: "MovieDetail",
        params: {
          assetId: movieId,
          assetName: movieTitle,
        },
      });
  };

  return (
    <ImageGallery
      data={topTenMovies}
      currentImage=setImageIndex(index)
      ...
    />

    <View style={styles.containerRow}>
          <FlatList
            horizontal={true}
            data={upcomingMovies}
            initialNumToRender={5}
            windowSize={10}
            removeClippedSubviews={true}
            keyExtractor={(item) => item.id.toString()}
            renderItem={(itemData) => (
              <HomeItem
                id={itemData.item.id}
                poster={itemData.item.poster_path}
                onAssetSelection={fetchMovieHandler}
              />
            )}
          />
        </View>
      </View>
  )
}

The  component renders the individual images within the Flatlist and passes the parameters (movieId, movieTitle) to the fetchMovieHandler function.

HomeItem code below...

class HomeItem extends React.PureComponent {
  render() {
    const assetHandler = async () => {
      this.props.onAssetSelection(this.props.id, this.props.title);
    };
    console.log("HomeItem is called");
    return (
      <TouchableOpacity onPress={assetHandler}>
          <View>
              <Image
                key={this.props.id}
                source={{
                  uri: `https://*******${this.props.poster}`,
                }}
              />
          </View>
      </TouchableOpacity>
    );
  }
}

export default React.memo(HomeItem);

Every 3 seconds the HomeItem is called and I see 10 log entries (one for each image and render - upcomingMovies has 10 images). From the UI everything looks fines since the images dont seems to change probably because I've defined the HomeItem as PureComponent and using React.memo(HomeItem) but it is causing performance issues since I'm getting the following error:

VirtualizedList: You have a large list that is slow to update - make sure your renderItem function renders components that follow React performance best practices like PureComponent, shouldComponentUpdate, etc

I tried to include the Flatlist inside the HomeItem component but the problem persists.


问:
How to simulate a slow internet connection for testing a webpage?
I am working on a prototype website on localhost using NodeJS and MongoDB.

I want to see how my site will load on slow internet.

How can I replicate that with localhost?

答:
If this is a localhost web page, and you want to know how long does it take to process and render the HTML web page, you can see via :

Go to the Developer Tools

Go to the Network tab.

Just navigate to the URL you want to check the timing for. Suppose, for your default.html page. You can just click on the hyperlink to go to that page

Networking tab will capture all of the requests in front of you, with their links, their HTTP status, their timeline etc.

The last link which will be downloaded will show the time elapsed in loading your website's web page.


问:
Whats the point of DOCTYPE?
I know that different doctypes are essentially about how compliant the html is, but what difference does it make what doctype you specify? Do browsers handle the same code differently depending on the doctype?
Thanks </p>

<p>UPDATE - most answers mention quirks mode can be set off if no doctype is specified. But what would be the different between xhtml and html 4.01? </p>

答:
Because Doctype is the flag to tell how the browser should handle the page.

For example :

HTML5 need this doctype<!DOCTYPE html>
If you remove this from the page, the any HTML5 capabilities inside your page won't be activated.

You can read more in http://www.w3.org/QA/Tips/Doctype

Title: Whats the point of DOCTYPE?

Body:
I know that different doctypes are essentially about how compliant the html is, but what difference does it make what doctype you specify? Do browsers handle the same code differently depending on the doctype?
Thanks

UPDATE - most answers mention quirks mode can be set off if no doctype is specified. But what would be the different between xhtml and html 4.01?


问:
Tensorflow libcublas 10.0 Issue
Hi I've been using Adrian's guide from https://www.pyimagesearch.com/2020/03/25/how-to-configure-your-nvidia-jetson-nano-for-computer-vision-and-deep-learning/

I'm attempting to run Tensorflow 1.13.1 on a Jetson Nano. When I go to initiate python and import tensorflow I get the following error:

Python 3.6.9 (default, Apr 18 2020, 01:56:04)
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

import tensorflow
      Traceback (most recent call last):
        File "/home/zachwad/.virtualenvs/py3cv4/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in
          from tensorflow.python.pywrap_tensorflow_internal import *
        File "/home/zachwad/.virtualenvs/py3cv4/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in
          _pywrap_tensorflow_internal = swig_import_helper()
        File "/home/zachwad/.virtualenvs/py3cv4/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
          _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
        File "/usr/lib/python3.6/imp.py", line 243, in load_module
          return load_dynamic(name, filename, file)
        File "/usr/lib/python3.6/imp.py", line 343, in load_dynamic
          return _load(spec)
      ImportError: libcublas.so.10.0: cannot open shared object file: No such file or directory

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "", line 1, in
  File "/home/zachwad/.virtualenvs/py3cv4/lib/python3.6/site-packages/tensorflow/init.py", line 24, in
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "/home/zachwad/.virtualenvs/py3cv4/lib/python3.6/site-packages/tensorflow/python/init.py", line 49, in
    from tensorflow.python import pywrap_tensorflow
  File "/home/zachwad/.virtualenvs/py3cv4/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 74, in
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/home/zachwad/.virtualenvs/py3cv4/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/zachwad/.virtualenvs/py3cv4/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/zachwad/.virtualenvs/py3cv4/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/usr/lib/python3.6/imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
  File "/usr/lib/python3.6/imp.py", line 343, in load_dynamic
    return _load(spec)
ImportError: libcublas.so.10.0: cannot open shared object file: No such file or directory

答:
Seems related to the following problem.

Make sure that a compatible cuda version (in this case cuda 10) is installed on your system and that the linker can find the library: libcublas.so.10.0

Tensorflow often uses older cuda versions.
Keep also in mind that tensorflow released version 2.0, which is very different from version 1.13.

Title: Tensorflow libcublas 10.0 Issue


问:
"Moving" a value from one row to another in MySQL
I'm pretty new to MySQL and I really don't know how to google this. Sorry if it's a dumb question.

I have a table that contains unique value pairs as the primary key (userID, somethingID) and a value. For example,

```<code>userID     somethingID    value
892        10             1
892        9              1
892        0              10
</code>```

If (userID, somethingID = 0) has a value greater than 0, the user should be able to decrement that value and increment the value of any other row. In the example above, userID 892 has a value of 10 in somethingID 0, so if he wants, he could take 1 from that value and move it to (892, 9):

```<code>userID     somethingID    value
892        10             1
892        9              2
892        0              9
</code>```

I need to add a check that ensures the value row of (userID, 0) is greater than zero before doing so. The value of (userID, 0) cannot be negative.

Any help would be appreciated.

Thank you all so much!

答:
This query:

```<code>select userid,
  max(case when somethingid > 0 then somethingid end) somethingid,
  max(case when somethingid = 0 and value > 0 then value end) zero_value
from tablename
group by userid
having zero_value is not null;
</code>```

returns the userids that contain rows with somethingid = 0 and value > 0 and a somethingid > 0.

You can join it to the table in the update statement:

```<code>update tablename t
inner join (
  select userid,
    max(case when somethingid > 0 then somethingid end) somethingid,
    max(case when somethingid = 0 and value > 0 then value end) zero_value
  from tablename
  group by userid
  having zero_value is not null
) g on g.userid = t.userid
    and ((t.somethingid = 0 and t.value = g.zero_value)  or (t.somethingid = g.somethingid))
set t.value = case
  when t.somethingid = g.somethingid then t.value + 1
  else t.value - 1
end;
</code>```

See the demo.

Body:
I'm pretty new to MySQL and I really don't know how to google this. Sorry if it's a dumb question.

I have a table that contains unique value pairs as the primary key (userID, somethingID) and a value. For example,

userID     somethingID    value
892        10             1
892        9              1
892        0              10

If (userID, somethingID = 0) has a value greater than 0, the user should be able to decrement that value and increment the value of any other row. In the example above, userID 892 has a value of 10 in somethingID 0, so if he wants, he could take 1 from that value and move it to (892, 9):

userID     somethingID    value
892        10             1
892        9              2
892        0              9

I need to add a check that ensures the value row of (userID, 0) is greater than zero before doing so. The value of (userID, 0) cannot be negative.

Any help would be appreciated.

Thank you all so much!

Body:
This query:

select userid,
  max(case when somethingid > 0 then somethingid end) somethingid,
  max(case when somethingid = 0 and value > 0 then value end) zero_value
from tablename
group by userid
having zero_value is not null;

returns the userids that contain rows with somethingid = 0 and value > 0 and a somethingid > 0.

You can join it to the table in the update statement:

update tablename t
inner join (
  select userid,
    max(case when somethingid > 0 then somethingid end) somethingid,
    max(case when somethingid = 0 and value > 0 then value end) zero_value
  from tablename
  group by userid
  having zero_value is not null
) g on g.userid = t.userid
    and ((t.somethingid = 0 and t.value = g.zero_value)  or (t.somethingid = g.somethingid))
set t.value = case
  when t.somethingid = g.somethingid then t.value + 1
  else t.value - 1
end;

See the demo.


问:
How do I incorporate variables in GOAP when planning regressively from the goal?
I am looking at and reading resources like this:

and this:

I have made a forward-searching planner using A*; but am now trying to search backwards for the efficiency gains.

Orkin specifically says

The planning example illustrated in Figure 2 consists of actions that have constant
  Boolean values for preconditions and effects, but it is important to point out that
  preconditions and effects can also represented by variables. The planner solves for these
  variables as it regresses from the goal. Variables add power and flexibility to the planner,
  as it can now satisfy more general preconditions. For instance, a Goto action with the
  effect of moving a character to a variable destination is far more powerful than a Goto
  action that moves to a constant, predetermined location.

So I'm not attempting to visualise this prior to implementing it; but I cannot work out how to solve the variables moving away from where they're needed:

```<code>        KEY             CURRENT     GOAL

    itemStockpiled      false       true
    ------------------------------------------

                StockpileItem       Effect:     itemStockpiled true
                                    Precond:    hasItem ?itemId?     **** How can I test this?
                                                agentAtPosition ?stockPos?

    itemStockpiled      true        true
    hasItem             0           ?itemId?
    agentAtPosition     ???         ?stockPos?
    ------------------------------------------

                Goto                Effect:     agentAtPosition ?stockPos?  **** Where is this?

    itemStockpiled      true        true
    hasItem             0           ?itemId?
    agentAtPosition     ?stockPos?  ?stockPos?
    ------------------------------------------

                PickupItem          Effect:     hasItem ?itemId?
                                    Precond:    agentAtPosition ?itemPos?

    itemStockpiled      true        true
    hasItem             ?itemId?    ?itemId?
    agentAtPosition     ?stockPos?  ?itemPos?      **** So we need to go
                                                   back to the item from
                                                   the stockpile pos
    ------------------------------------------

                Goto                Effect:     agentAtPosition ?itemPos?    **** Where is this?
                                    Precond:    foundItem true

    itemStockpiled      true        true
    hasItem             ?itemId?    ?itemId?
    agentAtPosition     ?itemPos?  ?itemPos?
    foundItem           false       true
    ------------------------------------------

                FindItem            Effect: foundItem true

    itemStockpiled      true        true
    hasItem             ?itemId?    ?itemId?
    agentAtPosition     ?itemPos?  ?itemPos?
    foundItem           true       true
    ------------------------------------------
</code>```

You'll see how in the above comments, I don't understand how I can check for things like an existance of a path, before I know where I'm finding a path too. For the item, I imaging I can have a boolean flag of "hasItem", and keep track of the itemId in a variable that isn't populated until FindItem is successful (and then used when executing the path); but how would this work with a GoTo action?

If I use a world-state variable "agentAtPosition" as an effect for Goto; it will be set at two different points in the plan; meaning that subsequent actions that need "agentAtPosition" to be true will already have their preconditions met, effectively ending the planning, erroneously thinking it found a path:

```<code>        KEY             CURRENT     GOAL

    itemStockpiled      false       true
    ------------------------------------------

                StockpileItem       Effect:     itemStockpiled true
                                    Precond:    hasItem true
                                                agentAtPosition true

    itemStockpiled      true        true
    hasItem             false       true
    agentAtPosition     false       true
    ------------------------------------------

                Goto                Effect:     agentAtPosition true

    itemStockpiled      true        true
    hasItem             false       true
    agentAtPosition     true        true
    ------------------------------------------

                PickupItem          Effect:     hasItem true
                                    Precond:    agentAtPosition true

    itemStockpiled      true        true
    hasItem             true        true
    agentAtPosition     true        true
    ------------------------------------------
</code>```

How do I work around this?

答:
So, it seems GOPA is this: http://alumni.media.mit.edu/~jorkin/goap.html.
I'd have linked the reference.

I don't understand what's you are trying to do and the paragraph you quote from "Orkin" (that I don't know about). However, this part is only an intuition:

Variables add power and flexibility to the planner, as it can now satisfy more general preconditions.

One must distinguish between changing the problem and changing the solution. If you implemented an A* forward search algorithm, then implementing full regression is a matter of implementing the regression operation of A over state s: the partial states s' that must have come before s is such that:
- the preconditions of A were true in s'
- the effects of A are consistent with s
- A is relevant for getting from s' to s. If there are no negative preconditions, then there is at least one p in add(A) that is not in s' but is in s.

Now, "adding variables" sounds like reformulating the problem. In that case, the main question is:
- is that reformulation preserving all the paths?
If not, it should merge some paths in a precise way. Otherwise, it's not a reformulation.

So, the first question is not about forward or backward search, is about confirming what are the possible paths. If the possible paths are correct, then regression should work.

Unless you are actually trying to do something smarter like not bounding objects until necessary.

I suggest 1st focusing on a simpler version where standard regression make sense, and then revisit what you want to do.

Body:
I am looking at and reading resources like this:

and this:

I have made a forward-searching planner using A*; but am now trying to search backwards for the efficiency gains.

Orkin specifically says

The planning example illustrated in Figure 2 consists of actions that have constant
  Boolean values for preconditions and effects, but it is important to point out that
  preconditions and effects can also represented by variables. The planner solves for these
  variables as it regresses from the goal. Variables add power and flexibility to the planner,
  as it can now satisfy more general preconditions. For instance, a Goto action with the
  effect of moving a character to a variable destination is far more powerful than a Goto
  action that moves to a constant, predetermined location.

So I'm not attempting to visualise this prior to implementing it; but I cannot work out how to solve the variables moving away from where they're needed:

        KEY             CURRENT     GOAL

    itemStockpiled      false       true
    ------------------------------------------

                StockpileItem       Effect:     itemStockpiled true
                                    Precond:    hasItem ?itemId?     **** How can I test this?
                                                agentAtPosition ?stockPos?

    itemStockpiled      true        true
    hasItem             0           ?itemId?
    agentAtPosition     ???         ?stockPos?
    ------------------------------------------

                Goto                Effect:     agentAtPosition ?stockPos?  **** Where is this?

    itemStockpiled      true        true
    hasItem             0           ?itemId?
    agentAtPosition     ?stockPos?  ?stockPos?
    ------------------------------------------

                PickupItem          Effect:     hasItem ?itemId?
                                    Precond:    agentAtPosition ?itemPos?

    itemStockpiled      true        true
    hasItem             ?itemId?    ?itemId?
    agentAtPosition     ?stockPos?  ?itemPos?      **** So we need to go
                                                   back to the item from
                                                   the stockpile pos
    ------------------------------------------

                Goto                Effect:     agentAtPosition ?itemPos?    **** Where is this?
                                    Precond:    foundItem true

    itemStockpiled      true        true
    hasItem             ?itemId?    ?itemId?
    agentAtPosition     ?itemPos?  ?itemPos?
    foundItem           false       true
    ------------------------------------------

                FindItem            Effect: foundItem true

    itemStockpiled      true        true
    hasItem             ?itemId?    ?itemId?
    agentAtPosition     ?itemPos?  ?itemPos?
    foundItem           true       true
    ------------------------------------------

You'll see how in the above comments, I don't understand how I can check for things like an existance of a path, before I know where I'm finding a path too. For the item, I imaging I can have a boolean flag of "hasItem", and keep track of the itemId in a variable that isn't populated until FindItem is successful (and then used when executing the path); but how would this work with a GoTo action?

If I use a world-state variable "agentAtPosition" as an effect for Goto; it will be set at two different points in the plan; meaning that subsequent actions that need "agentAtPosition" to be true will already have their preconditions met, effectively ending the planning, erroneously thinking it found a path:

        KEY             CURRENT     GOAL

    itemStockpiled      false       true
    ------------------------------------------

                StockpileItem       Effect:     itemStockpiled true
                                    Precond:    hasItem true
                                                agentAtPosition true

    itemStockpiled      true        true
    hasItem             false       true
    agentAtPosition     false       true
    ------------------------------------------

                Goto                Effect:     agentAtPosition true

    itemStockpiled      true        true
    hasItem             false       true
    agentAtPosition     true        true
    ------------------------------------------

                PickupItem          Effect:     hasItem true
                                    Precond:    agentAtPosition true

    itemStockpiled      true        true
    hasItem             true        true
    agentAtPosition     true        true
    ------------------------------------------

How do I work around this?


问:
“NODE_ENV” is not recognized as an internal or external command, operable command or batch file
I'm trying to setup an environment. However, I'm getting the following error every time:

NODE_ENV" is not recognized as an internal or external command, operable command or batch file.

When I added the set before NODE_ENV it showed me only this:

set NODE_ENV=development nodemon -w src --exec "babel-node src --presets es2015,stage-0"
```

答: Sometimes setting SET NODE_ENV=... doesn't solve your issue. Then you should run npm install -g win-node-env


问:
What can be alternate source of input for args getResolvedOptions() method in AWS GlueJob?
I have a Glue Job in which I want to pass parameters to getResolvedOptions. One way I know is by creating a JobRun within Lambda Function, I can pass it. What are the other ways to pass param1 and param2 in code below:

```<code>import sys
from awsglue.utils import getResolvedOptions

args = getResolvedOptions(sys.argv, ['param1',
                                     'param2'])
</code>```

Note: I don't want to pass parameters in code by hardcoding it.

Thanks in Advance.

答:
You can easily achieve this through cloudformation (cfn) yaml templates or alternatively you could just add the variables directly to the job, via cli/sdk/console etc. If you wanted to go down the cfn route, you could define your resource as follows:

```<code>  JobNAME:
    Type: "AWS::Glue::Job"
    Properties:
      Name: String
      Description: String
      Role: String
      GlueVersion: 1.0
      Command:
        Name: "glueetl"
        ScriptLocation: String
        PythonVersion: 3
      DefaultArguments: {
          "--job-language": "python",
          "--param1" : VALUE,
          "--param2" : VALUE,
          "--TempDir" : String,
          "--job-bookmark-option" : "job-bookmark-enable",
          "--enable-continuous-cloudwatch-log" : "false",
          "--enable-continuous-log-filter" : "false",
          "--enable-metrics" : "false"
      }
      ExecutionProperty:
        MaxConcurrentRuns: 1
      MaxCapacity: 5
      MaxRetries: 1
      Timeout: 60
</code>```

Once defined, you can call out the parameters through getResolvedOptions, noting there are reserved values for glue defaults, e.g.:

```<code>import sys
from awsglue.utils import getResolvedOptions

## @params: [JOB_NAME <--default assigned, param1 <---your value, param2 <---your value]
args = getResolvedOptions(sys.argv, ['JOB_NAME', 'param1','param2'])
</code>```

Body:
I have a Glue Job in which I want to pass parameters to getResolvedOptions. One way I know is by creating a JobRun within Lambda Function, I can pass it. What are the other ways to pass param1 and param2 in code below:

import sys
from awsglue.utils import getResolvedOptions

args = getResolvedOptions(sys.argv, ['param1',
                                     'param2'])

Note: I don't want to pass parameters in code by hardcoding it.

Thanks in Advance.

Body:
You can easily achieve this through cloudformation (cfn) yaml templates or alternatively you could just add the variables directly to the job, via cli/sdk/console etc. If you wanted to go down the cfn route, you could define your resource as follows:

  JobNAME:
    Type: "AWS::Glue::Job"
    Properties:
      Name: String
      Description: String
      Role: String
      GlueVersion: 1.0
      Command:
        Name: "glueetl"
        ScriptLocation: String
        PythonVersion: 3
      DefaultArguments: {
          "--job-language": "python",
          "--param1" : VALUE,
          "--param2" : VALUE,
          "--TempDir" : String,
          "--job-bookmark-option" : "job-bookmark-enable",
          "--enable-continuous-cloudwatch-log" : "false",
          "--enable-continuous-log-filter" : "false",
          "--enable-metrics" : "false"
      }
      ExecutionProperty:
        MaxConcurrentRuns: 1
      MaxCapacity: 5
      MaxRetries: 1
      Timeout: 60

Once defined, you can call out the parameters through getResolvedOptions, noting there are reserved values for glue defaults, e.g.:

import sys
from awsglue.utils import getResolvedOptions

## @params: [JOB_NAME <--default assigned, param1 <---your value, param2 <---your value]
args = getResolvedOptions(sys.argv, ['JOB_NAME', 'param1','param2'])


问:
How can I send message to specific contact through WhatsApp from my ios app using swift?
```<code>        // 1
        let urlWhats = "https://wa.me/\(mobile)/?text=\(text)"
        // 2
        if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) {
          // 3
          if let whatsappURL = NSURL(string: urlString) {
            // 4
            if UIApplication.shared.canOpenURL(whatsappURL as URL) {
              // 5
              UIApplication.shared.open(whatsappURL as URL, options: [:], completionHandler: nil)
//                UIApplication.shared.\
            } else {
              // 6
              print("Cannot Open Whatsapp")
            }
          }
        }
</code>```

I'm able to launch whatsapp from my app from the above mentioned code, it is composing prefix text to the contact I wish to send and I need to click the send button in whatsapp manually . But I'm looking for a code which automatically sends whatsapp text to number from my app. Can anyone share your thoughts on this?

答: You can only compose the message for a particular contact using the Deep Linking method that you have used for it. For sending the message user has to click on the send button manually. You could provide the user with an alert that says so. But, it's not possible to do it for the user from your side. If you were able to send a message on Whatsapp by writing code without the user's confirmation it would be a break of user's privacy. Don't you think?

Body:
        // 1
        let urlWhats = "https://wa.me/\(mobile)/?text=\(text)"
        // 2
        if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) {
          // 3
          if let whatsappURL = NSURL(string: urlString) {
            // 4
            if UIApplication.shared.canOpenURL(whatsappURL as URL) {
              // 5
              UIApplication.shared.open(whatsappURL as URL, options: [:], completionHandler: nil)
//                UIApplication.shared.\
            } else {
              // 6
              print("Cannot Open Whatsapp")
            }
          }
        }

I'm able to launch whatsapp from my app from the above mentioned code, it is composing prefix text to the contact I wish to send and I need to click the send button in whatsapp manually . But I'm looking for a code which automatically sends whatsapp text to number from my app. Can anyone share your thoughts on this?


问:
How to know selected value of v-calendar | Vue.js?
I am new in Vue.js and need some advice.

I have component (Navbar) with 2 element. First one is v-calendar, the second one is simple button. When user click button I want to know the selected value of v-calendar widget.

Navbar.vue:

```<code><template>
    <b-navbar toggleable type="warning" variant="warning">
        <v-date-picker class='v-date-picker'
                       mode='range'
                       v-model='range'
                       :show-day-popover=false
                       is-double-paned
                       show-caps>
        </v-date-picker>
        <b-button class="search-btn" v-on:click="search">
            <font-awesome-icon :icon="faSearch"/>
        </b-button>
    </b-navbar>
</template>

<script>
    import Vue from 'vue';
    import VCalendar from 'v-calendar'
    import 'v-calendar/lib/v-calendar.min.css';
    import {
        FontAwesomeIcon
    } from '@fortawesome/vue-fontawesome'
    import {
        faSearch
    } from '@fortawesome/free-solid-svg-icons'

    Vue.use(VCalendar);

    export default {
        name: "Navbar",
        data() {
            return {
                range: {
                    start: new Date(2018, 0, 16),
                    end: new Date(2018, 0, 19)
                },
                faSearch: faSearch
            }
        },
        components: {
            FontAwesomeIcon
        },
        methods: {
            search: function (event) {

            }
        }
    }
</script>
</code>```

答:
You could improve the syntax:</p>

```<code><b-button @click="search"/>

methods:{
    search() {
      console.log({ start: this.range.start, end: this.range.end })
    }
}
</code>```

Body:
I am new in Vue.js and need some advice.

I have component (Navbar) with 2 element. First one is v-calendar, the second one is simple button. When user click button I want to know the selected value of v-calendar widget.

Navbar.vue:

<template>

        <v-date-picker class='v-date-picker'
                       mode='range'
                       v-model='range'
                       :show-day-popover=false
                       is-double-paned
                       show-caps>
        </v-date-picker>

</template>

Body:
You could improve the syntax:

<b-button @click="search"/>

methods:{
    search() {
      console.log({ start: this.range.start, end: this.range.end })
    }
}


问:
Reset looping setTimeout()
I am able to add a row to my table every few seconds using setTimeout(). But when I try to reset the table and fill it up again, some of the rows from last time still show up. I would like to reset the whole table and start over from 0.

This is my code:

$(document).ready(() => {
  $('#btn-start').click(() => {
      showMoves();
  });
  $('#btn-reset').click(() => {
      $('#table-moves tbody tr').remove();
      clearTimeout(timer);
  });
});

var timer;

function showMoves () {
  const moves = ['nf3','d5','g3', 'g6'] // ...
  $('#table-moves tbody tr').remove();
  for (let i = 0; i < moves.length; i++) {
    timer = setTimeout(() => {
        $('#tbody-moves').append(`<tr><td>${i + 1}</td><td>${moves[i]}</td></tr>`);
    }, 2000 * i);
    if (i >= moves.length - 1) {
      clearTimeout(timer);
    }
  }
}```

Output

答:
setTimeout is an asynchronous function so while you iterate over moves you create N timers. So to reset them all you need to store them

$(document).ready(() => {
  $('#btn-start').click(() => {
      showMoves();
  });
  $('#btn-reset').click(() => {
      $('#table-moves tbody tr').remove();
      while(timers.length) clearTimeout(timers.shift()) // Added
  });
});

var timers = []; // Change

function showMoves () {
  const moves = ['nf3','d5','g3', 'g6'] // ...
  $('#table-moves tbody tr').remove();
  for (let i = 0; i < moves.length; i++) {
    /*Change*/timers.push(setTimeout(() => {
        $('#tbody-moves').append(`<tr><td>${i + 1}</td><td>${moves[i]}</td></tr>`);
    }, 2000 * i));
    if (i >= moves.length - 1) {
      clearTimeout(timers.pop()); // Change
    }
  }
}```

</code>```

Title: Reset looping setTimeout()

Body:
I am able to add a row to my table every few seconds using setTimeout(). But when I try to reset the table and fill it up again, some of the rows from last time still show up. I would like to reset the whole table and start over from 0.

This is my code:

$(document).ready(() => {
  $('#btn-start').click(() => {
      showMoves();
  });
  $('#btn-reset').click(() => {
      $('#table-moves tbody tr').remove();
      clearTimeout(timer);
  });
});

var timer;

function showMoves () {
  const moves = ['nf3','d5','g3', 'g6'] // ...
  $('#table-moves tbody tr').remove();
  for (let i = 0; i < moves.length; i++) {
    timer = setTimeout(() => {
        $('#tbody-moves').append(`<tr><td>${i + 1}</td><td>${moves[i]}</td></tr>`);
    }, 2000 * i);
    if (i >= moves.length - 1) {
      clearTimeout(timer);
    }
  }
}

Output


问:
Spinner receiving data in parentheses

```<code>spinner = (Spinner) findViewById(R.id.department_spinner);

departmentDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Departments");

departmentSpinnerDataList = new ArrayList<>();
adapter = new ArrayAdapter<String>(createNewEmployeeTab.this, departmentSpinnerDataList);
spinner.setAdapter(adapter);
retrieveDepartmentData();

public void retrieveDepartmentData(){

        listener = departmentDatabaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for (DataSnapshot item:dataSnapshot.getChildren()){

                    departmentSpinnerDataList.add(item.getValue().toString());

                }

                adapter.notifyDataSetChanged();

            }
</code>```

This is the first time dealing with the database.I cant seem to find out where the issue is.I can't restructure the database as it is used in other screens aswell.

答:
Change this:

```<code>departmentSpinnerDataList.add(item.getValue().toString());
</code>```

into this:

```<code>departmentSpinnerDataList.add(item.child("name").getValue().toString());
</code>```

add the child("name") to retrieve the name attribute from the database.

Title: Spinner receiving data in parentheses

Body:
spinner = (Spinner) findViewById(R.id.department_spinner);

departmentDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Departments");

departmentSpinnerDataList = new ArrayList<>();
adapter = new ArrayAdapter<String>(createNewEmployeeTab.this, departmentSpinnerDataList);
spinner.setAdapter(adapter);
retrieveDepartmentData();

public void retrieveDepartmentData(){

        listener = departmentDatabaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for (DataSnapshot item:dataSnapshot.getChildren()){

                    departmentSpinnerDataList.add(item.getValue().toString());

                }

                adapter.notifyDataSetChanged();

            }

This is the first time dealing with the database.I cant seem to find out where the issue is.I can't restructure the database as it is used in other screens aswell.

Body:
Change this:

departmentSpinnerDataList.add(item.getValue().toString());

into this:

departmentSpinnerDataList.add(item.child("name").getValue().toString());

add the child("name") to retrieve the name attribute from the database.


问:
Python Web Scraping: Output to csv
I'm doing some progress with web scraping however I still need some help to perform some operations:

```<code>import requests
import pandas as pd
from bs4 import BeautifulSoup

url = 'http://fcf.cat/equip/1920/1i/sant-ildefons-ue-b'

# soup = BeautifulSoup(requests.get(converturl).content, 'html.parser')

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

out = []

for tr in soup.select('.col-md-4 tbody tr'):
</code>```

On the class col-md-4 I know there are 3 tables I want to generate a csv which as an output has three values: first name, last name, and for the last value I want the header name of the table.

first name, last name, header table

Any help would be appreciated.

答:
This might work:</p>

```<code>import requests
import pandas as pd
from bs4 import BeautifulSoup

url = 'http://fcf.cat/equip/1920/1i/sant-ildefons-ue-b'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')
tables = soup.select('.col-md-4 table')
rows = []

for table in tables:
    cleaned = list(table.stripped_strings)
    header, names = cleaned[0], cleaned[1:]
    data = [name.split(', ') + [header] for name in names]
    rows.extend(data)

result = pd.DataFrame.from_records(rows, columns=['surname', 'name', 'table'])
</code>```

Title: Python Web Scraping: Output to csv

Body:
I'm doing some progress with web scraping however I still need some help to perform some operations:

import requests
import pandas as pd
from bs4 import BeautifulSoup

url = 'http://fcf.cat/equip/1920/1i/sant-ildefons-ue-b'

# soup = BeautifulSoup(requests.get(converturl).content, 'html.parser')

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

out = []

for tr in soup.select('.col-md-4 tbody tr'):

On the class col-md-4 I know there are 3 tables I want to generate a csv which as an output has three values: first name, last name, and for the last value I want the header name of the table.

first name, last name, header table

Any help would be appreciated.

Body:
This might work:

import requests
import pandas as pd
from bs4 import BeautifulSoup

url = 'http://fcf.cat/equip/1920/1i/sant-ildefons-ue-b'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')
tables = soup.select('.col-md-4 table')
rows = []

for table in tables:
    cleaned = list(table.stripped_strings)
    header, names = cleaned[0], cleaned[1:]
    data = [name.split(', ') + [header] for name in names]
    rows.extend(data)

result = pd.DataFrame.from_records(rows, columns=['surname', 'name', 'table'])


问:
How to associate and filter two related arrays?
I have two arrays and I want to link together when processing them.

```<code>$dat = array(
    "2020-02-01",
    "2020-02-05",
    "2020-02-10",
    "2020-02-12",
    "2020-02-15"
);
$word = array(
    "Attend To,Explore,Unaided,dull,bad"
);

//User input
$start = "2020-01-01";
$end = "2020-02-07";
</code>```

I want the input to affect the second array too, so when the first array gets its result from first 2, then the second array too should have it from the first 2.

```<code>//Filter out dates between start and end date
$result = array_filter($dat, function($data_item) use($start, $end) {
    return $data_item >= $start && $data_item <= $end;
});
</code>```

and the result is

```<code>Array
(
    [0] => 2020-02-01
    [1] => 2020-02-05
)
</code>```

I want it to be able to link $dat and $word so that the result for word too will be

```<code>Array
(
    [0] => Attend To
    [1] => Explore
)
</code>```

答:
A possible solution assuming that the arrays have the same keys (I changed it to reflect this), is to use the constant ARRAY_FILTER_USE_BOTH to array_filter, so that the key is available in the callback function.

here i fill a second array $result2 with the words while filtering the data (note that things are added in use and $result2 is passed by reference):

```<code>$dat = array("2020-02-01","2020-02-05","2020-02-10","20-02-12","2020-02-15");
$word = array("Attend To","Explore","Unaided","dull","bad");

//User input
$start = "2020-01-01";
$end = "2020-02-07";

//Filter out dates between start and end date
$result2 = [];
$result = array_filter($dat, function($data_item, $key) use($start, $end, $word, &$result2) {
    if($data_item >= $start && $data_item <= $end){
        $result2[$key] = $word[$key];
        return true;
    }
    return false;
}, ARRAY_FILTER_USE_BOTH);
</code>```

AbraCadaver's answer is perfect fit when only the filtering is needed, but this can be useful in case someone has to do extra operations in the filter callback..

Body:
I have two arrays and I want to link together when processing them.

$dat = array(
    "2020-02-01",
    "2020-02-05",
    "2020-02-10",
    "2020-02-12",
    "2020-02-15"
);
$word = array(
    "Attend To,Explore,Unaided,dull,bad"
);

//User input
$start = "2020-01-01";
$end = "2020-02-07";

I want the input to affect the second array too, so when the first array gets its result from first 2, then the second array too should have it from the first 2.

//Filter out dates between start and end date
$result = array_filter($dat, function($data_item) use($start, $end) {
    return $data_item >= $start && $data_item <= $end;
});

and the result is

Array
(
    [0] => 2020-02-01
    [1] => 2020-02-05
)

I want it to be able to link $dat and $word so that the result for word too will be

Array
(
    [0] => Attend To
    [1] => Explore
)

Body:
A possible solution assuming that the arrays have the same keys (I changed it to reflect this), is to use the constant ARRAY_FILTER_USE_BOTH to array_filter, so that the key is available in the callback function.

here i fill a second array $result2 with the words while filtering the data (note that things are added in use and $result2 is passed by reference):

$dat = array("2020-02-01","2020-02-05","2020-02-10","20-02-12","2020-02-15");
$word = array("Attend To","Explore","Unaided","dull","bad");

//User input
$start = "2020-01-01";
$end = "2020-02-07";

//Filter out dates between start and end date
$result2 = [];
$result = array_filter($dat, function($data_item, $key) use($start, $end, $word, &$result2) {
    if($data_item >= $start && $data_item <= $end){
        $result2[$key] = $word[$key];
        return true;
    }
    return false;
}, ARRAY_FILTER_USE_BOTH);

AbraCadaver's answer is perfect fit when only the filtering is needed, but this can be useful in case someone has to do extra operations in the filter callback..


问:
How to get a svg line element total length
I have a very simple svg with just one line on it

```<code><svg version="1.1" id="animation" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 640 480" xml:space="preserve" preserveAspectRatio="xMinYMin meet" baseProfile="tiny">
    <line id="line-1" style="stroke:#777777;stroke-miterlimit:10;" x1="358" y1="332.5" x2="371.3" y2="364.7"/>
</svg>
</code>```

and I use jquery to get the line and find it length with getTotalLength()

```<code>var len = $("#line-1").get(0).getTotalLength();
</code>```

but my browser keeps giving this error warning

Uncaught TypeError: $(...).get(...).getTotalLength is not a function

Can anyone tell me if line element can use getTotalLength()? If not, how can I get the length of the line.

Thanks.

here's my example: https://jsfiddle.net/chitocheng/1h5eckjh/

答:
For anyone trying to  know if in 2020 :

JQUERY (3.4.1) >> $('#lineID').get(0).getTotalLength()

JS >> document.getElementById('lineID').getTotalLength()

works on <lines/>

the answer is yes.

Browsers tested :

Firefox 76.0.1

Chromium: 81.0.4044.138 (Official Build) (64-bit)

Chrome  83.0.4103.61

Opera 68.0.3618.125

https://jsfiddle.net/mzyd4ura/2/

Body:
I have a very simple svg with just one line on it

<svg version="1.1" id="animation" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 640 480" xml:space="preserve" preserveAspectRatio="xMinYMin meet" baseProfile="tiny">
    <line id="line-1" style="stroke:#777777;stroke-miterlimit:10;" x1="358" y1="332.5" x2="371.3" y2="364.7"/>
</svg>

and I use jquery to get the line and find it length with getTotalLength()

var len = $("#line-1").get(0).getTotalLength();

but my browser keeps giving this error warning

Uncaught TypeError: $(...).get(...).getTotalLength is not a function

Can anyone tell me if line element can use getTotalLength()? If not, how can I get the length of the line.

Thanks.

here's my example: https://jsfiddle.net/chitocheng/1h5eckjh/


问:
Error using useEffect in react functional component
I am learning to use react hooks to manage state but I get the error saying
  Line 5:3:  React Hook "useEffect" is called in function "cockpit" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks

here is my code

```<code>import React, {useEffect} from "react";
import classes from "./Cockpit.module.css";

const cockpit = (props) => {
  useEffect(() => {
    console.log('Cockpit js useEffect');

  });

  const assiginedClasses = [];
  let btnClass = "";
  if (props.showPersons) {
    btnClass = classes.Red;
  }

  if (props.persons.length <= 2) {
    assiginedClasses.push(classes.red);
  }

  if (props.persons.length <= 1) {
    assiginedClasses.push(classes.bold);
  }
  return (
    <div className={classes.Cockpit}>
      <h1>Hi I'm a React App</h1>
      <p className={assiginedClasses.join(" ")}>This is really Working!</p>
      <button className={btnClass} onClick={props.clicked}>
        Toggle Name
      </button>
    </div>
  );
};

export default cockpit;
</code>```

答:
It's a linter "error" that comes from https://www.npmjs.com/package/eslint-plugin-react-hooks.

Very specifically it comes from: https://github.com/facebook/react/blob/ddcc69c83b59ef0f895aa5020196e2ae9de36133/packages/eslint-plugin-react-hooks/src/RulesOfHooks.js#L478

isDirectlyInsideComponentOrHook returns false because of an invalid component name.

```<code>        const isDirectlyInsideComponentOrHook = codePathFunctionName
          ? isComponentName(codePathFunctionName) ||
            isHook(codePathFunctionName)
          : isForwardRefCallback(codePathNode) || isMemoCallback(codePathNode);
</code>```

So then you get this error:

```<code>            } else if (codePathFunctionName) {
              // Custom message if we found an invalid function name.
              const message =
                `React Hook "${context.getSource(hook)}" is called in ` +
                `function "${context.getSource(codePathFunctionName)}" ` +
                'that is neither a React function component nor a custom ' +
                'React Hook function.' +
                ' React component names must start with an uppercase letter.';
              context.report({node: hook, message});
            }
</code>```

If your function name doesn't start with a capital letter, then react will display this "error" in your console.

Body:
I am learning to use react hooks to manage state but I get the error saying
  Line 5:3:  React Hook "useEffect" is called in function "cockpit" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks

here is my code

import React, {useEffect} from "react";
import classes from "./Cockpit.module.css";

const cockpit = (props) => {
  useEffect(() => {
    console.log('Cockpit js useEffect');

  });

  const assiginedClasses = [];
  let btnClass = "";
  if (props.showPersons) {
    btnClass = classes.Red;
  }

  if (props.persons.length <= 2) {
    assiginedClasses.push(classes.red);
  }

  if (props.persons.length <= 1) {
    assiginedClasses.push(classes.bold);
  }
  return (

Hi I'm a React App

This is really Working!

      <button className={btnClass} onClick={props.clicked}>
        Toggle Name
      </button>

  );
};

export default cockpit;

Body:
It's a linter "error" that comes from https://www.npmjs.com/package/eslint-plugin-react-hooks.

Very specifically it comes from: https://github.com/facebook/react/blob/ddcc69c83b59ef0f895aa5020196e2ae9de36133/packages/eslint-plugin-react-hooks/src/RulesOfHooks.js#L478

isDirectlyInsideComponentOrHook returns false because of an invalid component name.

        const isDirectlyInsideComponentOrHook = codePathFunctionName
          ? isComponentName(codePathFunctionName) ||
            isHook(codePathFunctionName)
          : isForwardRefCallback(codePathNode) || isMemoCallback(codePathNode);

So then you get this error:

            } else if (codePathFunctionName) {
              // Custom message if we found an invalid function name.
              const message =
                `React Hook "${context.getSource(hook)}" is called in ` +
                `function "${context.getSource(codePathFunctionName)}" ` +
                'that is neither a React function component nor a custom ' +
                'React Hook function.' +
                ' React component names must start with an uppercase letter.';
              context.report({node: hook, message});
            }

If your function name doesn't start with a capital letter, then react will display this "error" in your console.


问:
How can I have the integrated VSCode terminal not capture CTRL-E, CTRL-X, and CTRL-A?
How can I have the integrated VSCode terminal not capture CTRL-E, CTRL-X, and CTRL-A?

Actual behavior: does what the keyboard shortcuts normally do outside of terminal

Expected behavior:

CTRL-X-E should open $EDITOR in the integrated terminal, like it does in Readline-based terminals

答:
From the Command Palette I selected to view the JSON Keyboard Shortcuts, then entered this into the resulting file:

```<code>// Place your key bindings in this file to override the defaults
[
    {
        "key": "ctrl+e",
        "command": "ctrl+e",
        "when": "terminalFocus"
    },
]
</code>```

This allows me to use CTRL+E in the terminal when I have the terminal in focus, rather than it being interpreted by VS Code.

Body:
From the Command Palette I selected to view the JSON Keyboard Shortcuts, then entered this into the resulting file:

// Place your key bindings in this file to override the defaults
[
    {
        "key": "ctrl+e",
        "command": "ctrl+e",
        "when": "terminalFocus"
    },
]

This allows me to use CTRL+E in the terminal when I have the terminal in focus, rather than it being interpreted by VS Code.


问:
Why can we compare character constants?
Came across this statement in a C book, if ((letter >= 'P') && (letter <= 'S'))

It's trying to check if the letter falls between P and S (including both) and I was quite surprised to see it work.

How is it possible to do greater-than/lesser-than type operations on alphabets (character data type)?

It is a feature in only C or in other programming languages as well?

答:
"How is it possible to do greater-than/lesser-than type operations on alphabets (character data type)?"

Because the character constants refer to numeral character encoding values of f.e. the ASCII, Unicode or UTF-8 character set and are listed in the alphabetical order of the characters.

Some references:

https://en.wikipedia.org/wiki/ASCII

https://en.wikipedia.org/wiki/Unicode

https://en.wikipedia.org/wiki/UTF-8

"It is a feature in only C or in other programming languages as well?"

If they support numeral character encoding sets, where characters are listed in subsequent alpabetical order, then yes.

Note, that even the C standard does not specify that character values in encoding sets need to be in alphabetical order.

Also note that the syntax to accomplish the same effect of comparing might be completely different in other languages.

Title: Why can we compare character constants?


问:
Why .click event handler is not updated here?
I am passing a table row to a function which is supposed to update the onclick attribute on an anchor.

Whatever I have tried I am not able to set it to a new value. I can see that it is jQuery selects the anchor. But when I alert before an after, onclick attribute still points to the same value not the 'url' parameter that is provided to the function:

```<code>function modifyTrEditUrl(tr, url) {

           console.log(tr.find('td:eq(6) a')[0]);

           tr.find('td:eq(6) a')
                .attr('onclick', url); // I have tried
                                       //.click(function(e){..}) way too!

           console.log(tr.find('td:eq(6) a')[0]); //still the same value! :(
        }
</code>```

Any advices?

答:
I'm not sure, but it sounds like you may be confusing the onClick attribute with the HREF attribute. When a link is clicked, the URL in the HREF attribute is used.

The onClick attribute is really used for triggering Javascript stuff. That said, if you're using jQuery, you should really stick to the bind or live functions (which click is a wrapper for).

Body:
I am passing a table row to a function which is supposed to update the onclick attribute on an anchor.

Whatever I have tried I am not able to set it to a new value. I can see that it is jQuery selects the anchor. But when I alert before an after, onclick attribute still points to the same value not the 'url' parameter that is provided to the function:

function modifyTrEditUrl(tr, url) {

           console.log(tr.find('td:eq(6) a')[0]);

           tr.find('td:eq(6) a')
                .attr('onclick', url); // I have tried
                                       //.click(function(e){..}) way too!

           console.log(tr.find('td:eq(6) a')[0]); //still the same value! :(
        }

Any advices?


问:
Multiple fetch calls using fetchMock & `userEvent.click` within a `test.each` using React Testing Library
I'm looking to test a number of outcomes given the respons of a callback to an endpoit we are making requests to.

Given the code below:

describe('when I click the "continue to shop" button', () => {
test.only.each`
    applicationStatus                     | routeName                   | routeURL
    ${'CASH_ACCEPT'}                      | ${'Checkout Shipping'}      | ${'/checkout/shipping.page'}
    ${'DECLINED'}                         | ${'Account Rejected'}       | ${'/account/application/accountRejected.page'}
    ${'EXISTING_ACCOUNT_PROFILE_MATCHED'} | ${'Existing Account Found'} | ${'/account/accountFound.page?email=c***********4@example.com'}
    ${'a non-recognised'}                 | ${'Server Error'}           | ${'/serverError.page'}
`(
    'then the $applicationStatus response should take me to the $routeName page',
    async ({ applicationStatus, routeURL }) => {
        fetchMock.post(`/api/account-application/applications`, {
            data: {
                id: '123',
                type: 'account-application',
                attributes: {
                    applicationStatus: `${applicationStatus}`,
                    email: 't*********@example.com',
                },
            },
        });

        const component = render(<Benefits experiments={experiments} />);

        await act(async () => {
            await userEvent.click(component.getByText(/Continue to shop/i));
        });

        expect(component.getByTestId('loading-overlay'));

        // eslint-disable-next-line security/detect-non-literal-fs-filename
        expect(global.open).toBeCalledWith(`${routeURL}`, '_self');
    },
);
```

<p>I would expect each test iteration to be fired only once However, it seems that each test is faliing. It seems that the <code>userEvent.click</code> is happening more than once and is saving the previous click:</p>

<pre class="lang-js prettyprint-override"><code>Expected: "/account/accountFound.page?email=c_**\***_4@example.com", "\_self"
Received
1: "/checkout/shipping.page", "\_self"
2: "/account/application/accountRejected.page", "\_self"
3: "/account/accountFound.page?email=t**\***@example.com", "\_self"

Number of calls: 3
</code>```

My understanding is that after each test,cleanup is ran and eveything should be reset before the next. Can anyone see what I am doing wrong here? Thanks!

答:
It's expect(global.open) assertion that fails, not userEvent.click.

Jest doesn't reset spy calls by default, and no manual cleanup is performed in provided code.

Use resetAllMocks or restoreAllMocks:

```<code>afterEach(() => {
  jest.restoreAllMocks();
});
</code>```

The latter requires to set up global.open spy before each test and not only once.

Or better, enable resetMocks or restoreMocks configuration option, because cross-contamination is almost never desirable in well-written tests.

Body:
I'm looking to test a number of outcomes given the respons of a callback to an endpoit we are making requests to.

Given the code below:

describe('when I click the "continue to shop" button', () => {
test.only.each`
    applicationStatus                     | routeName                   | routeURL
    ${'CASH_ACCEPT'}                      | ${'Checkout Shipping'}      | ${'/checkout/shipping.page'}
    ${'DECLINED'}                         | ${'Account Rejected'}       | ${'/account/application/accountRejected.page'}
    ${'EXISTING_ACCOUNT_PROFILE_MATCHED'} | ${'Existing Account Found'} | ${'/account/accountFound.page?email=c***********4@example.com'}
    ${'a non-recognised'}                 | ${'Server Error'}           | ${'/serverError.page'}
`(
    'then the $applicationStatus response should take me to the $routeName page',
    async ({ applicationStatus, routeURL }) => {
        fetchMock.post(`/api/account-application/applications`, {
            data: {
                id: '123',
                type: 'account-application',
                attributes: {
                    applicationStatus: `${applicationStatus}`,
                    email: 't*********@example.com',
                },
            },
        });

        const component = render(<Benefits experiments={experiments} />);

        await act(async () => {
            await userEvent.click(component.getByText(/Continue to shop/i));
        });

        expect(component.getByTestId('loading-overlay'));

        // eslint-disable-next-line security/detect-non-literal-fs-filename
        expect(global.open).toBeCalledWith(`${routeURL}`, '_self');
    },
);

I would expect each test iteration to be fired only once However, it seems that each test is faliing. It seems that the userEvent.click is happening more than once and is saving the previous click:

Expected: "/account/accountFound.page?email=c_**\***_4@example.com", "\_self"
Received
1: "/checkout/shipping.page", "\_self"
2: "/account/application/accountRejected.page", "\_self"
3: "/account/accountFound.page?email=t**\***@example.com", "\_self"

Number of calls: 3

My understanding is that after each test,cleanup is ran and eveything should be reset before the next. Can anyone see what I am doing wrong here? Thanks!

Body:
It's expect(global.open) assertion that fails, not userEvent.click.

Jest doesn't reset spy calls by default, and no manual cleanup is performed in provided code.

Use resetAllMocks or restoreAllMocks:

afterEach(() => {
  jest.restoreAllMocks();
});

The latter requires to set up global.open spy before each test and not only once.

Or better, enable resetMocks or restoreMocks configuration option, because cross-contamination is almost never desirable in well-written tests.


问:
Return an array where the new elements are the sum of sum of distances between indices with same value in a given array
For each index in a given array I want to find the sum of sum of the distances between that index and other indices which have the same value in a given array.

So for [1,2,1,1,2,3], we would have [5,3,3,4,3,0] because

for index 0) |2-0|+|3-0| = 5, for index 1) |4-1| = 3 ,... , for index 3) |3-0|+|3-2| = 4,... etc..

Here is my attempt which gets TLE for arrays of length near 10000.

How can I make my solution more efficient?

```<code>def getDistanceMetrics(arr):
    if len(arr) > 10**5 or len(arr) < 1:
        return -1
    for z in range(len(arr)):
        if arr[z] > 10**9 or arr[z] < 1:
            return -1

    # Write your code here
    hm = collections.defaultdict(set)

    for i,value in enumerate(arr):
        hm[value].add(i)

    ans = []

    for j,val in enumerate(arr):
        tmp = 0
        for element in hm[val]:
            tmp += (j-element) if (j-element) >= 0 else element - j
        ans.append(tmp)

    return ans
</code>```

I would also appreciate knowing as to why and where my answer is slow, because to me it looks like O(n), which seems as good as you could do here.

答:
instead of iterating over arr, you can iterate over hm.
say we want to calculate the distance where hm of number one is {a1, ..., an}
and we want to calculate the answer for a_k then for all i < k we need to add a_k - a_i since a_k is greater. let's save a partial sum called p[i] (= a1 + ... a_i), you can add all the distances at once (that is adding a_k * (k) - p[k]) you can update p[k] as iterating through the set.
after this is done we will maintain a partial sum starting from the last element that is  p[k] = a_n + a_(n-1) + ... + a_k
again we iterate, but this time from the last element to the first element and add p[k] - a_k * (n-k) to the answer for a_k

This is will be done in linear time over all.

```<code># Write your code here
hm = collections.defaultdict(set)

for i,value in enumerate(arr):
    hm[value].add(i)

ans = [0] * len(arr)

for key in hm:
    p = 0
    for i in range(len(hm[key])):
        p += hm[key][i]
        ans[hm[key][i]] += hm[key][i] * (i+1) - p
    p = 0
    for i in range(len(hm[key]) - 1, -1, -1):
        p += hm[key][i]
        ans[hm[key][i]] += p - hm[key][i] * (len(hm[key]) - i)
return ans
</code>```

Body:
For each index in a given array I want to find the sum of sum of the distances between that index and other indices which have the same value in a given array.

So for [1,2,1,1,2,3], we would have [5,3,3,4,3,0] because

for index 0) |2-0|+|3-0| = 5, for index 1) |4-1| = 3 ,... , for index 3) |3-0|+|3-2| = 4,... etc..

Here is my attempt which gets TLE for arrays of length near 10000.

How can I make my solution more efficient?

def getDistanceMetrics(arr):
    if len(arr) > 10**5 or len(arr) < 1:
        return -1
    for z in range(len(arr)):
        if arr[z] > 10**9 or arr[z] < 1:
            return -1

    # Write your code here
    hm = collections.defaultdict(set)

    for i,value in enumerate(arr):
        hm[value].add(i)

    ans = []

    for j,val in enumerate(arr):
        tmp = 0
        for element in hm[val]:
            tmp += (j-element) if (j-element) >= 0 else element - j
        ans.append(tmp)

    return ans

I would also appreciate knowing as to why and where my answer is slow, because to me it looks like O(n), which seems as good as you could do here.

Body:
instead of iterating over arr, you can iterate over hm.
say we want to calculate the distance where hm of number one is {a1, ..., an}
and we want to calculate the answer for a_k then for all i < k we need to add a_k - a_i since a_k is greater. let's save a partial sum called p[i] (= a1 + ... a_i), you can add all the distances at once (that is adding a_k * (k) - p[k]) you can update p[k] as iterating through the set.
after this is done we will maintain a partial sum starting from the last element that is  p[k] = a_n + a_(n-1) + ... + a_k
again we iterate, but this time from the last element to the first element and add p[k] - a_k * (n-k) to the answer for a_k

This is will be done in linear time over all.

# Write your code here
hm = collections.defaultdict(set)

for i,value in enumerate(arr):
    hm[value].add(i)

ans = [0] * len(arr)

for key in hm:
    p = 0
    for i in range(len(hm[key])):
        p += hm[key][i]
        ans[hm[key][i]] += hm[key][i] * (i+1) - p
    p = 0
    for i in range(len(hm[key]) - 1, -1, -1):
        p += hm[key][i]
        ans[hm[key][i]] += p - hm[key][i] * (len(hm[key]) - i)
return ans