问:
drawImage() will not display image saved locally, but will display images hosted elsewhere
I've got a Vue app working but have hit a snag. I'm able to use drawImg on an image hosted elsewhere, but when saving the file and trying to load locally, it does nothing. No error, it just doesn't draw the image. I'm able to get the same image to load in a normal img tag so it isn't a path issue. Below is the code to load the image, both with examples of a saved image and the URL.

```<code>loadImg() {
    this.img = new Image();

    this.img.onload = () => {
        this.ctx.drawImage(this.img, 0, 0);
    }

    //this.img.src = '../../public/body-outline.jpg'; // does nothing
    this.img.src = 'https://www.templatesfront.com/wp-content/uploads/2016/05/human-body-outline-5641.jpg'; // works just fine
}
</code>```

And for completeness, the entire .vue file:

```<code><template>
    <v-app>
        <div align="center">
            <canvas @mousedown="startPainting" @mouseup="finishedPainting" @mousemove="draw" id="canvas"></canvas>
            <v-btn @click="clear">Clear Area</v-btn>
            <v-btn @click="saveImg">Save</v-btn>
        </div>
    </v-app>
</template>

<script>
/* eslint-disable */

export default {
    name: 'Canvas',
    components: {},
    data() {
        return {
            painting: false,
            canvas: null,
            ctx: null
        }
    },
    methods: {
    startPainting(e) {
      this.painting = true;
      this.draw(e)
    },
    finishedPainting() {
      this.painting = false;
      this.ctx.beginPath()
    },
    draw(e) {

      if(!this.painting) return

      this.ctx.lineWidth = 10;
            this.ctx.lineCap ="round"

            this.ctx.strokeStyle = 'rgba(0,255,255,0.4)';
        this.ctx.globalCompositeOperation = "multiply";
        if (this.ctx.globalCompositeOperation !== "multiply")     // use multiply if available
            this.ctx.globalCompositeOperation = 'destination-over'; // fallback mode

     this.ctx.lineTo(e.layerX,e.layerY)
     this.ctx.stroke()

     this.ctx.beginPath()
         this.ctx.moveTo(e.layerX,e.layerY)
        },
        clear() {
            this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
            this.loadImg();
        },
        saveImg() {
            let dataUrl = this.canvas.toDataURL();
            console.log(dataUrl)
        },
        loadImg() {
            this.img = new Image();
            //this.img.crossOrigin = "Anonymous";

            this.img.onload = () => {
                this.ctx.drawImage(this.img, 0, 0);
            }

            //this.img.src = '../../public/body-outline.jpg';
            this.img.src = 'https://www.templatesfront.com/wp-content/uploads/2016/05/human-body-outline-5641.jpg'
        }
  },
    mounted() {
        this.canvas = document.getElementById("canvas");
        this.ctx = canvas.getContext("2d");

        this.loadImg();

        // Resize canvas
        this.canvas.height = 400;
        this.canvas.width = 800;
    }
}
</script>

<style scoped>

#canvas {
    border: 1px solid gray;
    background-color: white;
}

</style>
</code>```

答:
This is because you are not using require for the path. You can use the path directly:

```<code>this.img.src = '/body-outline.jpg';
</code>```

Body:
I've got a Vue app working but have hit a snag. I'm able to use drawImg on an image hosted elsewhere, but when saving the file and trying to load locally, it does nothing. No error, it just doesn't draw the image. I'm able to get the same image to load in a normal img tag so it isn't a path issue. Below is the code to load the image, both with examples of a saved image and the URL.

loadImg() {
    this.img = new Image();

    this.img.onload = () => {
        this.ctx.drawImage(this.img, 0, 0);
    }

    //this.img.src = '../../public/body-outline.jpg'; // does nothing
    this.img.src = 'https://www.templatesfront.com/wp-content/uploads/2016/05/human-body-outline-5641.jpg'; // works just fine
}

And for completeness, the entire .vue file:

<template>
    <v-app>

            <canvas @mousedown="startPainting" @mouseup="finishedPainting" @mousemove="draw" id="canvas"></canvas>
            <v-btn @click="clear">Clear Area</v-btn>
            <v-btn @click="saveImg">Save</v-btn>

    </v-app>
</template>

Body:
This is because you are not using require for the path. You can use the path directly:

this.img.src = '/body-outline.jpg';


来源: stackexchange

问:
How do I delete an instance from a class by method in python?
The problem I'm facing is that I have person_1 Instance
And I create a destroyed static method that should delete any instance
That passed to it as y parameter but the instance still exists.

I want person_1 to be removed and python should give an error message.

Thanks in advance

```<code>class population:
    """ This class is used
    To adds and delete people """

    x = 0

    def __init__(self,name):
        self.name = name
        print(f'Initilaizing {name}\n Total_persons. {population.x}')

        population.x += 1

    @classmethod
    # This class method is used to adds a new instance to the population class.
    def constructor(cls, y):
        population.x += 1
        return cls(y)

    @staticmethod
    # This static method is used to remove an instance from the population class.
    def destroyed(k):
        del k
        population.x -= 1
        print(f'Total_persons after destroyed procedure. {population.x}')

person_1 = population('mohammed')
print(person_1.name)

population.destroyed(person_1)

print(person_1.name)
</code>```

答:
The problem you're running into is caused by the fact that del k in your destroyed function is killing off only that instance of the object, not the one outside of the function scope. Python allows you to add functionality to a deleting an object with the __del__ function.

Implementing as such:

```<code>    def __del__(self):
        population.x -= 1
        print(f'Total_persons after destroyed procedure. {population.x}')
</code>```

Will allow you to replace population.destroyed(person_1) with del person_1 to get the result you're looking for.

ContentLicense: CC BY-SA 4.0

Body:
The problem I'm facing is that I have person_1 Instance
And I create a destroyed static method that should delete any instance
That passed to it as y parameter but the instance still exists.

I want person_1 to be removed and python should give an error message.

Thanks in advance

class population:
    """ This class is used
    To adds and delete people """

    x = 0

    def __init__(self,name):
        self.name = name
        print(f'Initilaizing {name}\n Total_persons. {population.x}')

        population.x += 1

    @classmethod
    # This class method is used to adds a new instance to the population class.
    def constructor(cls, y):
        population.x += 1
        return cls(y)

    @staticmethod
    # This static method is used to remove an instance from the population class.
    def destroyed(k):
        del k
        population.x -= 1
        print(f'Total_persons after destroyed procedure. {population.x}')

person_1 = population('mohammed')
print(person_1.name)

population.destroyed(person_1)

print(person_1.name)

Body:
The problem you're running into is caused by the fact that del k in your destroyed function is killing off only that instance of the object, not the one outside of the function scope. Python allows you to add functionality to a deleting an object with the __del__ function.

Implementing as such:

    def __del__(self):
        population.x -= 1
        print(f'Total_persons after destroyed procedure. {population.x}')

Will allow you to replace population.destroyed(person_1) with del person_1 to get the result you're looking for.


问:
where are C# setting file values are saved? it's not in the appName.config
I'm using the settings files in C#. and cannot find where are the values saved.
the app works perfect but when I want to change manually the values in the appName.cpnfig it doesn't load/save the values there but in some other place.
does anyone know where?</p>

答:
Possible duplicate of Again, user config files C#.

It depend on your Windows version.  In Windows 7, I have it under C:\Users\tim\AppData\Local... as user.config.  See http://msdn.microsoft.com/En-US/library/8eyb2ct1.aspx for detailed information.

Settings File Locations

The location of the app.exe.config and
  user.config files will differ based on
  how the application is installed. For
  a Windows Forms-based application
  copied onto the local computer,
  app.exe.config will reside in the same
  directory as the base directory of the
  application's main executable file,
  and user.config will reside in the
  location specified by the
  Application.LocalUserAppDataPath
  property. For an application installed
  by means of ClickOnce, both of these
  files will reside in the ClickOnce
  Data Directory underneath
  %InstallRoot%\Documents and
  Settings\username\Local Settings.

The storage location of these files is
  slightly different if a user has
  enabled roaming profiles, which
  enables a user to define different
  Windows and application settings when
  he or she is using other computers
  within a domain. In that case, both
  ClickOnce applications and
  non-ClickOnce applications will have
  their app.exe.config and user.config
  files stored under
  %InstallRoot%\Documents and
  Settings\username\Application Data.

For more information about how the
  Application Settings feature works
  with the new deployment technology,
  see ClickOnce and Application
  Settings. For more information about
  the ClickOnce Data Directory, see
  Accessing Local and Remote Data in
  ClickOnce Applications.

ContentLicense: CC BY-SA 3.0


问:
Extract tables from ppt(x) in R
There are tables in ppt or pptx, and I want to extract them as data.frames in R. Any solutions? Thanks.

Alternatives: Turn ppt(x) to pdf in R, and extract them using other packages. Any packages to turn ppt to pdf?

答:
Hope this  will work for you. However, code is in python. You can easily modify for R.</p>

```<code>prs = Presentation((path_to_presentation))
# text_runs will be populated with a list of strings,
# one for each text run in presentation
text_runs = []
for slide in prs.slides:
    for shape in slide.shapes:
        if not shape.has_table:
            continue
        tbl = shape.table
        row_count = len(tbl.rows)
        col_count = len(tbl.columns)
        for r in range(0, row_count):
            for c in range(0, col_count):
                cell = tbl.cell(r,c)
                paragraphs = cell.text_frame.paragraphs
                for paragraph in paragraphs:
                    for run in paragraph.runs:
                        text_runs.append(run.text)

print(text_runs)```
</code>```

Title: Extract tables from ppt(x) in R

Body:
Hope this  will work for you. However, code is in python. You can easily modify for R.

prs = Presentation((path_to_presentation))
# text_runs will be populated with a list of strings,
# one for each text run in presentation
text_runs = []
for slide in prs.slides:
    for shape in slide.shapes:
        if not shape.has_table:
            continue
        tbl = shape.table
        row_count = len(tbl.rows)
        col_count = len(tbl.columns)
        for r in range(0, row_count):
            for c in range(0, col_count):
                cell = tbl.cell(r,c)
                paragraphs = cell.text_frame.paragraphs
                for paragraph in paragraphs:
                    for run in paragraph.runs:
                        text_runs.append(run.text)

print(text_runs)```


问:
What is the vertical equivalent of CSS font-kerning?
I have a font that is misaligned since the baseline is below y, g, j, etc. as opposed to regular baseline.

I've tried messing around with a few properties (line-height, height, display: inline-block, vertical-align: text-top) but can't get the font as far centered as it should be.

Is there a CSS equivalent of kerning, but in a vertical direction? Is there another way to uniformly fix this font via CSS?

答:
This is a very old question, but the solution I ended up using (as with most CSS) was to create a wrapper and pad asymmetrically, therefore raising the apparent baseline.

The main use-case was with headers with large border-radius causing slight (visual) vertical mis-alignment.


问:
Javascript/Typescript - Remove elements of an array that exists in another array
I have two arrays:

```<code>const arr1 = ['abc', 'def', 'ghi', 'jkl'];
const arr2 = ['123', 'abc', 'jkl', '456', '789'];
</code>```

What would be the cleanest way to return arr2 without the elements of arr1?

I guess arr2.filter(x => arr1.indexOf(x) < 0) would work, but is there a cleaner way?

答:
You can do a very slight optimization by using includes.

arr2.filter(x => !arr1.includes(x))
```

<p>Keep in mind this can become a slow operation for large arrays <code>O(mn)</code>. You can optimize for large data sets by using a <code>Set</code>.</p>

<pre class="lang-js prettyprint-override"><code>const arr1_set = new Set(arr1) // O(n) space
arr2.filter(x => !arr1_set.has(x)) // O(n) time
</code>```

More info here: Computing set intersection in linear time?

Body:
I have two arrays:

const arr1 = ['abc', 'def', 'ghi', 'jkl'];
const arr2 = ['123', 'abc', 'jkl', '456', '789'];

What would be the cleanest way to return arr2 without the elements of arr1?

I guess arr2.filter(x => arr1.indexOf(x) < 0) would work, but is there a cleaner way?

Body:
You can do a very slight optimization by using includes.

arr2.filter(x => !arr1.includes(x))

Keep in mind this can become a slow operation for large arrays O(mn). You can optimize for large data sets by using a Set.

const arr1_set = new Set(arr1) // O(n) space
arr2.filter(x => !arr1_set.has(x)) // O(n) time

More info here: Computing set intersection in linear time?


问:
Remove array element in MongoDB in Go
I have data in MongoDB like below:

{"_id":{"$oid":"5ed0cb4cb8d5570916d1ee7e"},"rolecode":"DHBK1_ROLE_05","productid":"XYZ_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3","DHBK1_FUNC_4"],"comid":"DHBK1"}
 {"_id":{"$oid":"5ed0cc67b8d5570916d1ef86"},"rolecode":"DHBK1_ROLE_06","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0d23cb8d5570916d1f4c8"},"rolecode":"DHBK1_ROLE_09","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1"],"comid":"DHBK1"}

And I have Mongo shell to remove DHBK1_FUNC_1 element from array.

Here is my Mongo shell:

```<code>db.company_role_function.update(
  { },
  { $pull: { functioncodelist: { $in: ['DHBK1_FUNC_1'] }}},
  { multi: true }
)
</code>```

Then I write Go code to implement my Mongo shell.

Here is my code:

```<code>    package main
    import (
        "context"
        "fmt"
        "strings"
        "time"
        "gopkg.in/mgo.v2"
    )
    func main() {
        var functionCode []string
        functionCode = append(functionCode, "DHBK1_FUNC_1")
        fmt.Println(functionCode)
        deleteArray(functionCode)
     }
    func deleteArray(functionCode []string) {
        session, err := mgo.Dial("mongo_uri_connect")
        if err != nil {
        panic(err)
     }
    c := session.DB("users").C("company_role_function")
    err = c.Update(bson.M{}, bson.M{"$pull": bson.M{"functioncodelist": bson.M{"$in": functionCode}}}, bson.M{"multi": true})
    if err != nil {
    fmt.Println(err)
    }
}
</code>```

When I run my code, it showed this error:

```<code># command-line-arguments
 .\main.go:86:16: too many arguments in call to c.Update
    have (primitive.M, primitive.M, primitive.M)
    want (interface {}, interface {})
</code>```

When I remove bson.M{"multi": true} in line err = c.Update(bson.M{}, bson.M{"$pull": bson.M{"functioncodelist": bson.M{"$in": functionCode}}}, bson.M{"multi": true}), it worked but doesn't remove any element DHBK1_FUNC_1.

Thank you

答:
I try to use Mongo-go-driver and it worked.

But Mgo still doesn't work.

Here is my code:

```<code>   func deleteArrayDriver(functionCode []string) {
   ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
   client, err := mongo.Connect(ctx, options.Client().ApplyURI("link"))
   if err != nil {
       panic(err)
   }
   defer client.Disconnect(ctx)
   database := client.Database("users")
   users := database.Collection("company_role_function")
   _, err = users.UpdateMany(ctx, bson.D{{}}, bson.M{"$pull": bson.M{"functioncodelist": bson.M{"$in": functionCode}}})
   if err != nil {
       panic(err)
   }
}
</code>```

Title: Remove array element in MongoDB in Go

Body:
I have data in MongoDB like below:

{"_id":{"$oid":"5ed0cb4cb8d5570916d1ee7e"},"rolecode":"DHBK1_ROLE_05","productid":"XYZ_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3","DHBK1_FUNC_4"],"comid":"DHBK1"}
 {"_id":{"$oid":"5ed0cc67b8d5570916d1ef86"},"rolecode":"DHBK1_ROLE_06","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3"],"comid":"DHBK1"}
{"_id":{"$oid":"5ed0d23cb8d5570916d1f4c8"},"rolecode":"DHBK1_ROLE_09","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1"],"comid":"DHBK1"}

And I have Mongo shell to remove DHBK1_FUNC_1 element from array.

Here is my Mongo shell:

db.company_role_function.update(
  { },
  { $pull: { functioncodelist: { $in: ['DHBK1_FUNC_1'] }}},
  { multi: true }
)

Then I write Go code to implement my Mongo shell.

Here is my code:

    package main
    import (
        "context"
        "fmt"
        "strings"
        "time"
        "gopkg.in/mgo.v2"
    )
    func main() {
        var functionCode []string
        functionCode = append(functionCode, "DHBK1_FUNC_1")
        fmt.Println(functionCode)
        deleteArray(functionCode)
     }
    func deleteArray(functionCode []string) {
        session, err := mgo.Dial("mongo_uri_connect")
        if err != nil {
        panic(err)
     }
    c := session.DB("users").C("company_role_function")
    err = c.Update(bson.M{}, bson.M{"$pull": bson.M{"functioncodelist": bson.M{"$in": functionCode}}}, bson.M{"multi": true})
    if err != nil {
    fmt.Println(err)
    }
}

When I run my code, it showed this error:

# command-line-arguments
 .\main.go:86:16: too many arguments in call to c.Update
    have (primitive.M, primitive.M, primitive.M)
    want (interface {}, interface {})

When I remove bson.M{"multi": true} in line err = c.Update(bson.M{}, bson.M{"$pull": bson.M{"functioncodelist": bson.M{"$in": functionCode}}}, bson.M{"multi": true}), it worked but doesn't remove any element DHBK1_FUNC_1.

Thank you

Body:
I try to use Mongo-go-driver and it worked.

But Mgo still doesn't work.

Here is my code:

   func deleteArrayDriver(functionCode []string) {
   ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
   client, err := mongo.Connect(ctx, options.Client().ApplyURI("link"))
   if err != nil {
       panic(err)
   }
   defer client.Disconnect(ctx)
   database := client.Database("users")
   users := database.Collection("company_role_function")
   _, err = users.UpdateMany(ctx, bson.D{{}}, bson.M{"$pull": bson.M{"functioncodelist": bson.M{"$in": functionCode}}})
   if err != nil {
       panic(err)
   }
}


答:
Code may have changed since @quasiben's answer.  According to the client's constructor, the config name is different.

The timeout can be set done explicitly:

```<code>Client(..., timeout="50s")
</code>```

or in the configs ("connect" instead of "tcp")

```<code>import dask
import distributed
dask.config.set({"distributed.comm.timeouts.connect": "50s"})
</code>```

Title: Dask Distributed Client - ERROR - Failed to reconnect to scheduler after 10.00 seconds, closing client

Body:
I am doing a very simple data transformation with Dask_ML and I am getting this error, I was wondering if anyone has encountered this. Looks like a system setting that can be modified?

df.head()

ReportDate_Time 2015-05-01  2015-06-01  2015-07-01  2015-08-01  2015-09-01  2015-10-01  2015-11-01  2015-12-01  2016-01-01  2016-02-01  ... 2017-04-01  2017-05-01  2017-06-01  2017-08-01  2017-09-01  2017-10-01  2017-11-01  2017-12-01  2018-01-01  2018-02-01
0   33.0    32.0    32.0    24.0    24.0    32.0    31.0    31.0    31.0    35.0    ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
1   670.0   978.0   1061.0  1048.0  525.0   936.0   804.0   1067.0  859.0   647.0   ... 407.0   457.0   517.0   388.0   345.0   428.0   688.0   1486.0  1090.0  0.0
2   132.0   130.0   127.0   137.0   92.0    96.0    112.0   124.0   126.0   112.0   ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
3   206.0   259.0   207.0   181.0   74.0    142.0   125.0   172.0   138.0   194.0   ... 188.0   211.0   239.0   179.0   159.0   197.0   318.0   315.0   189.0   190.0
4   290.0   311.0   401.0   381.0   138.0   315.0   275.0   407.0   408.0   419.0   ... 76.0    56.0    159.0   16.0    0.0 0.0 213.0   123.0   4.0 3.0
5 rows × 33 columns

from dask_ml.preprocessing import StandardScaler

scaler = StandardScaler().fit_transform(df_pivot)

Gives Error:

CancelledError:
distributed.client - ERROR - Failed to reconnect to scheduler after 10.00 seconds, closing client
distributed.utils - ERROR -
Traceback (most recent call last):
  File "/home/user/.local/lib/python3.6/site-packages/distributed/utils.py", line 662, in log_errors
    yield
  File "/home/user/.local/lib/python3.6/site-packages/distributed/client.py", line 1290, in _close
    await gen.with_timeout(timedelta(seconds=2), list(coroutines))
concurrent.futures._base.CancelledError
distributed.utils - ERROR -
Traceback (most recent call last):
  File "/home/user/.local/lib/python3.6/site-packages/distributed/utils.py", line 662, in log_errors
    yield
  File "/home/user/.local/lib/python3.6/site-packages/distributed/client.py", line 1019, in _reconnect
    await self._close()
  File "/home/user/.local/lib/python3.6/site-packages/distributed/client.py", line 1290, in _close
    await gen.with_timeout(timedelta(seconds=2), list(coroutines))
concurrent.futures._base.CancelledError

Any ideas?

Body:
Code may have changed since @quasiben's answer.  According to the client's constructor, the config name is different.

The timeout can be set done explicitly:

Client(..., timeout="50s")

or in the configs ("connect" instead of "tcp")

import dask
import distributed
dask.config.set({"distributed.comm.timeouts.connect": "50s"})


问:
onKeyDown get value from e.target.value?
What's wrong with my way to handle input in react? I want to detect keycode and prevent them to be entered into the input, but now below code doesn't seem working.

```<code>const Input = ({ placeholder }) => {   const [inputValue, setInputValue] = useState("");

  const handleKeyDown = e => {
    console.log(e.target.value);
    if ([188].includes(e.keyCode)) {
      console.log("comma");
    } else {
      setInputValue(e.target.value);
    }   };

  return (
    <div>
      <input
        type="text"
        value={inputValue}
        onKeyDown={handleKeyDown}
        placeholder={placeholder}
      />
    </div>   ); };
</code>```

https://codesandbox.io/s/ancient-waterfall-43not?file=/src/App.js

答:
I think you should not use the onKeyDown event on this case to filter your input. The reason is that someone could simply copy and paste the content into the input. So it would not filter the comma character.

You should use the onChange event and add a Regex to test if the input is valid.

```<code>const Input = ({ placeholder }) => {
  const [inputValue, setInputValue] = useState("");

  const handleChange = e => {
    const filteredInput = e.target.value.replace(/[^\w\s]/gi, "");
    setInputValue(filteredInput);
  };

  return (
    <div>
      <input
        type="text"
        value={inputValue}
        onChange={handleChange}
        placeholder={placeholder}
      />
    </div>
  );
};
</code>```

But how it works...

So the regex is currently allowing any word, digit (alphanumeric) and whitespaces. You could for example extend the whitelist to allow @ by doing const filteredInput = e.target.value.replace(/[^\w\s@]/gi, ""); Any rule inside the [^] is allowed. You can do some regex testing here https://regexr.com/55rke

Also you can test my example at: https://codesandbox.io/s/nice-paper-40dou?file=/src/App.js

Body:
What's wrong with my way to handle input in react? I want to detect keycode and prevent them to be entered into the input, but now below code doesn't seem working.

const Input = ({ placeholder }) => {   const [inputValue, setInputValue] = useState("");

  const handleKeyDown = e => {
    console.log(e.target.value);
    if ([188].includes(e.keyCode)) {
      console.log("comma");
    } else {
      setInputValue(e.target.value);
    }   };

  return (

      <input
        type="text"
        value={inputValue}
        onKeyDown={handleKeyDown}
        placeholder={placeholder}
      />

   ); };

https://codesandbox.io/s/ancient-waterfall-43not?file=/src/App.js

Body:
I think you should not use the onKeyDown event on this case to filter your input. The reason is that someone could simply copy and paste the content into the input. So it would not filter the comma character.

You should use the onChange event and add a Regex to test if the input is valid.

const Input = ({ placeholder }) => {
  const [inputValue, setInputValue] = useState("");

  const handleChange = e => {
    const filteredInput = e.target.value.replace(/[^\w\s]/gi, "");
    setInputValue(filteredInput);
  };

  return (
    <div>
      <input
        type="text"
        value={inputValue}
        onChange={handleChange}
        placeholder={placeholder}
      />
    </div>
  );
};

But how it works...

So the regex is currently allowing any word, digit (alphanumeric) and whitespaces. You could for example extend the whitelist to allow @ by doing const filteredInput = e.target.value.replace(/[^\w\s@]/gi, ""); Any rule inside the [^] is allowed. You can do some regex testing here https://regexr.com/55rke

Also you can test my example at: https://codesandbox.io/s/nice-paper-40dou?file=/src/App.js


问:
Can't change nav-link color in bootstrap 4
```<code><nav id="section_navbar" class="navbar navbar-expand-lg fixed-top">
        <div class="mx-auto my-2 order-0 order-md-1 position-relative">
            <div id="top_logo" class="container-fluid">
                <span>VirtualQR</span>
            </div>
        </div>
        <div class="navbar-collapse collapse w-100 dual-collapse2 order-2 order-md-1">
            <ul class="navbar-nav ml-auto">
                <li class="nav-item">
                    <a class="nav-link" href="#section_navbar">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#section_howdoesitwork">How does it work?</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#section_pricing">Pricings</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#section_contact">Contacts</a>
                </li>
            </ul>
</code>```

I can't get the nav-link to change color. I've tried other posts solutions but couldn't get it to work anyways.
I don't know if it has something to do with my code.

答:
Add inline css after each nav-link as below:

Home```

Body:
                VirtualQR

                    Home

                    How does it work?

                    Pricings

                    Contacts

I can't get the nav-link to change color. I've tried other posts solutions but couldn't get it to work anyways.
I don't know if it has something to do with my code.

Body:
Add inline css after each nav-link as below:

<a class="nav-link" href="#section_navbar" style="color: red;">Home</a>


问:
How can I scrape this page with selenium and chromedriver in python language?
I'm trying to scrape data from the website “http://www.nmpa.gov.cn/” by using selenium and chromedriver. When I was running the code, chromedriver succeeded in inputing the url but couldn't load the page, displaying a blank page. I tried to switch the target website into google.com and succeeded in scraping. I concluded that the target website server detected selenium and refused sending back data. So how can I scrape the data from website with selenium and chromedriver in python language. I'm quite a Python beginner, thank you for your kind help in advance. Here is my simple code:

```<code>from selenium import webdriver
my_driver_path = r"C:\python chrome driver\chromedriver.exe"
driver = webdriver.Chrome(executable_path=my_driver_path)
driver.get('http://www.nmpa.gov.cn/')
</code>```

here is the photo of the issue:
enter image description here

答:
The issue here is more on HTML than on Python.

If you check the source code of the page (you can do this by adding print(driver.page_source), you will see that it contains a meta tag with the http-equiv attribute set to "refresh":

<title>NMPA</title>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312"><meta http-equiv="refresh" content="0;URL=/WS04/CL2042/">

```

What this tag does is direct the browser to go to the given URL (/WS04/CL2042/, in a badly formatted attribute that the browser is luckily able to understand). So, instead of scraping http://www.nmpa.gov.cn/, you have to scrape http://www.nmpa.gov.cn/WS04/CL2042/.

If you change your code to access this other link, you will see that then you can get the whole page. You can either hard-code the new link or safely concatenate the first link with the "refresh" destination with a method like urllib.parse.join(): https://docs.python.org/3.7/library/urllib.parse.html#urllib.parse.urljoin.

Body:
I'm trying to scrape data from the website “http://www.nmpa.gov.cn/” by using selenium and chromedriver. When I was running the code, chromedriver succeeded in inputing the url but couldn't load the page, displaying a blank page. I tried to switch the target website into google.com and succeeded in scraping. I concluded that the target website server detected selenium and refused sending back data. So how can I scrape the data from website with selenium and chromedriver in python language. I'm quite a Python beginner, thank you for your kind help in advance. Here is my simple code:

from selenium import webdriver
my_driver_path = r"C:\python chrome driver\chromedriver.exe"
driver = webdriver.Chrome(executable_path=my_driver_path)
driver.get('http://www.nmpa.gov.cn/')

here is the photo of the issue:
enter image description here

Body:
The issue here is more on HTML than on Python.

If you check the source code of the page (you can do this by adding print(driver.page_source), you will see that it contains a meta tag with the http-equiv attribute set to "refresh":

<HTML><HEAD><title>NMPA</title></HEAD>
<body>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"><meta http-equiv="refresh" content="0;URL=/WS04/CL2042/">
</HTML>

What this tag does is direct the browser to go to the given URL (/WS04/CL2042/, in a badly formatted attribute that the browser is luckily able to understand). So, instead of scraping http://www.nmpa.gov.cn/, you have to scrape http://www.nmpa.gov.cn/WS04/CL2042/.

If you change your code to access this other link, you will see that then you can get the whole page. You can either hard-code the new link or safely concatenate the first link with the "refresh" destination with a method like urllib.parse.join(): https://docs.python.org/3.7/library/urllib.parse.html#urllib.parse.urljoin.


问:
General error: 1005 Can't create table ,Foreign key constraint is incorrectly formed in laravel
why laravel schema reply

[Illuminate\Database\QueryException]
    SQLSTATE[HY000]: General error: 1005 Can't create table test.#sql-13cc_d0 (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table cities add constrai
    nt cities_provinces_id_foreign foreign key (provinces_id) references provinces (id) on delete cascade)

[PDOException]   SQLSTATE[HY000]: General error: 1005 Can't create
  table test.#sql-13cc_d0 (errno: 150 "Foreign key constraint is
  incorrectly formed")

first table

```<code>Schema::create('provinces', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->boolean('is_enable');
        $table->boolean('is_deletable');
        $table->boolean('is_editable');
        $table->boolean('deleted');
        $table->timestamps();
    });
</code>```

second table

```<code>    Schema::create('cities', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('province_id')->unsigned()->index();
        $table->boolean('is_enable');
        $table->boolean('is_deletable');
        $table->boolean('is_editable');
        $table->boolean('deleted');
        $table->timestamps();

        $table->foreign('province_id')
            ->references('id')->on('provinces')
            ->onDelete('cascade');

    });
</code>```

答:
The time go ahead but i will comment something else.

Andile is right! You must have the same type. In this case, the foreign key should have the type bigInteger because you have bigIncrements on the reference table.

I think thats the solution for a little and boring debug. (sorry for my english)

Body:
why laravel schema reply

[Illuminate\Database\QueryException]
    SQLSTATE[HY000]: General error: 1005 Can't create table test.#sql-13cc_d0 (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table cities add constrai
    nt cities_provinces_id_foreign foreign key (provinces_id) references provinces (id) on delete cascade)

[PDOException]   SQLSTATE[HY000]: General error: 1005 Can't create
  table test.#sql-13cc_d0 (errno: 150 "Foreign key constraint is
  incorrectly formed")

first table

Schema::create('provinces', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->boolean('is_enable');
        $table->boolean('is_deletable');
        $table->boolean('is_editable');
        $table->boolean('deleted');
        $table->timestamps();
    });

second table

    Schema::create('cities', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('province_id')->unsigned()->index();
        $table->boolean('is_enable');
        $table->boolean('is_deletable');
        $table->boolean('is_editable');
        $table->boolean('deleted');
        $table->timestamps();

        $table->foreign('province_id')
            ->references('id')->on('provinces')
            ->onDelete('cascade');

    });


问:
How do I indent part of the text in a UITextView
I want to indent part of the text in a UITextView

Original:

```<code>Paragraph Here:
Hello World this is just a test.
Hello World this is just a test.
Hello World this is just a test
</code>```

How do I make it show up like this

```<code>Paragraph Here:
    Hello World this is just a test.
    Hello World this is just a test.
    Hello World this is just a test
</code>```

I don't want to use spaces in the beggining because if the device is really small it will mess it all up

答:
For anyone else looking at this problem, I found a solution on this blog:

https://bendodson.com/weblog/2018/08/09/bulleted-lists-with-uilabel/

"The bulk of the heavy lifting is done by an NSParagraphStyle
  attribute called headIndent which adds a fixed amount of padding to
  all but the first line of a paragraph"

Body:
I want to indent part of the text in a UITextView

Original:

Paragraph Here:
Hello World this is just a test.
Hello World this is just a test.
Hello World this is just a test

How do I make it show up like this

Paragraph Here:
    Hello World this is just a test.
    Hello World this is just a test.
    Hello World this is just a test

I don't want to use spaces in the beggining because if the device is really small it will mess it all up


问:
How to give the GoogleMap API inside a fragment a specific map seach
So, I basically put a GoogleMaps API inside a fragment in my app, and I want to give it a specific default search like we do with Intent, but in this case im using fragment instead of an intent.`public class LocalGymsFragment extends Fragment {</p>

```<code>    MapView mMapView;
    private GoogleMap googleMap;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_local_gyms, container, false);

        mMapView = (MapView) rootView.findViewById(R.id.mapView);
        mMapView.onCreate(savedInstanceState);

        mMapView.onResume(); // needed to get the map to display immediately

        try {
            MapsInitializer.initialize(getActivity().getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }

        mMapView.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap mMap) {
                googleMap = mMap;

                // For dropping a marker at a point on the Map
                LatLng sydney = new LatLng(-34, 151);
                googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));

                // For zooming automatically to the location of the marker
                CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
                googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            }
        });

        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }
}`
</code>```

答: I suggest that you try implementing the GoogleMaps API on a constraint layout or new GoogleMaps Activity. This is because Fragments aren't just a cup of tea. It is tough implementing this on fragments.</p>

Body:
So, I basically put a GoogleMaps API inside a fragment in my app, and I want to give it a specific default search like we do with Intent, but in this case im using fragment instead of an intent.`public class LocalGymsFragment extends Fragment {

    MapView mMapView;
    private GoogleMap googleMap;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_local_gyms, container, false);

        mMapView = (MapView) rootView.findViewById(R.id.mapView);
        mMapView.onCreate(savedInstanceState);

        mMapView.onResume(); // needed to get the map to display immediately

        try {
            MapsInitializer.initialize(getActivity().getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }

        mMapView.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap mMap) {
                googleMap = mMap;

                // For dropping a marker at a point on the Map
                LatLng sydney = new LatLng(-34, 151);
                googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));

                // For zooming automatically to the location of the marker
                CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
                googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            }
        });

        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }
}`


问:
How do I know which requirements my server needs for my database?
I need to reduce the cost of servers.
the current server has the application
web, the database. the technical characteristics in general are

5tb

16 cpus

30gb ram

the current application does not exceed 100 users per day, the database weighs approx 30 GB. for these reasons the current server expense seems too much to me. I checked in digital ocean droplet and proposed to have the web application in an 8 CPUs, 16 GB ram, 1tb. the database in a 4 CPUs, 16 GB ram, 240 GB solid disk. But how can I know if what I am proposing is correct? to make the server change. thanks for your help.

答:
Nobody can tell you the size of equipment you would use because this is totally dependent upon your application and how it is used.

For example, some applications are CPU-heavy (doing video processing), some require a lot of memory (keeping lots of data accessible), some are disk-dependent (doing database transactions). The "shape" of every application is different. Your application might be able to take advantage of multiple CPUs, or perhaps it is only using some of them.

Also, how users interact with every application is different. People use Facebook different to a banking app, different to a gaming website. If your 100 users are all in the same timezone, then usage will be different to having them spread around the world.

The only way to know what specification is require is either to monitor live traffic on the website and observe how CPU, RAM and disk is used, or simulate levels of traffic to reproduce what users typically do on the website and then measure the behaviour of the system.

Then there is the question of reliability. Consider whether you willing to run everything on one server, where the app might be unavailable if something goes wrong. Or perhaps you need high availability to ensure uptime, but at a greater cost.

Since you appear to be cost-conscious, I would recommend:

Monitor your current system (CPU, RAM, network, disk) during periods of normal usage.

If some aspects seem over-provisioned, then reduce them (eg if CPU never goes above 40%, reduce it). Check whether all CPUs are being used.

Use some form of continual monitoring to notify you when the application is not behaving as desired.

Keep log files to allow you to deep-dive into what might be causing the application problems.


问:
Bulk update via raw query in TypeORM
How can I do bulk update via raw query in TypeORM?

For example we have model User with property name

How can I change names of few users in one transaction?

typeorm version: 0.2.7

database: postgress

答:
To bulk update, you can use update with set method, it is always recommended to not use raw queries when you can use orm functions.

import {getConnection, In} from "typeorm";
const userIds = [1,2,3];

await getConnection()
  .createQueryBuilder()
  .update(User)
  .set({ isaSeniorCitizen: true })
  .where({ id: In(userIds) })
  .execute();

```

Title: Bulk update via raw query in TypeORM


问:
How do I store the values from my sliders to be stored as an integer that the object creation can use
In this code, I have an object creation menu that takes in values from a slider and uses that in the creation of the primitive - How can I actually get the sliders to store the number displayed as right now it just does nothing.

I could remove the sliders but ideally, id like to have them for a nicer user interface

```<code>import maya.cmds as mt

def ShowUI():

    if mt.window("Main", exists = True):
        mt.deleteUI("Main")

    mt.window("Main", title = "Maya Primitives", w = 300, h = 500)
    mt.columnLayout("MainLayout", w = 300, h =500)
    mt.optionMenu("PolygonMenu", w = 250, label = "Polygon Selection:")
    mt.menuItem(label = "Sphere")
    mt.menuItem(label = "Cube")
    mt.menuItem(label = "Cylinder")
    mt.button("Create", label = "Create", w = 300, command=ObjectCreation)
    mt.button("Delete", label = "Delete", w = 300, command=DeleteButton)
    mt.button("Clear", label = "Clear", w = 300, command=SceneClear)
    mt.showWindow("Main")

def DeleteButton(*args):
    mt.delete()

def SceneClear(*args):
    mt.delete(all=True, c=True)

def ObjectCreation(*args):
    currentValue = mt.optionMenu("PolygonMenu", query=True, value=True)
    if currentValue == "Sphere":
        SphereSlider()
        SphereRadius = mt.intSliderGrp(Sphradius, q = True, Value=True)
        finalSphere= mt.polySphere(r=SphereRadius, name = "Sphere", ch=False)

    elif currentValue == "Cube":
        CubeSlider()
        CubeWidth = mt.intSliderGrp(CubeW, q = True, Value=True)
        CubeHeight = mt.intSliderGrp(CubeH, q = True, Value=True)
        CubeDepth = mt.intSliderGrp(CubeD, q = True, Value=True)
        finalSphere= mt.polyCube(w=CubeWidth, h=CubeHeight, d=CubeDepth, name = "Cube", ch=False)

    elif currentValue == "Cylinder":
        CylinderSlider()
        CyclinderRadius =  mt.intSliderGrp(Cylradius, q = True, Value=True)
        CyclinderHeight =  mt.intSliderGrp(CylH, q = True, Value=True)
        finalCylinder= mt.polyCylinder(r=CylinderRadius, h=CylinderHeight, name = "Cylinder", ch=False)

def SphereSlider():
    Sphradius = mt.intSliderGrp(l="Radius",min=0,max=25, field=True)

def CubeSlider():
    CubeW = mt.intSliderGrp(l="Width", min=0, max=25, field=True)
    CubeH = mt.intSliderGrp(l="Height", min=0, max=25, field=True)
    CubeD = mt.intSliderGrp(l="Depth", min=0, max=25, field=True)

def CylinderSlider():
    Cylradius = mt.intSliderGrp(l="Radius",min=0,max=25, field=True)
    CylH = mt.intSliderGrp(l="Height", min=0, max=25, field=True)

ShowUI()
</code>```

答:
okay so to create a slider you use this command :

```<code>sphere_slider = mt.intSliderGrp(l="Radius",min=0,max=25, field=True)
</code>```

to query it :

```<code>slider_value = mt.intSliderGrp(sphere_slider , q = True, Value=True)
</code>```

but because you have those in two different def, you need to pass the name of the slider between them.
- For this you can make sphere_slider a global.
- Second option, you can give a unique name to your control (a bit dangerous because maya oculd rename it) :

```<code>mt.intSliderGrp("sphere_slider_name", l="Radius",min=0,max=25, field=True)
slider_value = mt.intSliderGrp("sphere_slider_name", q = True, Value=True)
</code>```

-third option, you can use dictionnaries or even classes :
 .Maya Python - Using data from UI
 .Using Sliders in Maya with Python to control Shapes - intSliderGrp
 .How to create Maya sliders to move objects in interface

Body:
In this code, I have an object creation menu that takes in values from a slider and uses that in the creation of the primitive - How can I actually get the sliders to store the number displayed as right now it just does nothing.

I could remove the sliders but ideally, id like to have them for a nicer user interface

import maya.cmds as mt

def ShowUI():

    if mt.window("Main", exists = True):
        mt.deleteUI("Main")

    mt.window("Main", title = "Maya Primitives", w = 300, h = 500)
    mt.columnLayout("MainLayout", w = 300, h =500)
    mt.optionMenu("PolygonMenu", w = 250, label = "Polygon Selection:")
    mt.menuItem(label = "Sphere")
    mt.menuItem(label = "Cube")
    mt.menuItem(label = "Cylinder")
    mt.button("Create", label = "Create", w = 300, command=ObjectCreation)
    mt.button("Delete", label = "Delete", w = 300, command=DeleteButton)
    mt.button("Clear", label = "Clear", w = 300, command=SceneClear)
    mt.showWindow("Main")

def DeleteButton(*args):
    mt.delete()

def SceneClear(*args):
    mt.delete(all=True, c=True)

def ObjectCreation(*args):
    currentValue = mt.optionMenu("PolygonMenu", query=True, value=True)
    if currentValue == "Sphere":
        SphereSlider()
        SphereRadius = mt.intSliderGrp(Sphradius, q = True, Value=True)
        finalSphere= mt.polySphere(r=SphereRadius, name = "Sphere", ch=False)

    elif currentValue == "Cube":
        CubeSlider()
        CubeWidth = mt.intSliderGrp(CubeW, q = True, Value=True)
        CubeHeight = mt.intSliderGrp(CubeH, q = True, Value=True)
        CubeDepth = mt.intSliderGrp(CubeD, q = True, Value=True)
        finalSphere= mt.polyCube(w=CubeWidth, h=CubeHeight, d=CubeDepth, name = "Cube", ch=False)

    elif currentValue == "Cylinder":
        CylinderSlider()
        CyclinderRadius =  mt.intSliderGrp(Cylradius, q = True, Value=True)
        CyclinderHeight =  mt.intSliderGrp(CylH, q = True, Value=True)
        finalCylinder= mt.polyCylinder(r=CylinderRadius, h=CylinderHeight, name = "Cylinder", ch=False)

def SphereSlider():
    Sphradius = mt.intSliderGrp(l="Radius",min=0,max=25, field=True)

def CubeSlider():
    CubeW = mt.intSliderGrp(l="Width", min=0, max=25, field=True)
    CubeH = mt.intSliderGrp(l="Height", min=0, max=25, field=True)
    CubeD = mt.intSliderGrp(l="Depth", min=0, max=25, field=True)

def CylinderSlider():
    Cylradius = mt.intSliderGrp(l="Radius",min=0,max=25, field=True)
    CylH = mt.intSliderGrp(l="Height", min=0, max=25, field=True)

ShowUI()

Body:
okay so to create a slider you use this command :

sphere_slider = mt.intSliderGrp(l="Radius",min=0,max=25, field=True)

to query it :

slider_value = mt.intSliderGrp(sphere_slider , q = True, Value=True)

but because you have those in two different def, you need to pass the name of the slider between them.
- For this you can make sphere_slider a global.
- Second option, you can give a unique name to your control (a bit dangerous because maya oculd rename it) :

mt.intSliderGrp("sphere_slider_name", l="Radius",min=0,max=25, field=True)
slider_value = mt.intSliderGrp("sphere_slider_name", q = True, Value=True)

-third option, you can use dictionnaries or even classes :
 .Maya Python - Using data from UI
 .Using Sliders in Maya with Python to control Shapes - intSliderGrp
 .How to create Maya sliders to move objects in interface


问:
How to call a function after closing a popover?
I hope someone can give a beginner some guidance, my problem is this:

I have a popover window
I open that popover with a segue from the mainViewController
I want to trigger a function in the mainViewController when the popover is closed
Inside the popover I have a button to close the popover with the following code:

```<code>@IBAction func closeButton(_ sender: Any) {

        dismiss(animated: true, completion: {checkIfPopoverDismissed()}) // I want to trigger this function in the mainView
    }
</code>```

In the mainViewController I have the following function, that I want to be triggered by the closure of the above popover

```<code> func checkIfPopoverDismissed()
    {
      print("the function is triggered")
    }
</code>```

So with the above I get:

```<code> Use of unresolved identifier 'checkIfPopoverDismissed'
</code>```

Because obviously checkIfPopoverDismissed() is in the mainViewController and does not exist in the popover view.

Any idea how I can make this work simply?

答:
*Try This:</p>

```<code>class MainViewController:UIViewController{

      /*In your mainViewController create an instance(I assume the name of the
      class, you can change this accordingly)*/

     //Create a shared instance of mainVC

   static var sharedInstance:MainViewController?

   // in viewDidLoad() assign the property to self

   override func viewDidLoad() {
    super.viewDidLoad()
     MainViewController.sharedInstance = self
}
  func checkIfPopoverDismissed()
    {
      print("the function is triggered")
    }

}

 //Assuming the class name
class PopOverView:UIViewController{

  @IBAction func closeButton(_ sender: Any) {

  dismiss(self,animated: true, completion:
   {MainViewController.sharedInstance?.checkIfPopoverDismissed()})

    }
</code>```

Body:
I hope someone can give a beginner some guidance, my problem is this:

I have a popover window
I open that popover with a segue from the mainViewController
I want to trigger a function in the mainViewController when the popover is closed
Inside the popover I have a button to close the popover with the following code:

@IBAction func closeButton(_ sender: Any) {

        dismiss(animated: true, completion: {checkIfPopoverDismissed()}) // I want to trigger this function in the mainView
    }

In the mainViewController I have the following function, that I want to be triggered by the closure of the above popover

 func checkIfPopoverDismissed()
    {
      print("the function is triggered")
    }

So with the above I get:

 Use of unresolved identifier 'checkIfPopoverDismissed'

Because obviously checkIfPopoverDismissed() is in the mainViewController and does not exist in the popover view.

Any idea how I can make this work simply?

Body:
*Try This:

class MainViewController:UIViewController{

      /*In your mainViewController create an instance(I assume the name of the
      class, you can change this accordingly)*/

     //Create a shared instance of mainVC

   static var sharedInstance:MainViewController?

   // in viewDidLoad() assign the property to self

   override func viewDidLoad() {
    super.viewDidLoad()
     MainViewController.sharedInstance = self
}
  func checkIfPopoverDismissed()
    {
      print("the function is triggered")
    }

}

 //Assuming the class name
class PopOverView:UIViewController{

  @IBAction func closeButton(_ sender: Any) {

  dismiss(self,animated: true, completion:
   {MainViewController.sharedInstance?.checkIfPopoverDismissed()})

    }


问:
How to get the longitude and lattitude from an address without showing map
I want to get latitude and longitude from address in one of my asp.net application, i know it s possible using google apis but i want to do it without showing google map. How can i do that?
  I also want to get distance between two pairs of latitude and longitude. Please guide me in that regards also.

Thanks
Pankaj

答:
try this code...........
In PAge load

```<code>protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetPhysiciansForMap("");
        }

        ((HtmlControl)Master.FindControl("myBody")).Attributes.Add("onload", "GenerateMap()");

    }
</code>```

And in .aspx page

```<code><script type="text/javascript">
  var geocoder;
  var map = null;
  var lat, lng;
  var infowindow = new google.maps.InfoWindow(
  {
    size: new google.maps.Size(150,50)
  });

  function GenerateMap() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(40.730885,-73.997383);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeControl: true,
      mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
      navigationControl: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
      }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    google.maps.event.addListener(map, 'click', function() {
        infowindow.close();
        });

  getHiddenValues();

  for (var i = 0; i < lat.length-1; i++) {
      var point = new google.maps.LatLng(lat[i], lng[i]);
      var marker = createMarker(point,'<div style="width:240px">Address: <br /> City: <br /> State: <br /> Lat n Lng: '+lat[i]+ ', ' +lng[i]+'<\/div>')
      }
}

  function createMarker(latlng, html) {
    var contentString = html;
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        zIndex: Math.round(latlng.lat()*-100000)<<5
        });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(contentString);
        infowindow.open(map,marker);
        });
}

function getHiddenValues()
  {
    lat = document.getElementById("ctl00_ContentPlaceHolder1_hfLat").value.split(',');
    lng = document.getElementById("ctl00_ContentPlaceHolder1_hfLng").value.split(',');
  }

</script>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
try this code...........
In PAge load

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetPhysiciansForMap("");
        }

        ((HtmlControl)Master.FindControl("myBody")).Attributes.Add("onload", "GenerateMap()");

    }

And in .aspx page

<script type="text/javascript">
  var geocoder;
  var map = null;
  var lat, lng;
  var infowindow = new google.maps.InfoWindow(
  {
    size: new google.maps.Size(150,50)
  });

  function GenerateMap() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(40.730885,-73.997383);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeControl: true,
      mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
      navigationControl: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
      }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    google.maps.event.addListener(map, 'click', function() {
        infowindow.close();
        });

  getHiddenValues();

  for (var i = 0; i < lat.length-1; i++) {
      var point = new google.maps.LatLng(lat[i], lng[i]);
      var marker = createMarker(point,'<div style="width:240px">Address: <br /> City: <br /> State: <br /> Lat n Lng: '+lat[i]+ ', ' +lng[i]+'<\/div>')
      }
}

  function createMarker(latlng, html) {
    var contentString = html;
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        zIndex: Math.round(latlng.lat()*-100000)<<5
        });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(contentString);
        infowindow.open(map,marker);
        });
}

function getHiddenValues()
  {
    lat = document.getElementById("ctl00_ContentPlaceHolder1_hfLat").value.split(',');
    lng = document.getElementById("ctl00_ContentPlaceHolder1_hfLng").value.split(',');
  }

</script>


问:
Airflow BranchPythonOperator - Continue After Branch
I have the following operators as shown below. I am able to visually see the the graph representation looks correct.  However, I am not able to get the functionality to work properly as in the paths will not keep going past either branch.  Regardless of the date, neither path will keep going to task_05.

The DAG has two (2) paths:

(1) If it is the first of the month, task_01->test_step->task_02->task_05->task_06

(2) If it is not the first of the month, task_01->test_step->task_03->task_04->task_05->task_06

Problem:  The functionality does not keep the DAG to complete all the way throug task_06.

Assuming the problems resides in the way I am using the bitwise operators.

Code

```<code>from airflow.operators.python_operator import BranchPythonOperator
from airflow.operators.dummy_operator import DummyOperator
from datetime import datetime, timedelta
from airflow.models import DAG

default_args = {
    'owner': 'astro',
    'depends_on_past': False,
    'start_date': datetime(2020, 5, 1),
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5),
}

dag = DAG(
    dag_id='astro_test',
    default_args=default_args,
    schedule_interval="0 10 * * *",
    catchup=True,
    max_active_runs=1
)

def dom_branch(ds_nodash, **kwargs):

    if ds_nodash[-2:] == '01':
        return "task_02"
    else:
        return "task_03"

with dag:
    one = DummyOperator(task_id='task_01')
    two = DummyOperator(task_id='task_02')
    three = DummyOperator(task_id='task_03')
    four = DummyOperator(task_id='task_04')
    five = DummyOperator(task_id='task_05')
    six = DummyOperator(task_id='task_06')

    dom_operator = BranchPythonOperator(
        task_id=f"test_step",
        provide_context=True,
        op_kwargs={'ds_nodash': '{{ ds_nodash }}'},
        python_callable=dom_branch
    )

    one >> dom_operator >> [two, three]
    two >> five
    three >> four >> five
    five >> six
</code>```

1st of month

Not 1st of month

答:
This is due that task_5 requires both upstreams to finish before it can start. Instead, you can add a trigger rule:
https://airflow.apache.org/docs/stable/concepts.html#trigger-rules

```<code>five = DummyOperator(
    task_id='task_05',
    trigger_rule=TriggerRule.ONE_SUCCESS,
)
</code>```

Body:
I have the following operators as shown below. I am able to visually see the the graph representation looks correct.  However, I am not able to get the functionality to work properly as in the paths will not keep going past either branch.  Regardless of the date, neither path will keep going to task_05.

The DAG has two (2) paths:

(1) If it is the first of the month, task_01->test_step->task_02->task_05->task_06

(2) If it is not the first of the month, task_01->test_step->task_03->task_04->task_05->task_06

Problem:  The functionality does not keep the DAG to complete all the way throug task_06.

Assuming the problems resides in the way I am using the bitwise operators.

Code

from airflow.operators.python_operator import BranchPythonOperator
from airflow.operators.dummy_operator import DummyOperator
from datetime import datetime, timedelta
from airflow.models import DAG

default_args = {
    'owner': 'astro',
    'depends_on_past': False,
    'start_date': datetime(2020, 5, 1),
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5),
}

dag = DAG(
    dag_id='astro_test',
    default_args=default_args,
    schedule_interval="0 10 * * *",
    catchup=True,
    max_active_runs=1
)

def dom_branch(ds_nodash, **kwargs):

    if ds_nodash[-2:] == '01':
        return "task_02"
    else:
        return "task_03"

with dag:
    one = DummyOperator(task_id='task_01')
    two = DummyOperator(task_id='task_02')
    three = DummyOperator(task_id='task_03')
    four = DummyOperator(task_id='task_04')
    five = DummyOperator(task_id='task_05')
    six = DummyOperator(task_id='task_06')

    dom_operator = BranchPythonOperator(
        task_id=f"test_step",
        provide_context=True,
        op_kwargs={'ds_nodash': '{{ ds_nodash }}'},
        python_callable=dom_branch
    )

    one >> dom_operator >> [two, three]
    two >> five
    three >> four >> five
    five >> six

1st of month

Not 1st of month

Body:
This is due that task_5 requires both upstreams to finish before it can start. Instead, you can add a trigger rule:
https://airflow.apache.org/docs/stable/concepts.html#trigger-rules

five = DummyOperator(
    task_id='task_05',
    trigger_rule=TriggerRule.ONE_SUCCESS,
)


问:
Get resolved type (and jsdoc tags) of variable initializer using TypeScript compiler API
Starting from the ts.Node for the initializer of p.prop1 below, is there a simple way to get the resolved type info (including doc tags/comment) for Props.prop1 using a type checker?

```<code>interface Props {
  /**
   * Doc comment
   * @tag
   */
  prop1: string;
}

const p: Props = { prop1: 'hello' };
//                 ^^^^^
</code>```

I'm aware of APIs like getTypeAtLocation, getDeclaredTypeOfSymbol, getApparentType, and getPropertyOfType, but haven't been able to figure out how to combine them (or what other APIs might be needed) to do what I want. Calling typeChecker.getSymbolAtLocation(node) on the prop1 initializer node returns a symbol which doesn't have the full type information.

(Ultimately what I want is the JSDoc tags, which once you have the right ts.Symbol can be acquired with symbol.getJsDocTags().)

答:
Getting type of prop1 identifier in object literal expression

To get the type, you can use getTypeAtLocation on the type checker:

```<code>// prop1 is a variable containing the ts.Node (ts.Identifier) of
// the node you highlighted in your question
const prop1Type = typeChecker.getTypeAtLocation(prop1.name);

// outputs: string
console.log(typeChecker.typeToString(prop1Type));
</code>```

Getting its JS doc tags

I'm honestly not sure what the correct way to get the JS doc tags are, but I've found it works to get the object literal expression's contextual type (I think that means it gets the definition type) then from there get the property of prop1:

```<code>const prop1Symbol = typeChecker.getSymbolAtLocation(prop1Symbol)!;
const propsType = typeChecker.getContextualType(prop1.parent)!;

// outputs the tag
console.log(propsType.getProperty(prop1Symbol.getName())!.getJsDocTags());
</code>```

Full Example

```<code>import { createProjectSync, ts } from "@ts-morph/bootstrap";

// setup
const project = createProjectSync({ useInMemoryFileSystem: true });
const sourceFile = project.createSourceFile("file.ts", `
interface Props {
  /**
   * Doc comment
   * @tag
   */
  prop1: string;
}
const p: Props = { prop1: 'hello' };
`);
const typeChecker = project.createProgram().getTypeChecker();

// Get the prop1 identifier in the `p` variable declaration's initializer's
// object literal expression
const varStmt = sourceFile.statements.find(ts.isVariableStatement)!;
const varDecl = varStmt.declarationList.declarations[0];
const varDeclObjLit = varDecl.initializer as ts.ObjectLiteralExpression;
const prop1 = varDeclObjLit.properties[0] as ts.PropertyAssignment;

// outputs: string
const prop1Type = typeChecker.getTypeAtLocation(prop1.name);
console.log(typeChecker.typeToString(prop1Type));

// outputs the js doc tag
const prop1Symbol = typeChecker.getSymbolAtLocation(prop1.name)!;
const propsType = typeChecker.getContextualType(prop1.parent)!;
console.log(propsType.getProperty(prop1Symbol.getName())!.getJsDocTags());
</code>```

Body:
Starting from the ts.Node for the initializer of p.prop1 below, is there a simple way to get the resolved type info (including doc tags/comment) for Props.prop1 using a type checker?

interface Props {
  /**
   * Doc comment
   * @tag
   */
  prop1: string;
}

const p: Props = { prop1: 'hello' };
//                 ^^^^^

I'm aware of APIs like getTypeAtLocation, getDeclaredTypeOfSymbol, getApparentType, and getPropertyOfType, but haven't been able to figure out how to combine them (or what other APIs might be needed) to do what I want. Calling typeChecker.getSymbolAtLocation(node) on the prop1 initializer node returns a symbol which doesn't have the full type information.

(Ultimately what I want is the JSDoc tags, which once you have the right ts.Symbol can be acquired with symbol.getJsDocTags().)

Body:
Getting type of prop1 identifier in object literal expression

To get the type, you can use getTypeAtLocation on the type checker:

// prop1 is a variable containing the ts.Node (ts.Identifier) of
// the node you highlighted in your question
const prop1Type = typeChecker.getTypeAtLocation(prop1.name);

// outputs: string
console.log(typeChecker.typeToString(prop1Type));

Getting its JS doc tags

I'm honestly not sure what the correct way to get the JS doc tags are, but I've found it works to get the object literal expression's contextual type (I think that means it gets the definition type) then from there get the property of prop1:

const prop1Symbol = typeChecker.getSymbolAtLocation(prop1Symbol)!;
const propsType = typeChecker.getContextualType(prop1.parent)!;

// outputs the tag
console.log(propsType.getProperty(prop1Symbol.getName())!.getJsDocTags());

Full Example

import { createProjectSync, ts } from "@ts-morph/bootstrap";

// setup
const project = createProjectSync({ useInMemoryFileSystem: true });
const sourceFile = project.createSourceFile("file.ts", `
interface Props {
  /**
   * Doc comment
   * @tag
   */
  prop1: string;
}
const p: Props = { prop1: 'hello' };
`);
const typeChecker = project.createProgram().getTypeChecker();

// Get the prop1 identifier in the `p` variable declaration's initializer's
// object literal expression
const varStmt = sourceFile.statements.find(ts.isVariableStatement)!;
const varDecl = varStmt.declarationList.declarations[0];
const varDeclObjLit = varDecl.initializer as ts.ObjectLiteralExpression;
const prop1 = varDeclObjLit.properties[0] as ts.PropertyAssignment;

// outputs: string
const prop1Type = typeChecker.getTypeAtLocation(prop1.name);
console.log(typeChecker.typeToString(prop1Type));

// outputs the js doc tag
const prop1Symbol = typeChecker.getSymbolAtLocation(prop1.name)!;
const propsType = typeChecker.getContextualType(prop1.parent)!;
console.log(propsType.getProperty(prop1Symbol.getName())!.getJsDocTags());


问:
Nodemon installed but not working in Node.js
I am using Node.js with express.js and I also installed Nodemon ( exist in node_modules folder) but it's not working.
Here is my package.json code. How can I solve this ?

```<code>// package.json

{
    "name": "node-api",
    "main": "server.js",
    "dependencies": {
        "express": "~4.0.0",
        "mongoose": "~3.6.13",
        "body-parser": "~1.0.1"
    }
}
</code>```

答:
This issue is very much common. It showed 'found 0 vulnerabilities' while installing but never showed in dev dependencies.

I tried restarting my text editor and run the command again

```<code>npm i --save-dev nodemon
</code>```

it started working.

Body:
I am using Node.js with express.js and I also installed Nodemon ( exist in node_modules folder) but it's not working.
Here is my package.json code. How can I solve this ?

// package.json

{
    "name": "node-api",
    "main": "server.js",
    "dependencies": {
        "express": "~4.0.0",
        "mongoose": "~3.6.13",
        "body-parser": "~1.0.1"
    }
}

Body:
This issue is very much common. It showed 'found 0 vulnerabilities' while installing but never showed in dev dependencies.

I tried restarting my text editor and run the command again

npm i --save-dev nodemon

it started working.


问:
Returning a boolean value in a JavaScript function
I am doing a client side form validation to check if passwords match. But the validation function always returns undefined.

```<code>function validatePassword(errorMessage)
{
   var password = document.getElementById("password");
   var confirm_password = document.getElementById("password_confirm");

   if(password.value)
   {
      // Check if confirm_password matches
      if(password.value != confirm_password.value)
      {
         return false;
      }
   }
   else
   {
      // If password is empty but confirm password is not
      if(confirm_password.value)
      {
         return false;
      }
   }
   return true;
}
</code>```

Please note that the validatePassword is called from a member function of the Form object.

```<code>function Form(validation_fn)
{
   // Do other stuff
   this.submit_btn = document.getElementById("submit");
   this.validation_fn = validation_fn;
}

Form.prototype.submit = funciton()
{
   var result;
   if(this.validation_fn)
   {
      result = this.validation_fn();
   }

   //result is always undefined
   if(result)
   {
       //do other stuff
   }
}
</code>```

答:
Don't forget to use var/let while declaring any variable.See below examples for JS compiler behaviour. </p>

```<code>function  func(){
return true;
}

isBool = func();
console.log(typeof (isBool));   // output - string

let isBool = func();
console.log(typeof (isBool));   // output - boolean
</code>```

Body:
I am doing a client side form validation to check if passwords match. But the validation function always returns undefined.

function validatePassword(errorMessage)
{
   var password = document.getElementById("password");
   var confirm_password = document.getElementById("password_confirm");

   if(password.value)
   {
      // Check if confirm_password matches
      if(password.value != confirm_password.value)
      {
         return false;
      }
   }
   else
   {
      // If password is empty but confirm password is not
      if(confirm_password.value)
      {
         return false;
      }
   }
   return true;
}

Please note that the validatePassword is called from a member function of the Form object.

function Form(validation_fn)
{
   // Do other stuff
   this.submit_btn = document.getElementById("submit");
   this.validation_fn = validation_fn;
}

Form.prototype.submit = funciton()
{
   var result;
   if(this.validation_fn)
   {
      result = this.validation_fn();
   }

   //result is always undefined
   if(result)
   {
       //do other stuff
   }
}

Body:
Don't forget to use var/let while declaring any variable.See below examples for JS compiler behaviour.

function  func(){
return true;
}

isBool = func();
console.log(typeof (isBool));   // output - string

let isBool = func();
console.log(typeof (isBool));   // output - boolean


问:
Need some assistance with CyberSource authentication please
I am trying to post a request for "flex/v1/keys" api and i am trying to mirror the examples CyberSource have on the api page. But i keep getting back {"response":{"rmsg":"Authentication Failed"}} .
Please can someone assist me i am clueless and been struggling for a while now.

Code for getting headers sorted.

```<code>var crypto = require("crypto-js");
var requestHost = 'apitest.cybersource.com';
var merchantId = 'testrest';
var merchantKeyId = '08c94330-f618-42a3-b09d-e1e43be5efda';
var merchantSecretKey = 'yBJxy6LjM2TmcPGu+GaJrHtkke25fPpUX+UY6/L/1tE=';
var resource = "/flex/v1/keys";

//digest
var payload = '{"encryptionType": "None"}';
var data = crypto.enc.Utf8.parse(payload)
var hash = crypto.SHA256(data)
var base64 = crypto.enc.Base64.stringify(hash);
var digest = "SHA-256=" + base64;
pm.globals.set("digest",digest);

//date
var date = new Date(Date.now()).toUTCString();
pm.globals.set("date",date);

//signature
var signatureHeader = "";
signatureHeader += "keyid=\"" + merchantKeyId + "\"";
signatureHeader += ", algorithm=\"HmacSHA256\"";
var headersForPostMethod = "host date (request-target) digest v-c-merchant-id";
signatureHeader += ", headers=\"" + headersForPostMethod + "\"";

var signatureString = 'host: ' + requestHost;
signatureString += '\ndate: ' + new Date(Date.now()).toUTCString();
signatureString += '\n(request-target): ';
var targetUrlForPost = "post " + resource;
signatureString += targetUrlForPost + '\n';
signatureString += 'digest: SHA-256=' + digest + '\n';
signatureString += 'v-c-merchant-id: ' + merchantId;

var dataSigString = crypto.enc.Utf8.parse(signatureString);
var secKey = crypto.enc.Base64.parse(merchantSecretKey);
var hashHmac = CryptoJS.HmacSHA256(dataSigString, secKey)
var base64hashHmac = CryptoJS.enc.Base64.stringify(hashHmac);

signatureHeader += ", signature=\"" + base64hashHmac + "\"";
pm.globals.set("signature",signatureHeader);
</code>```

My post request i am trying to send.

```<code>curl --location --request POST 'https://apitest.cybersource.com/flex/v1/keys' \
--header 'digest: SHA-256=yF79QR9XHmXEMjhnXRIvsaGie/xoTduWMP8kMOUIyVc=' \
--header 'v-c-merchant-id: testrest' \
--header 'date: Fri, 29 May 2020 15:06:42 GMT' \
--header 'host: apitest.cybersource.com' \
--header 'signature: keyid="08c94330-f618-42a3-b09d-e1e43be5efda", algorithm="HmacSHA256", headers="host date (request-target) digest v-c-merchant-id", signature="lnv5/zeUimcef0Dr3VeOyKgOw/cX8Erdb+qaKuSwuug="' \
--header 'profile-id: 93B32398-AD51-4CC2-A682-EA3E93614EB1' \
--header 'Content-Type: application/json' \
--data-raw '{"encryptionType": "None"}'
</code>```

RESULTS

```<code>POST https://apitest.cybersource.com/flex/v1/keys

Request Headers
digest: SHA-256=yF79QR9XHmXEMjhnXRIvsaGie/xoTduWMP8kMOUIyVc=
v-c-merchant-id: testrest
date: Fri, 29 May 2020 14:57:17 GMT
host: apitest.cybersource.com
signature: keyid="08c94330-f618-42a3-b09d-e1e43be5efda", algorithm="HmacSHA256", headers="host date (request-target) digest v-c-merchant-id", signature="cLFxiYvra8KMBOaTB25Ke+gnQh67/MMn9wr0d8PRSm4="
profile-id: 93B32398-AD51-4CC2-A682-EA3E93614EB1
Content-Type: application/json
User-Agent: PostmanRuntime/7.25.0
Accept: */*
Cache-Control: no-cache
Postman-Token: ef33044d-e745-4014-bdd8-d30f659be760
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 27

Request Body
{"encryptionType": "None"}↵

Response Headers
Strict-Transport-Security: max-age=31536000
v-c-correlation-id: 9e9d8293-b909-4fdf-9ae6-9f992e5dca87
content-type: application/json
v-c-response-time: 1590764238
content-length: 45

Response Body
{"response":{"rmsg":"Authentication Failed"}}
</code>```

答:
for anyone encountering this issue i have found my fix and it works now with crypto-js authentication.

Silly mistake from me not building the string up properly.
just update the script mentioned in my question with the following.

BROKEN

```<code>signatureString += 'digest: SHA-256=' + digest + '\n';
</code>```

FIX

```<code>signatureString += 'digest: ' + digest + '\n';
</code>```

Body:
I am trying to post a request for "flex/v1/keys" api and i am trying to mirror the examples CyberSource have on the api page. But i keep getting back {"response":{"rmsg":"Authentication Failed"}} .
Please can someone assist me i am clueless and been struggling for a while now.

Code for getting headers sorted.

var crypto = require("crypto-js");
var requestHost = 'apitest.cybersource.com';
var merchantId = 'testrest';
var merchantKeyId = '08c94330-f618-42a3-b09d-e1e43be5efda';
var merchantSecretKey = 'yBJxy6LjM2TmcPGu+GaJrHtkke25fPpUX+UY6/L/1tE=';
var resource = "/flex/v1/keys";

//digest
var payload = '{"encryptionType": "None"}';
var data = crypto.enc.Utf8.parse(payload)
var hash = crypto.SHA256(data)
var base64 = crypto.enc.Base64.stringify(hash);
var digest = "SHA-256=" + base64;
pm.globals.set("digest",digest);

//date
var date = new Date(Date.now()).toUTCString();
pm.globals.set("date",date);

//signature
var signatureHeader = "";
signatureHeader += "keyid=\"" + merchantKeyId + "\"";
signatureHeader += ", algorithm=\"HmacSHA256\"";
var headersForPostMethod = "host date (request-target) digest v-c-merchant-id";
signatureHeader += ", headers=\"" + headersForPostMethod + "\"";

var signatureString = 'host: ' + requestHost;
signatureString += '\ndate: ' + new Date(Date.now()).toUTCString();
signatureString += '\n(request-target): ';
var targetUrlForPost = "post " + resource;
signatureString += targetUrlForPost + '\n';
signatureString += 'digest: SHA-256=' + digest + '\n';
signatureString += 'v-c-merchant-id: ' + merchantId;

var dataSigString = crypto.enc.Utf8.parse(signatureString);
var secKey = crypto.enc.Base64.parse(merchantSecretKey);
var hashHmac = CryptoJS.HmacSHA256(dataSigString, secKey)
var base64hashHmac = CryptoJS.enc.Base64.stringify(hashHmac);

signatureHeader += ", signature=\"" + base64hashHmac + "\"";
pm.globals.set("signature",signatureHeader);

My post request i am trying to send.

curl --location --request POST 'https://apitest.cybersource.com/flex/v1/keys' \
--header 'digest: SHA-256=yF79QR9XHmXEMjhnXRIvsaGie/xoTduWMP8kMOUIyVc=' \
--header 'v-c-merchant-id: testrest' \
--header 'date: Fri, 29 May 2020 15:06:42 GMT' \
--header 'host: apitest.cybersource.com' \
--header 'signature: keyid="08c94330-f618-42a3-b09d-e1e43be5efda", algorithm="HmacSHA256", headers="host date (request-target) digest v-c-merchant-id", signature="lnv5/zeUimcef0Dr3VeOyKgOw/cX8Erdb+qaKuSwuug="' \
--header 'profile-id: 93B32398-AD51-4CC2-A682-EA3E93614EB1' \
--header 'Content-Type: application/json' \
--data-raw '{"encryptionType": "None"}'

RESULTS

POST https://apitest.cybersource.com/flex/v1/keys

Request Headers
digest: SHA-256=yF79QR9XHmXEMjhnXRIvsaGie/xoTduWMP8kMOUIyVc=
v-c-merchant-id: testrest
date: Fri, 29 May 2020 14:57:17 GMT
host: apitest.cybersource.com
signature: keyid="08c94330-f618-42a3-b09d-e1e43be5efda", algorithm="HmacSHA256", headers="host date (request-target) digest v-c-merchant-id", signature="cLFxiYvra8KMBOaTB25Ke+gnQh67/MMn9wr0d8PRSm4="
profile-id: 93B32398-AD51-4CC2-A682-EA3E93614EB1
Content-Type: application/json
User-Agent: PostmanRuntime/7.25.0
Accept: */*
Cache-Control: no-cache
Postman-Token: ef33044d-e745-4014-bdd8-d30f659be760
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 27

Request Body
{"encryptionType": "None"}↵

Response Headers
Strict-Transport-Security: max-age=31536000
v-c-correlation-id: 9e9d8293-b909-4fdf-9ae6-9f992e5dca87
content-type: application/json
v-c-response-time: 1590764238
content-length: 45

Response Body
{"response":{"rmsg":"Authentication Failed"}}

Body:
for anyone encountering this issue i have found my fix and it works now with crypto-js authentication.

Silly mistake from me not building the string up properly.
just update the script mentioned in my question with the following.

BROKEN

signatureString += 'digest: SHA-256=' + digest + '\n';

FIX

signatureString += 'digest: ' + digest + '\n';


问:
Check if all Input component fields are filled, then enable submit button
I want it so that when all  fields are filled(i.e. not empty), the submit button will be enabled. I could implement this easily if the number of fields were fixed, but in this case, the number of fields won't be fixed, such as items in a shopping cart. Here is my code so far:</p>

```<code>{orders.map((order, i) => (
<Row key={i}>
    <Col>
        <Row><Text>{o.quantity}</Text><Text>{`${order.name}`}</Text></Row>
    </Col>
    <Col>
        <Item fixedLabel>
                <Label>$</Label>
                <Input placeholder={"0.00"} value={order.price} />
        </Item>
    </Col>
</Row>
))}
<Button disabled={this.state.disabled} onPress={this.submit.bind(this)}><Text>Submit</Text></Button>
</code>```

答:
Define the initial state of disabled as false. Then, do as follows...

```<code>{orders.map((order, i) => {
  if(!order.name || !order.value) { this.setState({ disabled: true }) }
  <Row key={i}>
    <Col>
      <Row><Text>{o.quantity}</Text><Text>{`${order.name}`}</Text></Row>
    </Col>
    <Col>
      <Item fixedLabel>
        <Label>$</Label>
        <Input placeholder={"0.00"} value={order.price} />
      </Item>
    </Col>
  </Row>
})}
<Button disabled={this.state.disabled} onPress={this.submit.bind(this)}><Text>Submit</Text></Button>
</code>```

Here, it checks if the name or value of the particular order is null. If it found at least a one order with name or value of the particular order is null, it sets the disabled as true.

Body:
I want it so that when all  fields are filled(i.e. not empty), the submit button will be enabled. I could implement this easily if the number of fields were fixed, but in this case, the number of fields won't be fixed, such as items in a shopping cart. Here is my code so far:

{orders.map((order, i) => (
<Row key={i}>
    <Col>
        <Row><Text>{o.quantity}</Text><Text>{`${order.name}`}</Text></Row>
    </Col>
    <Col>
        <Item fixedLabel>
                $
                <Input placeholder={"0.00"} value={order.price} />
        </Item>
    </Col>
</Row>
))}
<Button disabled={this.state.disabled} onPress={this.submit.bind(this)}><Text>Submit</Text></Button>

Body:
Define the initial state of disabled as false. Then, do as follows...

{orders.map((order, i) => {
  if(!order.name || !order.value) { this.setState({ disabled: true }) }
  <Row key={i}>
    <Col>
      <Row><Text>{o.quantity}</Text><Text>{`${order.name}`}</Text></Row>
    </Col>
    <Col>
      <Item fixedLabel>
        <Label>$</Label>
        <Input placeholder={"0.00"} value={order.price} />
      </Item>
    </Col>
  </Row>
})}
<Button disabled={this.state.disabled} onPress={this.submit.bind(this)}><Text>Submit</Text></Button>

Here, it checks if the name or value of the particular order is null. If it found at least a one order with name or value of the particular order is null, it sets the disabled as true.


问:
How to deploy multiple apps (monorepo) with Azure and NX
I'm using NX tools to manage a monorepo with multiple apps and I'm struggling to understand how to deploy using Azure and release pipelines.

Disclaimer : I'm very new to Azure and devops in general.

My understanding is this :
I create a pipeline (not a release pipeline, just a "regular one" if that make any sense) and plug a yml to it. Also, the pipeline is linked to a repo on Azure Repos, which means that every time I push to this repo, it will trigger the pipeline and run the yaml commands.
On this commands, I run lint, test and builds.

This is what I can do and can understand, the following become more obscure :

The build job is supposed to create an artifact if I'm pusing/merging on master which I can conditioned.
Now I can create a release pipeline which will be trigger when to repo it is linked to will create an artifact. This release pipeline can then send this artifact to an app service which is a slot where an app will live.

Okay, but I'm using a monorepo, which means the build will produce multiple applications and each one of these apps should be deploy to the correct app service.

After some research, I found that the general idea is to create one release pipeline for each app. These release pipelines are all linked to the same monorepo, but they have a filter which is a build tag. The build tag is added while building the apps using the yml file.

So these are basically my understanding of all of this. Now here are the questions :

What exactly is a build tag and where does it live? Is it somehow linked to an artifact?

The idea is to create one build tag per artifact, right?

I failed to create a build tag, how can I do so?

What is the correct way to zip and publish the artifacts?

Here is the yaml I'm using :

```<code>jobs:
  - job: Lint
    steps:
      - task: NodeTool@0
        inputs:
          versionSpec: '12.x'
        displayName: 'Install Node.js'
      - task: Npm@1
        displayName: 'Npm install'
      - pwsh: 'npm run nx affected -- --target=lint --parallel --base=origin/master --maxParallel=4'
        displayName: 'Running lint'

  - job: Test
    steps:
      - task: NodeTool@0
        inputs:
          versionSpec: '12.x'
        displayName: 'Install Node.js'
      - task: Npm@1
        displayName: 'npm install'
      - pwsh: 'npm run nx affected -- --target=test --parallel --code-coverage --base=origin/master --maxParallel=4'
        displayName: 'Running tests'

  - job: Build
    steps:
      - task: NodeTool@0
        inputs:
          versionSpec: '12.x'
        displayName: 'Install Node.js'
      - task: Npm@1
        displayName: 'npm install'
      - pwsh: 'npm run nx affected -- --target=build --parallel --base=origin/master --prod'
        displayName: 'Running build'
      - pwsh: |
          npm run nx affected:apps -- --base=HEAD~1  --head=HEAD | grep -E '( - )(\w|-|\d|_)+' | sed -E 's/ - /##vso[build.addbuildtag]/g'
        displayName: 'Adding build tags'
</code>```

When running this, test, lint and builds are working, but I don't think it adds a build tag, here is the log :

It appears like nothing happens... How can I correctly add the tag and make the release pipeline to be triggered?

I've also found this snippet to zip and publish the artifact, but I don't know if I can use that since in a monorepo we should - I think - create multiple artifacts.

5) So the last question is : how can I create multiple artifacts and is it even the good thing to do?

Many many thanks in advance for the help, I know this is a long boring post and helping a noob can be boring but I'm stuck with this for way to long...

答:
1, You can add tags for a build from the UI page(Build summary page, see below) or using Rest api. It can be used to filter between builds. If your build pipeline generated multiple artifacts, build tags will not be able to filter the artifacts which generated in one build.

2, So you can think about how to separate the build artifacts for each app in your pipeline.

You can use Archive files task to zip your build artifacts and publish using publish build artifacts task.

See below yaml example: I used two archive files task to package the build artifacts for app1 and app2 separately. And save the zipped artifacts in folder $(Build.ArtifactStagingDirectory).
Then the publish build artifacts task will publish the artifacts to azure devops cloud. (Release pipeline will download the artifacts to deploy to your app server)

```<code>- task: ArchiveFiles@2
      inputs:
        rootFolderOrFile: $(system.defaultworkingdirectory)/app1/dist
        archiveType: 'zip'
        archiveFile: '$(Build.ArtifactStagingDirectory)/app1/dist1.zip'
        includeRootFolder: false
      enabled: true
    - task: ArchiveFiles@2
      inputs:
        rootFolderOrFile: $(system.defaultworkingdirectory)/app2/dist
        archiveType: 'zip'
        archiveFile: '$(Build.ArtifactStagingDirectory)/app2/dist2.zip'
        includeRootFolder: false
      enabled: true

    - task: PublishBuildArtifacts@1
      inputs:
        PathtoPublish: $(Build.ArtifactStagingDirectory)/
        artifactName: build
</code>```

3, Then you can use multiple stages in your release pipeline and use Azure App Service Deploy task. For below example:

In stage one add Azure App Service Deploy task and set the package to $(System.DefaultWorkingDirectory)/**/app1/dist1.zip to deploy app1. And in stage two set it to  $(System.DefaultWorkingDirectory)/**/app2/dist2.zip to deploy app2.

Another workaround to deploy multiple apps in monorepo is to create multiple build/release pipeline, one for each app. And in the build pipeline using path filter to let the build pipeline only be triggered when it corresponding app is updated.

```<code>trigger:
  paths:
    include:
    - root/app1/*
</code>```

Hope above helps!

Body:
I'm using NX tools to manage a monorepo with multiple apps and I'm struggling to understand how to deploy using Azure and release pipelines.

Disclaimer : I'm very new to Azure and devops in general.

My understanding is this :
I create a pipeline (not a release pipeline, just a "regular one" if that make any sense) and plug a yml to it. Also, the pipeline is linked to a repo on Azure Repos, which means that every time I push to this repo, it will trigger the pipeline and run the yaml commands.
On this commands, I run lint, test and builds.

This is what I can do and can understand, the following become more obscure :

The build job is supposed to create an artifact if I'm pusing/merging on master which I can conditioned.
Now I can create a release pipeline which will be trigger when to repo it is linked to will create an artifact. This release pipeline can then send this artifact to an app service which is a slot where an app will live.

Okay, but I'm using a monorepo, which means the build will produce multiple applications and each one of these apps should be deploy to the correct app service.

After some research, I found that the general idea is to create one release pipeline for each app. These release pipelines are all linked to the same monorepo, but they have a filter which is a build tag. The build tag is added while building the apps using the yml file.

So these are basically my understanding of all of this. Now here are the questions :

What exactly is a build tag and where does it live? Is it somehow linked to an artifact?

The idea is to create one build tag per artifact, right?

I failed to create a build tag, how can I do so?

What is the correct way to zip and publish the artifacts?

Here is the yaml I'm using :

jobs:
  - job: Lint
    steps:
      - task: NodeTool@0
        inputs:
          versionSpec: '12.x'
        displayName: 'Install Node.js'
      - task: Npm@1
        displayName: 'Npm install'
      - pwsh: 'npm run nx affected -- --target=lint --parallel --base=origin/master --maxParallel=4'
        displayName: 'Running lint'

  - job: Test
    steps:
      - task: NodeTool@0
        inputs:
          versionSpec: '12.x'
        displayName: 'Install Node.js'
      - task: Npm@1
        displayName: 'npm install'
      - pwsh: 'npm run nx affected -- --target=test --parallel --code-coverage --base=origin/master --maxParallel=4'
        displayName: 'Running tests'

  - job: Build
    steps:
      - task: NodeTool@0
        inputs:
          versionSpec: '12.x'
        displayName: 'Install Node.js'
      - task: Npm@1
        displayName: 'npm install'
      - pwsh: 'npm run nx affected -- --target=build --parallel --base=origin/master --prod'
        displayName: 'Running build'
      - pwsh: |
          npm run nx affected:apps -- --base=HEAD~1  --head=HEAD | grep -E '( - )(\w|-|\d|_)+' | sed -E 's/ - /##vso[build.addbuildtag]/g'
        displayName: 'Adding build tags'

When running this, test, lint and builds are working, but I don't think it adds a build tag, here is the log :

It appears like nothing happens... How can I correctly add the tag and make the release pipeline to be triggered?

I've also found this snippet to zip and publish the artifact, but I don't know if I can use that since in a monorepo we should - I think - create multiple artifacts.

5) So the last question is : how can I create multiple artifacts and is it even the good thing to do?

Many many thanks in advance for the help, I know this is a long boring post and helping a noob can be boring but I'm stuck with this for way to long...

Body:
1, You can add tags for a build from the UI page(Build summary page, see below) or using Rest api. It can be used to filter between builds. If your build pipeline generated multiple artifacts, build tags will not be able to filter the artifacts which generated in one build.

2, So you can think about how to separate the build artifacts for each app in your pipeline.

You can use Archive files task to zip your build artifacts and publish using publish build artifacts task.

See below yaml example: I used two archive files task to package the build artifacts for app1 and app2 separately. And save the zipped artifacts in folder $(Build.ArtifactStagingDirectory).
Then the publish build artifacts task will publish the artifacts to azure devops cloud. (Release pipeline will download the artifacts to deploy to your app server)

- task: ArchiveFiles@2
      inputs:
        rootFolderOrFile: $(system.defaultworkingdirectory)/app1/dist
        archiveType: 'zip'
        archiveFile: '$(Build.ArtifactStagingDirectory)/app1/dist1.zip'
        includeRootFolder: false
      enabled: true
    - task: ArchiveFiles@2
      inputs:
        rootFolderOrFile: $(system.defaultworkingdirectory)/app2/dist
        archiveType: 'zip'
        archiveFile: '$(Build.ArtifactStagingDirectory)/app2/dist2.zip'
        includeRootFolder: false
      enabled: true

    - task: PublishBuildArtifacts@1
      inputs:
        PathtoPublish: $(Build.ArtifactStagingDirectory)/
        artifactName: build

3, Then you can use multiple stages in your release pipeline and use Azure App Service Deploy task. For below example:

In stage one add Azure App Service Deploy task and set the package to $(System.DefaultWorkingDirectory)/**/app1/dist1.zip to deploy app1. And in stage two set it to  $(System.DefaultWorkingDirectory)/**/app2/dist2.zip to deploy app2.

Another workaround to deploy multiple apps in monorepo is to create multiple build/release pipeline, one for each app. And in the build pipeline using path filter to let the build pipeline only be triggered when it corresponding app is updated.

trigger:
  paths:
    include:
    - root/app1/*

Hope above helps!


问:
SQL Server: How to check if a windows user exists in the database but under a different user name
I am trying to create a user via a T-SQL script in SQL Server 2005/2008. I run the following SQL to check if the user exists and create the user if it does not:

```<code>IF NOT EXISTS (SELECT *
               FROM   sys.database_principals
               WHERE  name = N'MyDomain\MyUser')
  BEGIN
      CREATE USER [MyDomain\MyUser] FOR LOGIN [MyDomain\MyUser] WITH default_schema=[dbo];

      SELECT 1;
  END
ELSE
  BEGIN
      SELECT 0;
  END
</code>```

Unfortunately, this does not work when the windows account MyDomain\MyUser is already in the database but under a different name. An example of this would be if MyDomain\MyUser was the account that created the database then it will already be in the database under the dbo user. When this is the case I get the following error:

Msg 15063, Level 16, State 1, Line 1
  The login already has an account under
  a different user name.

How can I check if the windows user MyDomain\MyUser is already a user in the database even if it is under a different user name?

答:
Do the testing for windows user vs sys.database_principals using the SID rather than the name/user_id:

```<code>select * from sys.database_principals where sid = SUSER_SID(N'MyDomain\MyUser')
</code>```

Since this uses the SID of the login ID, it doesn't matter what name it was mapped to in the database.

Body:
I am trying to create a user via a T-SQL script in SQL Server 2005/2008. I run the following SQL to check if the user exists and create the user if it does not:

IF NOT EXISTS (SELECT *
               FROM   sys.database_principals
               WHERE  name = N'MyDomain\MyUser')
  BEGIN
      CREATE USER [MyDomain\MyUser] FOR LOGIN [MyDomain\MyUser] WITH default_schema=[dbo];

      SELECT 1;
  END
ELSE
  BEGIN
      SELECT 0;
  END

Unfortunately, this does not work when the windows account MyDomain\MyUser is already in the database but under a different name. An example of this would be if MyDomain\MyUser was the account that created the database then it will already be in the database under the dbo user. When this is the case I get the following error:

Msg 15063, Level 16, State 1, Line 1
  The login already has an account under
  a different user name.

How can I check if the windows user MyDomain\MyUser is already a user in the database even if it is under a different user name?

Body:
Do the testing for windows user vs sys.database_principals using the SID rather than the name/user_id:

select * from sys.database_principals where sid = SUSER_SID(N'MyDomain\MyUser')

Since this uses the SID of the login ID, it doesn't matter what name it was mapped to in the database.