问:
React Native upload to S3 with presigned URL
Been trying with no luck to upload an image to S3 from React Native using pre-signed url.  Here is my code:

generate pre-signed url in node:

```<code>const s3 = new aws.S3();

const s3Params = {
  Bucket: bucket,
  Key: fileName,
  Expires: 60,
  ContentType: 'image/jpeg',
  ACL: 'public-read'
};

return s3.getSignedUrl('putObject', s3Params);
</code>```

here is RN request to S3:

```<code>var file = {
  uri: game.pictureToSubmitUri,
  type: 'image/jpeg',
  name: 'image.jpg',
};

const xhr = new XMLHttpRequest();
var body = new FormData();
body.append('file', file);
xhr.open('PUT', signedRequest);
xhr.onreadystatechange = () => {
  if(xhr.readyState === 4){
    if(xhr.status === 200){
      alert('Posted!');
    }
    else{
      alert('Could not upload file.');
   }
 }
};
xhr.send(body);
</code>```

game.pictureToSubmitUri = assets-library://asset/asset.JPG?id=A282A2C5-31C8-489F-9652-7D3BD5A1FAA4&ext=JPG

signedRequest = https://my-bucket.s3-us-west-1.amazonaws.com/8bd2d4b9-3206-4bff-944d-e06f872d8be3?AWSAccessKeyId=AKIAIOLHQY4GAXN26FOQ&Content-Type=image%2Fjpeg&Expires=1465671117&Signature=bkQIp5lgzuYrt2vyl7rqpCXPcps%3D&x-amz-acl=public-read

Error message:

```<code><Code>SignatureDoesNotMatch</Code>
<Message>
The request signature we calculated does not match the signature you provided. Check your key and signing method.
</Message>
</code>```

I can successfully curl and image to S3 using the generated url, and I seem to be able to successfully post to requestb.in from RN (however I can only see the raw data on requestb.in so not 100% sure the image is properly there).

Based on all this, I've narrowed my issue down to 1) my image is not correctly uploading period, or 2) somehow the way S3 wants my request is different then how it is coming in.

Any help would be muuuuuucchhhh appreciated!

UPDATE

Can successfully post from RN to S3 if body is just text ({'data': 'foo'}).  Perhaps AWS does not like mutliform data?  How can I send as just a file in RN???

答:
FOR REACT NATIVE I WILL NOT BE USING ANY 3RD PARTY LIBS.

i have my pick image function that picks the image and upload using xhr

```<code>const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
     // mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
      base64:true
    });

    console.log(result);

    if (!result.cancelled) {
     // setImage(result.uri);
      let base64Img = `data:image/jpg;base64,${result.uri}`;

       // ImagePicker saves the taken photo to disk and returns a local URI to it
  let localUri = result.uri;
  let filename = localUri.split('/').pop();

  // Infer the type of the image
  let match = /\.(\w+)$/.exec(filename);
  let type = match ? `image/${match[1]}` : `image`;

  // Upload the image using the fetch and FormData APIs
  let formData = new FormData();
  // Assume "photo" is the name of the form field the server expects
  formData.append('file', { uri: base64Img, name: filename, type });

  const xhr = new XMLHttpRequest();

  xhr.open('GET', ENVIRONMENTS.CLIENT_API+`/sign-s3?file-name=${filename}&file-type=${type}`);
  xhr.setRequestHeader('Access-Control-Allow-Headers', '*');
xhr.setRequestHeader('Content-type', 'application/json');
// xhr.setRequestHeader('Content-type', 'multipart/form-data');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
 xhr.setRequestHeader('X-Amz-ACL', 'public-read') //added
xhr.setRequestHeader('Content-Type', type) //added
xhr.onreadystatechange = () => {
  if(xhr.readyState === 4){
    if(xhr.status === 200){
      const response = JSON.parse(xhr.responseText);
      alert(JSON.stringify( response.signedRequest, response.url))
      // uploadFile(file, response.signedRequest, response.url);
      // this.setState({imagename:file.name})
      const xhr2 = new XMLHttpRequest();

            xhr2.open('PUT', response.signedRequest);
            xhr2.setRequestHeader('Access-Control-Allow-Headers', '*');
            xhr2.setRequestHeader('Content-type', 'application/json');
            // xhr2.setRequestHeader('Content-type', 'multipart/form-data');
            xhr2.setRequestHeader('Access-Control-Allow-Origin', '*');
            //  xhr2.setRequestHeader('X-Amz-ACL', 'public-read') //added
            xhr2.setRequestHeader('Content-Type', type) //added
            xhr2.onreadystatechange = () => {
              if(xhr2.readyState === 4){
                if(xhr2.status === 200){

                  alert("successful upload ")
                }
                else{
                  // alert('Could not upload file.');
                  var error = new Error(xhr.responseText)
                  error.code = xhr.status;
                  for (var key in response) error[key] = response[key]
                  alert(error)
                }
              }
            };
            xhr2.send( result.base64)
    }
    else{
      alert('Could not get signed URL.');
    }
  }
};
xhr.send();

    }

  };

then some where in the render method

<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button title="Pick an image from camera roll" onPress={pickImage} />
      {image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
    </View>

hope it helps any one who doesnt want sleepless nights like me.
</code>```

Body:
Been trying with no luck to upload an image to S3 from React Native using pre-signed url.  Here is my code:

generate pre-signed url in node:

const s3 = new aws.S3();

const s3Params = {
  Bucket: bucket,
  Key: fileName,
  Expires: 60,
  ContentType: 'image/jpeg',
  ACL: 'public-read'
};

return s3.getSignedUrl('putObject', s3Params);

here is RN request to S3:

var file = {
  uri: game.pictureToSubmitUri,
  type: 'image/jpeg',
  name: 'image.jpg',
};

const xhr = new XMLHttpRequest();
var body = new FormData();
body.append('file', file);
xhr.open('PUT', signedRequest);
xhr.onreadystatechange = () => {
  if(xhr.readyState === 4){
    if(xhr.status === 200){
      alert('Posted!');
    }
    else{
      alert('Could not upload file.');
   }
 }
};
xhr.send(body);

game.pictureToSubmitUri = assets-library://asset/asset.JPG?id=A282A2C5-31C8-489F-9652-7D3BD5A1FAA4&ext=JPG

signedRequest = https://my-bucket.s3-us-west-1.amazonaws.com/8bd2d4b9-3206-4bff-944d-e06f872d8be3?AWSAccessKeyId=AKIAIOLHQY4GAXN26FOQ&Content-Type=image%2Fjpeg&Expires=1465671117&Signature=bkQIp5lgzuYrt2vyl7rqpCXPcps%3D&x-amz-acl=public-read

Error message:

SignatureDoesNotMatch
<Message>
The request signature we calculated does not match the signature you provided. Check your key and signing method.
</Message>

I can successfully curl and image to S3 using the generated url, and I seem to be able to successfully post to requestb.in from RN (however I can only see the raw data on requestb.in so not 100% sure the image is properly there).

Based on all this, I've narrowed my issue down to 1) my image is not correctly uploading period, or 2) somehow the way S3 wants my request is different then how it is coming in.

Any help would be muuuuuucchhhh appreciated!

UPDATE

Can successfully post from RN to S3 if body is just text ({'data': 'foo'}).  Perhaps AWS does not like mutliform data?  How can I send as just a file in RN???

Body:
FOR REACT NATIVE I WILL NOT BE USING ANY 3RD PARTY LIBS.

i have my pick image function that picks the image and upload using xhr

const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
     // mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
      base64:true
    });

    console.log(result);

    if (!result.cancelled) {
     // setImage(result.uri);
      let base64Img = `data:image/jpg;base64,${result.uri}`;

       // ImagePicker saves the taken photo to disk and returns a local URI to it
  let localUri = result.uri;
  let filename = localUri.split('/').pop();

  // Infer the type of the image
  let match = /\.(\w+)$/.exec(filename);
  let type = match ? `image/${match[1]}` : `image`;

  // Upload the image using the fetch and FormData APIs
  let formData = new FormData();
  // Assume "photo" is the name of the form field the server expects
  formData.append('file', { uri: base64Img, name: filename, type });

  const xhr = new XMLHttpRequest();

  xhr.open('GET', ENVIRONMENTS.CLIENT_API+`/sign-s3?file-name=${filename}&file-type=${type}`);
  xhr.setRequestHeader('Access-Control-Allow-Headers', '*');
xhr.setRequestHeader('Content-type', 'application/json');
// xhr.setRequestHeader('Content-type', 'multipart/form-data');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
 xhr.setRequestHeader('X-Amz-ACL', 'public-read') //added
xhr.setRequestHeader('Content-Type', type) //added
xhr.onreadystatechange = () => {
  if(xhr.readyState === 4){
    if(xhr.status === 200){
      const response = JSON.parse(xhr.responseText);
      alert(JSON.stringify( response.signedRequest, response.url))
      // uploadFile(file, response.signedRequest, response.url);
      // this.setState({imagename:file.name})
      const xhr2 = new XMLHttpRequest();

            xhr2.open('PUT', response.signedRequest);
            xhr2.setRequestHeader('Access-Control-Allow-Headers', '*');
            xhr2.setRequestHeader('Content-type', 'application/json');
            // xhr2.setRequestHeader('Content-type', 'multipart/form-data');
            xhr2.setRequestHeader('Access-Control-Allow-Origin', '*');
            //  xhr2.setRequestHeader('X-Amz-ACL', 'public-read') //added
            xhr2.setRequestHeader('Content-Type', type) //added
            xhr2.onreadystatechange = () => {
              if(xhr2.readyState === 4){
                if(xhr2.status === 200){

                  alert("successful upload ")
                }
                else{
                  // alert('Could not upload file.');
                  var error = new Error(xhr.responseText)
                  error.code = xhr.status;
                  for (var key in response) error[key] = response[key]
                  alert(error)
                }
              }
            };
            xhr2.send( result.base64)
    }
    else{
      alert('Could not get signed URL.');
    }
  }
};
xhr.send();

    }

  };

then some where in the render method

<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button title="Pick an image from camera roll" onPress={pickImage} />
      {image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
    </View>

hope it helps any one who doesnt want sleepless nights like me.


来源: stackexchange

问:
Handlebars.js Else If
I'm using Handlebars.js for client side view rendering.  If Else works great but I've encountered a 3 way conditional that requires ELSE IF:

This doesn't work:

{{#if FriendStatus.IsFriend }}

{{else if FriendStatus.FriendRequested}}

{{else}}

{{/if}}
```

How do I do ELSE IF with handlebars?

答:
Hello I have only a MINOR classname edit, and so far this is how iv divulged it. i think i need to pass in multpile parameters to the helper,

server.js

app.engine('handlebars', ViewEngine({
        "helpers":{
                isActive: (val, options)=>{
                    if (val === 3 || val === 0){
                        return options.fn(this)
                    }
                }
        }
}));
```

<p>header.handlebars</p>

<pre class="lang-html prettyprint-override"><code><ul class="navlist">
          <li   class="navitem navlink {{#isActive 0}}active{{/isActive}}"
                >Home</li>
          <li   class="navitem navlink {{#isActive 1}}active{{/isActive}}"
                >Trending</li>
          <li   class="navitem navlink {{#isActive 2}}active{{/isActive}}"
                >People</li>
          <li   class="navitem navlink {{#isActive 3}}active{{/isActive}}"
                >Mystery</li>
          <li class="navitem navbar-search">
            <input type="text" id="navbar-search-input" placeholder="Search...">
            <button type="button" id="navbar-search-button"><i class="fas fa-search"></i></button>
          </li>
        </ul>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Handlebars.js Else If

Body:
I'm using Handlebars.js for client side view rendering.  If Else works great but I've encountered a 3 way conditional that requires ELSE IF:

This doesn't work:

{{#if FriendStatus.IsFriend }}

{{else if FriendStatus.FriendRequested}}

{{else}}

{{/if}}

How do I do ELSE IF with handlebars?

Body:
Hello I have only a MINOR classname edit, and so far this is how iv divulged it. i think i need to pass in multpile parameters to the helper,

server.js

app.engine('handlebars', ViewEngine({
        "helpers":{
                isActive: (val, options)=>{
                    if (val === 3 || val === 0){
                        return options.fn(this)
                    }
                }
        }
}));

header.handlebars

<ul class="navlist">
          <li   class="navitem navlink {{#isActive 0}}active{{/isActive}}"
                ><a href="#">Home</a></li>
          <li   class="navitem navlink {{#isActive 1}}active{{/isActive}}"
                ><a href="#">Trending</a></li>
          <li   class="navitem navlink {{#isActive 2}}active{{/isActive}}"
                ><a href="#">People</a></li>
          <li   class="navitem navlink {{#isActive 3}}active{{/isActive}}"
                ><a href="#">Mystery</a></li>
          <li class="navitem navbar-search">
            <input type="text" id="navbar-search-input" placeholder="Search...">
            <button type="button" id="navbar-search-button"><i class="fas fa-search"></i></button>
          </li>
        </ul>

ContentLicense: CC BY-SA 4.0


问:
getting first level of categorisation from Notes view
I have a categorized Notes view, let say the first categorized column is TypeOfVehicle the second categorized column is Model and the third categorized column is Manufacturer.

I would like to collect only the values for the first category and return it as json object:

I am facing two problems:
- I can not read the value for the category, the column values are emptry and when I try to access the underlying document it is null

the script won't hop over to the category/sibling on the same level.

can someone explain me what am I doing wrong here?

```<code>private Object getFirstCategory() {
        JsonJavaObject json = new JsonJavaObject();
        try{
            String server = null;
            String filepath = null;
            server = props.getProperty("server");
            filepath = props.getProperty("filename");
            Database db;
            db = utils.getSession().getDatabase(server, filepath);
            if (db.isOpen()) {
                View vw = db.getView("transport");
                if (null != vw) {
                    vw.setAutoUpdate(false);
                    ViewNavigator nav;
                    nav = vw.createViewNav();

                    JsonJavaArray arr = new JsonJavaArray();
                    Integer count = 0;
                    ViewEntry tmpentry;
                    ViewEntry entry = nav.getFirst();
                    while (null != entry) {
                        Vector<?> columnValues = entry.getColumnValues();
                        if(entry.isCategory()){
                            System.out.println("entry notesid = " + entry.getNoteID());
                            Document doc = entry.getDocument();
                            if(null != doc){
                                if (doc.hasItem("TypeOfVehicle ")){
                                    System.out.println("category has not " + "TypeOfVehicle ");
                                }
                                else{
                                    System.out.println("category IS " + doc.getItemValueString("TypeOfVehicle "));
                                }
                            } else{
                                System.out.println("doc is null");
                            }

                            JsonJavaObject row = new JsonJavaObject();
                            JsonJavaObject jo = new JsonJavaObject();

                            String TypeOfVehicle  = String.valueOf(columnValues.get(0));
                            if (null != TypeOfVehicle ) {
                                if (!TypeOfVehicle .equals("")){
                                    jo.put("TypeOfVehicle ", TypeOfVehicle );
                                } else{
                                    jo.put("TypeOfVehicle ", "Not categorized");
                                }
                            } else {
                                jo.put("TypeOfVehicle ", "Not categorized");
                            }

                            row.put("request", jo);
                            arr.put(count, row);
                            count++;

                            tmpentry = nav.getNextSibling(entry);
                            entry.recycle();
                            entry = tmpentry;

                        } else{
                            //tmpentry = nav.getNextCategory();
                            //entry.recycle();
                            //entry = tmpentry;
                        }

                    }

                    json.put("data", arr);

                    vw.setAutoUpdate(true);
                    vw.recycle();
                }
            }
        } catch (Exception e) {
            OpenLogUtil.logErrorEx(e, JSFUtil.getXSPContext().getUrl().toString(), Level.SEVERE, null);
        }
        return json;
    }
</code>```

答:
What you're doing wrong is trying to treat any single view entry as both a category and a document. A single view entry can only be one of a category, a document, or a total.

If you have an entry for which isCategory() returns true, then for the same entry:

isDocument() will return false.

getDocument() will return null.

getNoteID() will return an empty string.

If the only thing you need is top-level categories, then get the first entry from the navigator and iterate over entries using nav.getNextSibling(entry) as you're already doing, but:

Don't try to get documents, note ids, or fields.

Use entry.getColumnValues().get(0) to get the value of the first column for each category.

If the view contains any uncategorised documents, it's possible that entry.getColumnValues().get(0) might throw an exception, so you should also check that entry.getColumnValues().size() is at least 1 before trying to get a value.

If you need any extra data beyond just top-level categories, then note that subcategories and documents are children of their parent categories.

If an entry has a subcategory, nav.getChild(entry) will get the first subcategory of that entry.

If an entry has no subcategories, but is a category which contains documents, nav.getChild(entry) will get the first document in that category.

Body:
I have a categorized Notes view, let say the first categorized column is TypeOfVehicle the second categorized column is Model and the third categorized column is Manufacturer.

I would like to collect only the values for the first category and return it as json object:

I am facing two problems:
- I can not read the value for the category, the column values are emptry and when I try to access the underlying document it is null

the script won't hop over to the category/sibling on the same level.

can someone explain me what am I doing wrong here?

private Object getFirstCategory() {
        JsonJavaObject json = new JsonJavaObject();
        try{
            String server = null;
            String filepath = null;
            server = props.getProperty("server");
            filepath = props.getProperty("filename");
            Database db;
            db = utils.getSession().getDatabase(server, filepath);
            if (db.isOpen()) {
                View vw = db.getView("transport");
                if (null != vw) {
                    vw.setAutoUpdate(false);
                    ViewNavigator nav;
                    nav = vw.createViewNav();

                    JsonJavaArray arr = new JsonJavaArray();
                    Integer count = 0;
                    ViewEntry tmpentry;
                    ViewEntry entry = nav.getFirst();
                    while (null != entry) {
                        Vector<?> columnValues = entry.getColumnValues();
                        if(entry.isCategory()){
                            System.out.println("entry notesid = " + entry.getNoteID());
                            Document doc = entry.getDocument();
                            if(null != doc){
                                if (doc.hasItem("TypeOfVehicle ")){
                                    System.out.println("category has not " + "TypeOfVehicle ");
                                }
                                else{
                                    System.out.println("category IS " + doc.getItemValueString("TypeOfVehicle "));
                                }
                            } else{
                                System.out.println("doc is null");
                            }

                            JsonJavaObject row = new JsonJavaObject();
                            JsonJavaObject jo = new JsonJavaObject();

                            String TypeOfVehicle  = String.valueOf(columnValues.get(0));
                            if (null != TypeOfVehicle ) {
                                if (!TypeOfVehicle .equals("")){
                                    jo.put("TypeOfVehicle ", TypeOfVehicle );
                                } else{
                                    jo.put("TypeOfVehicle ", "Not categorized");
                                }
                            } else {
                                jo.put("TypeOfVehicle ", "Not categorized");
                            }

                            row.put("request", jo);
                            arr.put(count, row);
                            count++;

                            tmpentry = nav.getNextSibling(entry);
                            entry.recycle();
                            entry = tmpentry;

                        } else{
                            //tmpentry = nav.getNextCategory();
                            //entry.recycle();
                            //entry = tmpentry;
                        }

                    }

                    json.put("data", arr);

                    vw.setAutoUpdate(true);
                    vw.recycle();
                }
            }
        } catch (Exception e) {
            OpenLogUtil.logErrorEx(e, JSFUtil.getXSPContext().getUrl().toString(), Level.SEVERE, null);
        }
        return json;
    }


问:
What is the functionality of this regex?
I am recently learning regex and i am not quite sure how the following regex works:

```<code>str.replaceAll("(\\w)(\\w*)", "$2$1ay");
</code>```

This allows us to do the following:

```<code>input string: "Hello World !"
return string: "elloHay orldWay !"
</code>```

From what I know: w is supposed to match all word characters including 0-9 and underscore and $ matches stuff at the end of string.

答:
Enclosing a regex expression in brackets () will make it a Capturing group.

Here you have 2 capturing groups , (\w) captures a single word character, and (\w*) catches zero or more.
$1 and $2 are used to refer to the captured groups, first and second respectively.

Also replaceAll takes each word individually.
So in this example in  'Hello' , 'H' is the first captured groups and 'ello' is the second. It's replaced by a reordered version - $2$1 which is basically swapping the captured groups.
So you get '$2$1ay' as 'elloHay'

The same for the next word also.

Body:
I am recently learning regex and i am not quite sure how the following regex works:

str.replaceAll("(\\w)(\\w*)", "$2$1ay");

This allows us to do the following:

input string: "Hello World !"
return string: "elloHay orldWay !"

From what I know: w is supposed to match all word characters including 0-9 and underscore and $ matches stuff at the end of string.


问:
Selenium c# - how do i test that an image src file exists (verifying if the image shows on the page)
im new to Selenium and c# so I've hit a dead end.  I need to know how to check weather an images src file exists or not.  When I mean exists, is it showing on the page (not the red x box you get when no image is present).

I have tried file.exists(@c://imagename); and System.File.Exists.

I don't know if this is correct or not.

Any help would be great!! My heads fried with this

Thanks

答:
Assuming that the path to the image is relative in the src attribute you would need to work out the URL then run a test similar to the one outlined in this answer:

Test to see if an image exists in C#

If you really need to check if the image exists and has been deployed (I would question if this is a qorthwhile test to be honest) you could use something like the code below:

```<code>HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://full-path-to-your-image.png");
request.Method = "HEAD";

bool exists;
try
{
    request.GetResponse();
    exists = true;
}
catch
{
   exists = false;
}
</code>```

It basically checks the URL (of the image in your case), to see if the images exists.

If you need a hand with it turn round and ask ;)

Body:
Assuming that the path to the image is relative in the src attribute you would need to work out the URL then run a test similar to the one outlined in this answer:

Test to see if an image exists in C#

If you really need to check if the image exists and has been deployed (I would question if this is a qorthwhile test to be honest) you could use something like the code below:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://full-path-to-your-image.png");
request.Method = "HEAD";

bool exists;
try
{
    request.GetResponse();
    exists = true;
}
catch
{
   exists = false;
}

It basically checks the URL (of the image in your case), to see if the images exists.

If you need a hand with it turn round and ask ;)


问:
parsing the string into the json in the method of yeoman generator
I am using yeoman generator to create a code with the template, where the data for the template is passed in the option as a string showed as below,

```<code>yo express-no-stress myapp --data {"title":"Type"}
</code>```

this string data can be parsed as JSON later in the install methods.

```<code>  install() {
      async app() {
         let str = this.options.data;
         if(str != undefined && typeof str == 'string') {
              console.log(str);
              let field_property = JSON.parse(str);
         }
        .....
      } // parseapp
  }// install
</code>```

however when running the application, it always encounters an error saying
"syntaxError: Unexpected token t in JSON at position 1" in the JSON.parse() method.

I don't get why it causes this error, any idea, thanks.

答:
You have to enclose your JSON in single quotes in the command line:

```<code>yo express-no-stress myapp --data '{"title":"Type"}'
</code>```

Otherwise your shell tries to evaluate it.

Body:
I am using yeoman generator to create a code with the template, where the data for the template is passed in the option as a string showed as below,

yo express-no-stress myapp --data {"title":"Type"}

this string data can be parsed as JSON later in the install methods.

  install() {
      async app() {
         let str = this.options.data;
         if(str != undefined && typeof str == 'string') {
              console.log(str);
              let field_property = JSON.parse(str);
         }
        .....
      } // parseapp
  }// install

however when running the application, it always encounters an error saying
"syntaxError: Unexpected token t in JSON at position 1" in the JSON.parse() method.

I don't get why it causes this error, any idea, thanks.

Body:
You have to enclose your JSON in single quotes in the command line:

yo express-no-stress myapp --data '{"title":"Type"}'

Otherwise your shell tries to evaluate it.


问:
How to invoke the map functional from a javascript Array
Why is the map() not being invoked here?

let N = 16;
let fullSizeBufs = Array(2).map((x) =>
  Array(N).fill(-1)
)
console.log(fullSizeBufs)```
</div>
</div>
</p>

<p>We get </p>

```[undefined, undefined]
```

I even put a breakpoint on the  Array(N).fill(-1) : it is not hit. The map() is just skipped.  What is the correct syntax for this?

答:
You have to fill the first array, or map has nothing to iterate on.  The Array constructor initializes with references undefined, which is not the same as [undefined, undefined, undefined], which is actually an array of 3 references to undefined.

eg: [,,,].map(x=>console.log(x)) vs [undefined,undefined,undefined].map(x=>console.log(x))

let N = 16;
let fullSizeBufs = Array(2).fill(0).map((x) =>
  Array(N).fill(-1)
)
console.log(fullSizeBufs)```

Body:
Why is the map() not being invoked here?

let N = 16;
let fullSizeBufs = Array(2).map((x) =>
  Array(N).fill(-1)
)
console.log(fullSizeBufs)

We get

[undefined, undefined]

I even put a breakpoint on the  Array(N).fill(-1) : it is not hit. The map() is just skipped.  What is the correct syntax for this?


问:
what does git bundle command do?
I have been asked to do a project (react-firebase).

On submission one of the instruction is to run

```<code>git bundle create ../${PWD##*/}.bundle --all to create a .bundle file with the repo contents
</code>```

I am not sure what the above means. Can someone help in figuring what I need to do?

答:
git bundle create ../${PWD##*/}.bundle --all creates a bundle whose path is ../${PWD##*/}.bundle. The bundle is like a mirror image of the repository with all refs (by --all). It works as a read-only repository.

For example, you can run git clone <path_to_bundle> to create a cloned repository, git fetch <path_to_bundle> master to fetch master from the bundle, git ls-remote to list all the refs in the bundle. But it would fail if you run git push <path_to_bundle> master. It's read-only for git commands.

Title: what does git bundle command do?

Body:
I have been asked to do a project (react-firebase).

On submission one of the instruction is to run

git bundle create ../${PWD##*/}.bundle --all to create a .bundle file with the repo contents

I am not sure what the above means. Can someone help in figuring what I need to do?


问:
How to write a python program to find the second most repeated word in a given string
I have the string as Welcome to Datacurators.tech and i need to find out second most repeated character in the given string. I need to use only basic python code ( not to use import or def functions). i have the below code but it gives me count of all the characters. Expected output ( e,c,o,a) output could be in any order.

```<code>stri = "Welcome to Datacurators.tech"
counts={}
for i in stri:
    counts[i]=stri.count(i)
print (counts)
</code>```

答:
Following your code, you can first get the second large number and then get all char which count equals to the number:</p>

```<code>second_large_count = sorted(set(counts.values()),reverse=True)[1] # 1 means second (large) item

second_large_char_set = {k for k,v in counts.items() if v ==second_large_count}

print(second_large_char_set)
</code>```

Body:
I have the string as Welcome to Datacurators.tech and i need to find out second most repeated character in the given string. I need to use only basic python code ( not to use import or def functions). i have the below code but it gives me count of all the characters. Expected output ( e,c,o,a) output could be in any order.

stri = "Welcome to Datacurators.tech"
counts={}
for i in stri:
    counts[i]=stri.count(i)
print (counts)

Body:
Following your code, you can first get the second large number and then get all char which count equals to the number:

second_large_count = sorted(set(counts.values()),reverse=True)[1] # 1 means second (large) item

second_large_char_set = {k for k,v in counts.items() if v ==second_large_count}

print(second_large_char_set)


问:
Streaming data from on-prem database to Oracle OCI Obejctstorage
I have an on-prem database that has 50GB of JSON data. I'm planning to take the backup of this data to OCI object storage using Java SDK to a single object in a bucket. on-prem database paginates JSON data result. How can I stream/upload each page of data to OCI object storage whenever it arrives? Do I need to use multipart upload? Is there any example that shows the streaming of data to object storage?

The example in SDK shows uploading a file to Objectstorage but my requirement is to stream data without storing it to temp files.

答:
do you want to upload the individual JSON pages, or do you need to combine them back together first into a single JSON object?

I don't think the OCI Java SDK can help you with combining the different pages. For that, you may need a JSON serializer/deserializer, or possibly even work with plain JSON Strings. If the object is large enough, you may not want to actually parse it. Handling Strings is less robust, but possibly faster and more memory-efficient.

To upload, you would either use putObject in the ObjectStorageClient, or use the UploadManager. The latter can upload in multiple parts and is ideal for large objects. Here is an example: https://github.com/oracle/oci-java-sdk/blob/master/bmc-examples/src/main/java/UploadObjectExample.java


问:
Usage of printf and fgets together in a loop
I am trying to implement a simple program which infinitely reads input from the user and then prints it. But there are some problems. It is a simple issue but my Google searches didn't lead me any solution. Here is the code.

```<code>int main() {

    char pass[32];
    int x=10;

    while (x!=0) {

        printf("\nInput the password: ");
        fgets(pass, sizeof(pass), stdin);

        printf("that is what i read: %s", pass);
    }
    return 0;
}
</code>```

When I enter a string longer than 32 characters, it behaves anormally.

```<code>Input the password: pass
that is what i read: pass

Input the password: passsssss
that is what i read: passsssss

Input the password: passssssssssssssssssssssssssssssss
that is what i read: passsssssssssssssssssssssssssss
Input the password: that is what i read: sss

Input the password:
</code>```

You see in the third attempt, it prints the third line automatically. I didn't type the input 'that is what i read: sss'.

Why does that happen?

答:
The safe solution when using fgets would be something like this:

```<code>if (fgets(pass, sizeof(pass), stdin) != NULL){
    int len = strlen(pass);
    if (len > 0 && pass[len-1] != '\n'){
        int ch;
        while ((ch=getchar()) != '\n' && ch != EOF);
    }
}
</code>```

Or this:

```<code>if (fgets(pass, sizeof(pass), stdin) != NULL){
    if (strcspn(pass, "\n") == sizeof(pass) - 1){
        int ch;
        while ((ch=getchar()) != '\n' && ch != EOF);
    }
}
</code>```

You need to check if there is a new line character \n in the string, if there isn't then there is excess characters left in the stdin that must be cleared.

Body:
I am trying to implement a simple program which infinitely reads input from the user and then prints it. But there are some problems. It is a simple issue but my Google searches didn't lead me any solution. Here is the code.

int main() {

    char pass[32];
    int x=10;

    while (x!=0) {

        printf("\nInput the password: ");
        fgets(pass, sizeof(pass), stdin);

        printf("that is what i read: %s", pass);
    }
    return 0;
}

When I enter a string longer than 32 characters, it behaves anormally.

Input the password: pass
that is what i read: pass

Input the password: passsssss
that is what i read: passsssss

Input the password: passssssssssssssssssssssssssssssss
that is what i read: passsssssssssssssssssssssssssss
Input the password: that is what i read: sss

Input the password:

You see in the third attempt, it prints the third line automatically. I didn't type the input 'that is what i read: sss'.

Why does that happen?

Body:
The safe solution when using fgets would be something like this:

if (fgets(pass, sizeof(pass), stdin) != NULL){
    int len = strlen(pass);
    if (len > 0 && pass[len-1] != '\n'){
        int ch;
        while ((ch=getchar()) != '\n' && ch != EOF);
    }
}

Or this:

if (fgets(pass, sizeof(pass), stdin) != NULL){
    if (strcspn(pass, "\n") == sizeof(pass) - 1){
        int ch;
        while ((ch=getchar()) != '\n' && ch != EOF);
    }
}

You need to check if there is a new line character \n in the string, if there isn't then there is excess characters left in the stdin that must be cleared.


问:
why am i getting error when importing AudioSegment?
i'm trying to use pydub, but when i import it to python with AudioSegment it will give me an error saying it doesn't recognize it.
i tried using pip install and searching online.
any help??
i'm using python 2.7 </p>

```<code>from pydub import AudioSegment
</code>```

答:
Tried @paolov's solution - didn't work until I had restarted pycharm / python editor...

Also - see Python convert mp3 to wav with Pydub for quick alternative that doesn't necessary require pydub (but still needs ffmpeg)... involves import subprocess, thanks to @Roland Smith

PS - also, see http://blog.gregzaal.com/how-to-install-ffmpeg-on-windows/ for description of how to add to PATH - in context of ffmpeg).  I added to folder within my PyCharm/Python project instead of straight on C drive... either should work, but as I say, try restarting editor, and check cmd line > ffmpeg -codecs after adding to PATH...

Body:
i'm trying to use pydub, but when i import it to python with AudioSegment it will give me an error saying it doesn't recognize it.
i tried using pip install and searching online.
any help??
i'm using python 2.7

from pydub import AudioSegment


问:
ReactNative - How to exclude format when using paste on TextInput
React Native : 0.61.4

If paste formatted text into my TextInput, the styles of TextInput are ignored.

```<code> <TextInput
    multiline
    scrollEnabled={false}
    inputAccessoryViewID="reviewButton"
    style={{
      fontSize: 20,
      alignSelf: 'center',
      marginHorizontal: '15%',
      flex: 1,
      textAlignVertical: 'top',
      color: 'black',
    }}
    value={content}
    maxLength={200}
    onChangeText={changeContent}
  />
</code>```

I specified the color and fontSize in the style of TextInput, but when I use paste, the color and fontSize are different.

How can I remove Text format when pasting?

It only happens on Android.

答:
After doing some research and try to recreate your case in some famous React native app, I think its can't be possible :)

And btw, in case you haven't notice yet, in Android, there are always two options for pasting including Paste and Paste as plain text.

Body:
React Native : 0.61.4

If paste formatted text into my TextInput, the styles of TextInput are ignored.

 <TextInput
    multiline
    scrollEnabled={false}
    inputAccessoryViewID="reviewButton"
    style={{
      fontSize: 20,
      alignSelf: 'center',
      marginHorizontal: '15%',
      flex: 1,
      textAlignVertical: 'top',
      color: 'black',
    }}
    value={content}
    maxLength={200}
    onChangeText={changeContent}
  />

I specified the color and fontSize in the style of TextInput, but when I use paste, the color and fontSize are different.

How can I remove Text format when pasting?

It only happens on Android.


问:
Flink slot removed exception
I am getting the following exception

```<code>org.apache.flink.util.FlinkException: The assigned slot container_1546939492951_0001_01_003659_0 was removed.
at org.apache.flink.runtime.resourcemanager.slotmanager.SlotManager.removeSlot(SlotManager.java:789)
at org.apache.flink.runtime.resourcemanager.slotmanager.SlotManager.removeSlots(SlotManager.java:759)
at org.apache.flink.runtime.resourcemanager.slotmanager.SlotManager.internalUnregisterTaskManager(SlotManager.java:951)
at org.apache.flink.runtime.resourcemanager.slotmanager.SlotManager.unregisterTaskManager(SlotManager.java:372)
at org.apache.flink.runtime.resourcemanager.ResourceManager.closeTaskManagerConnection(ResourceManager.java:823)
at org.apache.flink.yarn.YarnResourceManager.lambda$onContainersCompleted$0(YarnResourceManager.java:346)
at org.apache.flink.runtime.rpc.akka.AkkaRpcActor.handleRunAsync(AkkaRpcActor.java:332)
at org.apache.flink.runtime.rpc.akka.AkkaRpcActor.handleRpcMessage(AkkaRpcActor.java:158)
at org.apache.flink.runtime.rpc.akka.FencedAkkaRpcActor.handleRpcMessage(FencedAkkaRpcActor.java:70)
at org.apache.flink.runtime.rpc.akka.AkkaRpcActor.onReceive(AkkaRpcActor.java:142)
at org.apache.flink.runtime.rpc.akka.FencedAkkaRpcActor.onReceive(FencedAkkaRpcActor.java:40)
at akka.actor.UntypedActor$$anonfun$receive$1.applyOrElse(UntypedActor.scala:165)
at akka.actor.Actor$class.aroundReceive(Actor.scala:502)
at akka.actor.UntypedActor.aroundReceive(UntypedActor.scala:95)
at akka.actor.ActorCell.receiveMessage(ActorCell.scala:526)
at akka.actor.ActorCell.invoke(ActorCell.scala:495)
at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:257)
at akka.dispatch.Mailbox.run(Mailbox.scala:224)
at akka.dispatch.Mailbox.exec(Mailbox.scala:234)
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
</code>```

when running a batch process involving joining two very large datasets.

Here is what I can see in the overview. The failure happened on a task manager which did not get any inputs. Weirdly the previous set (partition -> flat map -> map) did not send anything to that task manager despite having a rebalance in front.

Am running it on EMR. I see that there is a slot.idle.timeout, would that have an effect and if so how do I specify it for that job? Can it be done on the command line?

答: This issue is not always cause by oom and killed by yarn,if you have log like this:"Closing TaskExecutor connection container_e86_1590402668190_3503_01_000015 because: Container released on a lost node",and it is before your error log.I am guessing this problem cause by Nodemanager down.About 10 minutes ,flink ResourceManager can not communicate with NodeManager,ResourceManager will start to remove slot ,and restart(if you have restart strategy).

Title: Flink slot removed exception

Body:
I am getting the following exception

org.apache.flink.util.FlinkException: The assigned slot container_1546939492951_0001_01_003659_0 was removed.
at org.apache.flink.runtime.resourcemanager.slotmanager.SlotManager.removeSlot(SlotManager.java:789)
at org.apache.flink.runtime.resourcemanager.slotmanager.SlotManager.removeSlots(SlotManager.java:759)
at org.apache.flink.runtime.resourcemanager.slotmanager.SlotManager.internalUnregisterTaskManager(SlotManager.java:951)
at org.apache.flink.runtime.resourcemanager.slotmanager.SlotManager.unregisterTaskManager(SlotManager.java:372)
at org.apache.flink.runtime.resourcemanager.ResourceManager.closeTaskManagerConnection(ResourceManager.java:823)
at org.apache.flink.yarn.YarnResourceManager.lambda$onContainersCompleted$0(YarnResourceManager.java:346)
at org.apache.flink.runtime.rpc.akka.AkkaRpcActor.handleRunAsync(AkkaRpcActor.java:332)
at org.apache.flink.runtime.rpc.akka.AkkaRpcActor.handleRpcMessage(AkkaRpcActor.java:158)
at org.apache.flink.runtime.rpc.akka.FencedAkkaRpcActor.handleRpcMessage(FencedAkkaRpcActor.java:70)
at org.apache.flink.runtime.rpc.akka.AkkaRpcActor.onReceive(AkkaRpcActor.java:142)
at org.apache.flink.runtime.rpc.akka.FencedAkkaRpcActor.onReceive(FencedAkkaRpcActor.java:40)
at akka.actor.UntypedActor$$anonfun$receive$1.applyOrElse(UntypedActor.scala:165)
at akka.actor.Actor$class.aroundReceive(Actor.scala:502)
at akka.actor.UntypedActor.aroundReceive(UntypedActor.scala:95)
at akka.actor.ActorCell.receiveMessage(ActorCell.scala:526)
at akka.actor.ActorCell.invoke(ActorCell.scala:495)
at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:257)
at akka.dispatch.Mailbox.run(Mailbox.scala:224)
at akka.dispatch.Mailbox.exec(Mailbox.scala:234)
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

when running a batch process involving joining two very large datasets.

Here is what I can see in the overview. The failure happened on a task manager which did not get any inputs. Weirdly the previous set (partition -> flat map -> map) did not send anything to that task manager despite having a rebalance in front.

Am running it on EMR. I see that there is a slot.idle.timeout, would that have an effect and if so how do I specify it for that job? Can it be done on the command line?


问:
Is it possible, how to show diff between commits in github?
A user proposed a localization to an open source project; however, they proposed a localization for an old version. I'd like to point them at the changes that were made between the two.

I know that I can show the difference between branches by providing the following link:

```<code>https://github.com/<user or organization>/<project>/master...master:<branch name>
</code>```

Is there a similar interface for comparing certain commits? (and, ideally, only versions of a certain file) I'd like not to bother the potential contributor with learning git and doing the diff locally in the first place (although that I'll suggest that in the future).

I've tried

```<code>https://github.com/<user or organization>/<project>/master...master:<hash>
</code>```

but that didn't work which is kinda expected; and I haven't found any reference on this matter either.

答:
You can compare the difference between two commits on GitHub by using the below URL

```<code>https://github.com/{user}/{repo}/compare/{commit-1-hash}..{commit-2-hash}
</code>```

For eg, to compare the diff between commits c3a414e and faf7c6f for the linguist repo of github, use the below

```<code>https://github.com/github/linguist/compare/c3a414e..faf7c6f
</code>```

The above will show the diff like this:

You can go through the GitHub reference for more information.

Body:
A user proposed a localization to an open source project; however, they proposed a localization for an old version. I'd like to point them at the changes that were made between the two.

I know that I can show the difference between branches by providing the following link:

https://github.com/<user or organization>/<project>/master...master:<branch name>

Is there a similar interface for comparing certain commits? (and, ideally, only versions of a certain file) I'd like not to bother the potential contributor with learning git and doing the diff locally in the first place (although that I'll suggest that in the future).

I've tried

https://github.com/<user or organization>/<project>/master...master:<hash>

but that didn't work which is kinda expected; and I haven't found any reference on this matter either.

Body:
You can compare the difference between two commits on GitHub by using the below URL

https://github.com/{user}/{repo}/compare/{commit-1-hash}..{commit-2-hash}

For eg, to compare the diff between commits c3a414e and faf7c6f for the linguist repo of github, use the below

https://github.com/github/linguist/compare/c3a414e..faf7c6f

The above will show the diff like this:

You can go through the GitHub reference for more information.


问:
Find sets that contain at least one element from other sets
Suppose we are given n sets and want to construct all minimal sets that have at least one element in common with each of the input sets. A set S is called minimal, if there is no admissible set S' that is a subset of S.

An example:

```<code>In: s1 = {1, 2, 3}; s2 = {3, 4, 5}; s3 = {5, 6}

Out: [{1, 4, 6}, {1, 5}, {2, 4, 6}, {2, 5}, {3, 5}, {3, 6}]
</code>```

My idea was to iteratively add one set after the other to the solution:

```<code>result = f(s1, f(s2, f(s3, ...)))
</code>```

whereby f is a merge function that could look as follows:

```<code>function f(newSet, setOfSets):
   Step 1:
      return all elements of setOfSets that share an element with newSet

   Step 2:
      for each remaining element setE of setOfSets:
         for each element e of newSet:
            return union(setE, {e})
</code>```

The issue with the above appraoch is that the cartesian product computed in step 2 may contain supersets of sets returned in step 1. I was thinking of going through all already returned sets (see Find minimal set of subsets that covers a given set), but this seems to be too complicated and inefficient, and I hope that there is a better solution in my special case.

How could I achieve the goal without determining the full cartesian product in step 2?

Note that this question is related to the question of finding the smallest set only, but I need to find all sets that are minimal in the way specified above. I am aware that the number of solutions will not be polynomial.

The number n of input sets will be several hundret, but the sets contain only elements from a limited range (e.g. about 20 different values), which also limits the sets' sizes. It would be acceptible if the algorithm runs in O(n^2), but it should be basically linear (maybe with a log multiplier) of the output sets.

答:
I have come up with a solution based on the trie data structure as described here. Tries make it relatively fast to determine whether one of the stored sets is a subset of another given set (Savnik, 2013).

The solution then looks as follows:

Create a trie

Iterate through the given sets

In each iteration, go through the sets in the trie and check if they are disjoint with the new set.

If they are, continue; if not, add corresponding new sets to the trie unless they are supersets of sets in the trie.

The worst-case runtime is O(n m c), whereby m is the maximal number of solutions if we consider only n' <= n of the input sets, and c is the time factor from the subset lookups.

The code is below. I have implemented the algorithm based on the python package datrie, which is a wrapper around an efficent C implementation of a trie. The code below is in cython but can be converted to pure python easily by removing/exchangin cython specific commands.

The extended trie implementation:

```<code>from datrie cimport BaseTrie, BaseState, BaseIterator

cdef bint has_subset_c(BaseTrie trie, BaseState trieState, str setarr,
                        int index, int size):
    cdef BaseState trieState2 = BaseState(trie)
    cdef int i
    trieState.copy_to(trieState2)
    for i in range(index, size):
        if trieState2.walk(setarr[i]):
            if trieState2.is_terminal() or has_subset_c(trie, trieState2, setarr,
                                                        i, size):
                return True
            trieState.copy_to(trieState2)
    return False

cdef class SetTrie():
    def __init__(self, alphabet, initSet=[]):
        if not hasattr(alphabet, "__iter__"):
            alphabet = range(alphabet)
        self.trie = BaseTrie("".join(chr(i) for i in alphabet))
        self.touched = False
        for i in initSet:
            self.trie[chr(i)] = 0
            if not self.touched:
                self.touched = True

    def has_subset(self, superset):
        cdef BaseState trieState = BaseState(self.trie)
        setarr = "".join(chr(i) for i in superset)
        return bool(has_subset_c(self.trie, trieState, setarr, 0, len(setarr)))

    def extend(self, sets):
        for s in sets:
            self.trie["".join(chr(i) for i in s)] = 0
            if not self.touched:
                self.touched = True

    def delete_supersets(self):
        cdef str elem
        cdef BaseState trieState = BaseState(self.trie)
        cdef BaseIterator trieIter = BaseIterator(BaseState(self.trie))
        if trieIter.next():
            elem = trieIter.key()
            while trieIter.next():
                self.trie._delitem(elem)
                if not has_subset_c(self.trie, trieState, elem, 0, len(elem)):
                    self.trie._setitem(elem, 0)
                elem = trieIter.key()
            if has_subset_c(self.trie, trieState, elem, 0, len(elem)):
                val = self.trie.pop(elem)
                if not has_subset_c(self.trie, trieState, elem, 0, len(elem)):
                    self.trie._setitem(elem, val)

    def update_by_settrie(self, SetTrie setTrie, maxSize=inf, initialize=True):
        cdef BaseIterator trieIter = BaseIterator(BaseState(setTrie.trie))
        cdef str s
        if initialize and not self.touched and trieIter.next():
            for s in trieIter.key():
                self.trie._setitem(s, 0)
            self.touched = True

        while trieIter.next():
            self.update(set(trieIter.key()), maxSize, True)

    def update(self, otherSet, maxSize=inf, isStrSet=False):
        if not isStrSet:
            otherSet = set(chr(i) for i in otherSet)
        cdef str subset, newSubset, elem
        cdef list disjointList = []
        cdef BaseTrie trie = self.trie
        cdef int l
        cdef BaseIterator trieIter = BaseIterator(BaseState(self.trie))
        if trieIter.next():
            subset = trieIter.key()
            while trieIter.next():
                if otherSet.isdisjoint(subset):
                    disjointList.append(subset)
                    trie._delitem(subset)
                subset = trieIter.key()
            if otherSet.isdisjoint(subset):
                disjointList.append(subset)
                trie._delitem(subset)

        cdef BaseState trieState = BaseState(self.trie)
        for subset in disjointList:
            l = len(subset)
            if l < maxSize:
                if l+1 > self.maxSizeBound:
                    self.maxSizeBound = l+1
                for elem in otherSet:
                    newSubset = subset + elem
                    trieState.rewind()
                    if not has_subset_c(self.trie, trieState, newSubset, 0,
                                        len(newSubset)):
                        trie[newSubset] = 0

    def get_frozensets(self):
        return (frozenset(ord(t) for t in subset) for subset in self.trie)

    def clear(self):
        self.touched = False
        self.trie.clear()

    def prune(self, maxSize):
        cdef bint changed = False
        cdef BaseIterator trieIter
        cdef str k
        if self.maxSizeBound > maxSize:
            self.maxSizeBound = maxSize
            trieIter = BaseIterator(BaseState(self.trie))
            k = ''
            while trieIter.next():
                if len(k) > maxSize:
                    self.trie._delitem(k)
                    changed = True
                k = trieIter.key()
            if len(k) > maxSize:
                self.trie._delitem(k)
                changed = True
        return changed

    def __nonzero__(self):
        return self.touched

    def __repr__(self):
        return str([set(ord(t) for t in subset) for subset in self.trie])

</code>```

This can be used as follows:

```<code>def cover_sets(sets):
    strie = SetTrie(range(10), *([i] for i in sets[0]))
    for s in sets[1:]:
        strie.update(s)
    return strie.get_frozensets()
</code>```

Timing:

```<code>from timeit import timeit
s1 = {1, 2, 3}
s2 = {3, 4, 5}
s3 = {5, 6}
%timeit cover_sets([s1, s2, s3])
</code>```

Result:

```<code>37.8 µs ± 2.97 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code>```

Note that the trie implementation above works only with keys larger than (and not equal to) 0. Otherwise, the integer to character mapping does not work properly. This problem can be solved with an index shift.

Body:
Suppose we are given n sets and want to construct all minimal sets that have at least one element in common with each of the input sets. A set S is called minimal, if there is no admissible set S' that is a subset of S.

An example:

In: s1 = {1, 2, 3}; s2 = {3, 4, 5}; s3 = {5, 6}

Out: [{1, 4, 6}, {1, 5}, {2, 4, 6}, {2, 5}, {3, 5}, {3, 6}]

My idea was to iteratively add one set after the other to the solution:

result = f(s1, f(s2, f(s3, ...)))

whereby f is a merge function that could look as follows:

function f(newSet, setOfSets):
   Step 1:
      return all elements of setOfSets that share an element with newSet

   Step 2:
      for each remaining element setE of setOfSets:
         for each element e of newSet:
            return union(setE, {e})

The issue with the above appraoch is that the cartesian product computed in step 2 may contain supersets of sets returned in step 1. I was thinking of going through all already returned sets (see Find minimal set of subsets that covers a given set), but this seems to be too complicated and inefficient, and I hope that there is a better solution in my special case.

How could I achieve the goal without determining the full cartesian product in step 2?

Note that this question is related to the question of finding the smallest set only, but I need to find all sets that are minimal in the way specified above. I am aware that the number of solutions will not be polynomial.

The number n of input sets will be several hundret, but the sets contain only elements from a limited range (e.g. about 20 different values), which also limits the sets' sizes. It would be acceptible if the algorithm runs in O(n^2), but it should be basically linear (maybe with a log multiplier) of the output sets.

Body:
I have come up with a solution based on the trie data structure as described here. Tries make it relatively fast to determine whether one of the stored sets is a subset of another given set (Savnik, 2013).

The solution then looks as follows:

Create a trie

Iterate through the given sets

In each iteration, go through the sets in the trie and check if they are disjoint with the new set.

If they are, continue; if not, add corresponding new sets to the trie unless they are supersets of sets in the trie.

The worst-case runtime is O(n m c), whereby m is the maximal number of solutions if we consider only n' <= n of the input sets, and c is the time factor from the subset lookups.

The code is below. I have implemented the algorithm based on the python package datrie, which is a wrapper around an efficent C implementation of a trie. The code below is in cython but can be converted to pure python easily by removing/exchangin cython specific commands.

The extended trie implementation:

from datrie cimport BaseTrie, BaseState, BaseIterator

cdef bint has_subset_c(BaseTrie trie, BaseState trieState, str setarr,
                        int index, int size):
    cdef BaseState trieState2 = BaseState(trie)
    cdef int i
    trieState.copy_to(trieState2)
    for i in range(index, size):
        if trieState2.walk(setarr[i]):
            if trieState2.is_terminal() or has_subset_c(trie, trieState2, setarr,
                                                        i, size):
                return True
            trieState.copy_to(trieState2)
    return False

cdef class SetTrie():
    def __init__(self, alphabet, initSet=[]):
        if not hasattr(alphabet, "__iter__"):
            alphabet = range(alphabet)
        self.trie = BaseTrie("".join(chr(i) for i in alphabet))
        self.touched = False
        for i in initSet:
            self.trie[chr(i)] = 0
            if not self.touched:
                self.touched = True

    def has_subset(self, superset):
        cdef BaseState trieState = BaseState(self.trie)
        setarr = "".join(chr(i) for i in superset)
        return bool(has_subset_c(self.trie, trieState, setarr, 0, len(setarr)))

    def extend(self, sets):
        for s in sets:
            self.trie["".join(chr(i) for i in s)] = 0
            if not self.touched:
                self.touched = True

    def delete_supersets(self):
        cdef str elem
        cdef BaseState trieState = BaseState(self.trie)
        cdef BaseIterator trieIter = BaseIterator(BaseState(self.trie))
        if trieIter.next():
            elem = trieIter.key()
            while trieIter.next():
                self.trie._delitem(elem)
                if not has_subset_c(self.trie, trieState, elem, 0, len(elem)):
                    self.trie._setitem(elem, 0)
                elem = trieIter.key()
            if has_subset_c(self.trie, trieState, elem, 0, len(elem)):
                val = self.trie.pop(elem)
                if not has_subset_c(self.trie, trieState, elem, 0, len(elem)):
                    self.trie._setitem(elem, val)

    def update_by_settrie(self, SetTrie setTrie, maxSize=inf, initialize=True):
        cdef BaseIterator trieIter = BaseIterator(BaseState(setTrie.trie))
        cdef str s
        if initialize and not self.touched and trieIter.next():
            for s in trieIter.key():
                self.trie._setitem(s, 0)
            self.touched = True

        while trieIter.next():
            self.update(set(trieIter.key()), maxSize, True)

    def update(self, otherSet, maxSize=inf, isStrSet=False):
        if not isStrSet:
            otherSet = set(chr(i) for i in otherSet)
        cdef str subset, newSubset, elem
        cdef list disjointList = []
        cdef BaseTrie trie = self.trie
        cdef int l
        cdef BaseIterator trieIter = BaseIterator(BaseState(self.trie))
        if trieIter.next():
            subset = trieIter.key()
            while trieIter.next():
                if otherSet.isdisjoint(subset):
                    disjointList.append(subset)
                    trie._delitem(subset)
                subset = trieIter.key()
            if otherSet.isdisjoint(subset):
                disjointList.append(subset)
                trie._delitem(subset)

        cdef BaseState trieState = BaseState(self.trie)
        for subset in disjointList:
            l = len(subset)
            if l < maxSize:
                if l+1 > self.maxSizeBound:
                    self.maxSizeBound = l+1
                for elem in otherSet:
                    newSubset = subset + elem
                    trieState.rewind()
                    if not has_subset_c(self.trie, trieState, newSubset, 0,
                                        len(newSubset)):
                        trie[newSubset] = 0

    def get_frozensets(self):
        return (frozenset(ord(t) for t in subset) for subset in self.trie)

    def clear(self):
        self.touched = False
        self.trie.clear()

    def prune(self, maxSize):
        cdef bint changed = False
        cdef BaseIterator trieIter
        cdef str k
        if self.maxSizeBound > maxSize:
            self.maxSizeBound = maxSize
            trieIter = BaseIterator(BaseState(self.trie))
            k = ''
            while trieIter.next():
                if len(k) > maxSize:
                    self.trie._delitem(k)
                    changed = True
                k = trieIter.key()
            if len(k) > maxSize:
                self.trie._delitem(k)
                changed = True
        return changed

    def __nonzero__(self):
        return self.touched

    def __repr__(self):
        return str([set(ord(t) for t in subset) for subset in self.trie])

This can be used as follows:

def cover_sets(sets):
    strie = SetTrie(range(10), *([i] for i in sets[0]))
    for s in sets[1:]:
        strie.update(s)
    return strie.get_frozensets()

Timing:

from timeit import timeit
s1 = {1, 2, 3}
s2 = {3, 4, 5}
s3 = {5, 6}
%timeit cover_sets([s1, s2, s3])

Result:

37.8 µs ± 2.97 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Note that the trie implementation above works only with keys larger than (and not equal to) 0. Otherwise, the integer to character mapping does not work properly. This problem can be solved with an index shift.


问:
Azure Key Vault access permissions and key security
I am developing a .NET application that uploads files to Azure Storage. I am leveraging client-side encryption as done in the tutorial at https://azure.microsoft.com/en-us/documentation/articles/storage-encrypt-decrypt-blobs-key-vault/

The application works, i.e. I can successfully upload an encrypted blob to a selected storage account and container.

However, I have some concerns about the security of the RSA key. If the client application gets the key from Key Vault to use in the BlobEncryptionPolicy, that key could get compromised? The only thing the application really needs is the public key of the RSA pair, the private key should remain stored on the server (decrypting only happens by a trusted web app).

The other concern I have is that it is trivial for the AAD integration info to be obtained from the app.config. How does one work around that?

(note: the workstations on which the upload app will run are not necessarily trusted)

答:
All you need is a public key to encrypt a random symmetric key and use that symmetric key to encrypt your data. The server process (Function or similar) has access to the private key used to decrypt the symmetric key, and then decrypt the blob. Access the the private key, held in KV, can be restricted using RBAC policy and applying a managed identity to the process that needs to read the private key.

Finally, the public key really should not be a naked key, it should be in a X.509 cert so you can verify the authenticity of the server end point.


问:
All pipelines failing with error TF400898: An Internal Error Occurred. Activity Id: ca42ac35-7b58-4ac4-9c2e-41d1aa848dce
We are using the SaaS Azure DevOps and this morning all pipelines starting failing with this error

```<code>TF400898: An Internal Error Occurred. Activity Id: ca42ac35-7b58-4ac4-9c2e-41d1aa848dce
</code>```

According to https://status.dev.azure.com/ there are no known outages.  I see a previous question on here that indicated it was a Microsoft issue but nothing so far on their twitter feeds and support pages.

EDIT:

Here's a sample JSON response

```<code>{
"$id":"1",

"innerException":null,
"message":"TF400898: An Internal Error Occurred. Activity Id: e97f2210-35fe-4251-8451-75ed71049e3b.",
"typeName":"System.Data.SqlClient.SqlException, System.Data",
"typeKey":"SqlException",
"errorCode":0,
"eventId":0
}
</code>```

EDIT 2:
Apparently its just the - checkout command!  I ran a simple test of a pipeline with only this:

```<code>trigger: none

pool: some-pool

steps:
- checkout: git://MyAzureDevOpsProject/SomeRepo
</code>```

and it fails.  Can anyone else double check that?

答:
Sorry for the inconvenience, there's one issue about this in DC forum. Some customers also encountered similar issues. We have reported it to product team, you can follow the link above to get notifications if there's any update.

And as a workaround from Richard Gavel:

Try defining the repo in yaml using explicit resource instead of Inline syntax.

Update: Roll out is now completed. Our telemetry shows that the incident has been mitigated.
We apologize for the interruptions caused by this incident.

Body:
We are using the SaaS Azure DevOps and this morning all pipelines starting failing with this error

TF400898: An Internal Error Occurred. Activity Id: ca42ac35-7b58-4ac4-9c2e-41d1aa848dce

According to https://status.dev.azure.com/ there are no known outages.  I see a previous question on here that indicated it was a Microsoft issue but nothing so far on their twitter feeds and support pages.

EDIT:

Here's a sample JSON response

{
"$id":"1",

"innerException":null,
"message":"TF400898: An Internal Error Occurred. Activity Id: e97f2210-35fe-4251-8451-75ed71049e3b.",
"typeName":"System.Data.SqlClient.SqlException, System.Data",
"typeKey":"SqlException",
"errorCode":0,
"eventId":0
}

EDIT 2:
Apparently its just the - checkout command!  I ran a simple test of a pipeline with only this:

trigger: none

pool: some-pool

steps:
- checkout: git://MyAzureDevOpsProject/SomeRepo

and it fails.  Can anyone else double check that?


问:
How to get value of index column in pandas?
I have a pandas data frame like following.

```<code>                  colName
date
2020-06-02 03:00:00 39
</code>```

I can get value of each entry of colName using following. How to get date value?

```<code>for index, row in max_items.iterrows():
        print(str(row['colName]))
        // How to get date??
</code>```

答:
Anti-pattern Warning

First I want to highlight, this is an anti-pattern, using iteration is highly counterproductive.
There are extremely rare cases when you need to iterate through the pandas dataframes. Essentially, Map, Apply and applymap can achieve results efficiently.

Coming to the issue at hand:
you need to convert your index to datetime if not already there.

Simple example:

```<code># Creating the dataframe
df1 = pd.DataFrame({'date':pd.date_range(start='1/1/2018', end='1/03/2018'),
                   'test_value_a':[5, 6, 9],
                   'test_value_b':[2, 5, 1]})

# Coverting date column into index of type datetime.
df1.index = pd.to_datetime(df1.date)

# Dropping date column we had created
df1.drop(labels='date', axis="columns")
</code>```

To print date, month, month name, day or day_name:

```<code>df1.index.date
df1.index.month
df1.index.month
df1.index.month_name
df1.index.day
df1.index.day_name
</code>```

I would suggest read about loc, iloc and ix in the pandas' documentation that should help.
I hope I didn't veer off from the crux of the question.

Body:
I have a pandas data frame like following.

                  colName
date
2020-06-02 03:00:00 39

I can get value of each entry of colName using following. How to get date value?

for index, row in max_items.iterrows():
        print(str(row['colName]))
        // How to get date??

Body:
Anti-pattern Warning

First I want to highlight, this is an anti-pattern, using iteration is highly counterproductive.
There are extremely rare cases when you need to iterate through the pandas dataframes. Essentially, Map, Apply and applymap can achieve results efficiently.

Coming to the issue at hand:
you need to convert your index to datetime if not already there.

Simple example:

# Creating the dataframe
df1 = pd.DataFrame({'date':pd.date_range(start='1/1/2018', end='1/03/2018'),
                   'test_value_a':[5, 6, 9],
                   'test_value_b':[2, 5, 1]})

# Coverting date column into index of type datetime.
df1.index = pd.to_datetime(df1.date)

# Dropping date column we had created
df1.drop(labels='date', axis="columns")

To print date, month, month name, day or day_name:

df1.index.date
df1.index.month
df1.index.month
df1.index.month_name
df1.index.day
df1.index.day_name

I would suggest read about loc, iloc and ix in the pandas' documentation that should help.
I hope I didn't veer off from the crux of the question.


问:
@Order on WebSecurityConfigurers must be unique. Order of 100 was already used on org.engine.security.WebSecurityConfig
I'm trying to run Spring Boot app which connects to remote MySQL server. I get exception during startup time:

```<code>Caused by: java.lang.IllegalStateException: @Order on WebSecurityConfigurers must be unique. Order of 100 was already used on org.engine.security.WebSecurityConfig$$EnhancerBySpringCGLIB$$de8b459d@49e2b3c5, so it cannot be used on org.engine.security.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$e6562c81@5a484ce1 too.
        at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(WebSecurityConfiguration.java:147
</code>```

Full log: https://pastebin.com/xDguJ0Vz

Locally it's working fine. Probably the connect time to MySQL is the issue. Do you know how I can increase the connect time in order to fix this issue?

答:
Wrong Spring Security configurations.

Default WebSecurityConfigurerAdapter's @Order value is 100.
When creating 2 or more WebSecurityConfigurerAdapter implementations, set unique value explicitly.

On your environment, org.engine.security.WebSecurityConfig and org.engine.security.WebSecurityConfiguration are ones.

Body:
I'm trying to run Spring Boot app which connects to remote MySQL server. I get exception during startup time:

Caused by: java.lang.IllegalStateException: @Order on WebSecurityConfigurers must be unique. Order of 100 was already used on org.engine.security.WebSecurityConfig$$EnhancerBySpringCGLIB$$de8b459d@49e2b3c5, so it cannot be used on org.engine.security.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$e6562c81@5a484ce1 too.
        at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(WebSecurityConfiguration.java:147

Full log: https://pastebin.com/xDguJ0Vz

Locally it's working fine. Probably the connect time to MySQL is the issue. Do you know how I can increase the connect time in order to fix this issue?


问:
Uploading and viewing pdf in django
I am making a Webapp using django. In the app, users can login and upload one pdf file. Then others users can visit their profile and view/download the uploaded pdf file. I know how to upload the pdf. But how do I make it viewable and downloadable from the site??</p>

答:
do this in template

```<code><a href={{model_field_name.url}} class= btn btn-primary>download pdf</a>
</code>```

this will create a button link to the pdf file and render it in pdf extension where you can view or download it.

Title: Uploading and viewing pdf in django

Body:
do this in template

<a href={{model_field_name.url}} class= btn btn-primary>download pdf</a>

this will create a button link to the pdf file and render it in pdf extension where you can view or download it.


问:
Stringify dictionary in Swift
I have an Object of type [Dictionary<String: Any>]

```<code>[{
    "addCity" : "Xyz",
    "addLandmark" : "Shopper",
    "addCountry" : "Abc",
    "addPincode" : "122001",
    "isPrimary" : "false",
    "addAddress" : "S44",
    "addState" : "abc",
    "addAddress2" : "Grand Road",
    "addContact" : "11111111",
    "addName" : "John"
}]
</code>```

and want to convert this into this:

```<code>"{\"addAddress\":\"S44\",\"addAddress2\":\"Grand Road\",\"addCity\":\"Xyz\",\"addContact\":\"11111111\",\"addCountry\":\"abc\",\"addLandmark\":\"Shopper\",\"addName\":\" John\",\"addPincode\":\"122002\",\"addState\":\"abc\",\"isPrimary\":true}"
</code>```

means I have to stringify the above values and tried various methods but not reached to any solution.

I have tried this

```<code>do {
    let arrJson = try JSONSerialization.data(withJSONObject: dataAddress, options: JSONSerialization.WritingOptions.prettyPrinted)
    let string = String(data: arrJson, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
    let tempJson = string! as String
    print("%%%%%%",tempJson)
} catch let error as NSError {
    print(error.description)
}
</code>```

but it just returned the same in JSON form.

Please can anyone help me.

答:
Here is a safe/communicative extension:

```<code>extension Dictionary where Key == String, Value == Any {
    var stringified: String? {
        do {
            let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
            guard let stringy = String(data: data, encoding: .utf8) else {
                print("ERROR: failed to cast data as string")
                return nil
            }
            return stringy
        } catch let err {
            print("error with " + #function + ": " + err.localizedDescription)
            return nil
        }
    }
}
</code>```

Here is an alternative that may save you time for Encodable objects.

```<code>extension Encodable {
    var stringified: String? {
        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted
        guard let data = try? encoder.encode(self) else { return nil }
        return String(data: data, encoding: .utf8)
    }
}
</code>```

Title: Stringify dictionary in Swift

Body:
I have an Object of type [Dictionary<String: Any>]

[{
    "addCity" : "Xyz",
    "addLandmark" : "Shopper",
    "addCountry" : "Abc",
    "addPincode" : "122001",
    "isPrimary" : "false",
    "addAddress" : "S44",
    "addState" : "abc",
    "addAddress2" : "Grand Road",
    "addContact" : "11111111",
    "addName" : "John"
}]

and want to convert this into this:

"{\"addAddress\":\"S44\",\"addAddress2\":\"Grand Road\",\"addCity\":\"Xyz\",\"addContact\":\"11111111\",\"addCountry\":\"abc\",\"addLandmark\":\"Shopper\",\"addName\":\" John\",\"addPincode\":\"122002\",\"addState\":\"abc\",\"isPrimary\":true}"

means I have to stringify the above values and tried various methods but not reached to any solution.

I have tried this

do {
    let arrJson = try JSONSerialization.data(withJSONObject: dataAddress, options: JSONSerialization.WritingOptions.prettyPrinted)
    let string = String(data: arrJson, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
    let tempJson = string! as String
    print("%%%%%%",tempJson)
} catch let error as NSError {
    print(error.description)
}

but it just returned the same in JSON form.

Please can anyone help me.

Body:
Here is a safe/communicative extension:

extension Dictionary where Key == String, Value == Any {
    var stringified: String? {
        do {
            let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
            guard let stringy = String(data: data, encoding: .utf8) else {
                print("ERROR: failed to cast data as string")
                return nil
            }
            return stringy
        } catch let err {
            print("error with " + #function + ": " + err.localizedDescription)
            return nil
        }
    }
}

Here is an alternative that may save you time for Encodable objects.

extension Encodable {
    var stringified: String? {
        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted
        guard let data = try? encoder.encode(self) else { return nil }
        return String(data: data, encoding: .utf8)
    }
}


问:
How to using FakeAsync with testWidgets?
I am trying to use FakeAsync from Dart quiver  library to mock the clock of a CountDownTimer.
However, when I await any async function inside the run method, it hangs.

```<code>testWidgets('Resend OTP', (WidgetTester tester) async {
  await FakeAsync().run((async) async {
    final countDownTimer = new CountdownTimer(
      new Duration(seconds: 30),
      new Duration(seconds: 1),
      stopwatch: FakeStopwatch(
          () => async.getClock(DateTime.fromMillisecondsSinceEpoch(0)).now().millisecondsSinceEpoch, 1000),
    );
    print(countDownTimer.remaining);
    print(countDownTimer.isRunning);
    await tester.pumpWidget(Container());

  });
});
</code>```

答:
Found it,
I am going to post it here anyways in case somebody needs the answer in the future:

```<code>testWidgets('Resend OTP Test concept', (WidgetTester tester) async {
    final fakeAsync = FakeAsync();
    fakeAsync.run((async) async {
      final countDownTimer = new CountdownTimer(
        new Duration(seconds: 30),
        new Duration(seconds: 1),
        stopwatch: FakeStopwatch(
            () => async.getClock(DateTime.fromMillisecondsSinceEpoch(0)).now().millisecondsSinceEpoch, 1000),
      );
      print(countDownTimer.remaining);
      print(countDownTimer.isRunning);
      await tester.pumpWidget(Container());
//      expect(true, false);

    });
    fakeAsync.flushMicrotasks();
  });
</code>```

The trick is to create a variable for the FakeAsync then synchronously call  fakeAsync.flushMicrotasks();

Body:
I am trying to use FakeAsync from Dart quiver  library to mock the clock of a CountDownTimer.
However, when I await any async function inside the run method, it hangs.

testWidgets('Resend OTP', (WidgetTester tester) async {
  await FakeAsync().run((async) async {
    final countDownTimer = new CountdownTimer(
      new Duration(seconds: 30),
      new Duration(seconds: 1),
      stopwatch: FakeStopwatch(
          () => async.getClock(DateTime.fromMillisecondsSinceEpoch(0)).now().millisecondsSinceEpoch, 1000),
    );
    print(countDownTimer.remaining);
    print(countDownTimer.isRunning);
    await tester.pumpWidget(Container());

  });
});

Body:
Found it,
I am going to post it here anyways in case somebody needs the answer in the future:

testWidgets('Resend OTP Test concept', (WidgetTester tester) async {
    final fakeAsync = FakeAsync();
    fakeAsync.run((async) async {
      final countDownTimer = new CountdownTimer(
        new Duration(seconds: 30),
        new Duration(seconds: 1),
        stopwatch: FakeStopwatch(
            () => async.getClock(DateTime.fromMillisecondsSinceEpoch(0)).now().millisecondsSinceEpoch, 1000),
      );
      print(countDownTimer.remaining);
      print(countDownTimer.isRunning);
      await tester.pumpWidget(Container());
//      expect(true, false);

    });
    fakeAsync.flushMicrotasks();
  });

The trick is to create a variable for the FakeAsync then synchronously call  fakeAsync.flushMicrotasks();


问:
Using PagedList for paginating product list
I am trying to show a list of products and show pagination. So, I decided to use PagedList plugin. I read some examples of how to modify controller and view to do so in the link below.
https://github.com/TroyGoode/PagedList

But, instead of using ViewBag, I managed to send a group of products to controller by doing some modifications to controller:

```<code>public ActionResult Index(string name)
{
    IEnumerable<ProductModel> productList = new HashSet<ProductModel>();

    if (string.IsNullOrWhiteSpace(name))
    {

    }
    else
    {
        CategoryModel category = db.Categories.Where(x => x.CategorytUrl == name).FirstOrDefault();
        if (category != null)
        {
            int catId = category.Id;
            string catName = category.Name;
            ViewBag.categoryName = category.Name;
            List<SpecItemsModel> options = Products.GetFilter(category.Id);
            //initialize the list
            //productList = Products.ProductLists(catId);
            ViewBag.filters = options;
            var childrenIDs = db.Categories.Where(x => x.ParentId == category.Id).Select(x => x.Id);
            var grandchildrenIDs = db.Categories.Where(x => childrenIDs.Contains((int)x.ParentId)).Select(x => x.Id);
            List<int> catIds = new List<int>();
            catIds.Add(category.Id);
            catIds.AddRange(childrenIDs);
            catIds.AddRange(grandchildrenIDs);

            var templates = db.ProductTemplates.Where(t => catIds.Contains(t.CategoryId)).Select(x => x.Id);
            productList = db.Products.Where(p => templates.Contains(p.ProductTemplateId));
        }
    }
                var pageNumber = page ?? 1;
        //var onePageOfProducts = productList.OrderBy(i => i.AdminRate).ToPagedList(pageNumber, 2);
        //ViewBag.OnePageOfProducts = onePageOfProducts;
        return View(productList.OrderBy(i => i.AdminRate).ToPagedList(pageNumber, 2));
}
</code>```

As the result, products are showing up in he view in 2-product groups. the only thing I don't know is how to modify html pager of the example I mentioned to show paging controls. :

```<code>    @model IEnumerable<fardashahr.Models.ProductModel>

    <div class="col-md-9">

        @foreach (var item in Model)
        {
                    <a href="@Url.Action("Details","Home",new { name = item.ProductUrl })">
                        <img class="bd-placeholder-img card-img-top mw-100" src="/Images/Uploads/Products/@item.Id/Thumbs/@item.ImageName" />
                    </a>
                        <p class="card-text">
                            <h3>
                                @item.ShortName
                            </h3>
                        </p>
        }
    </div>
</div>
</code>```

Any suggestions?

答:
Sorry, I didn't check the github project you posted.

In Controller

Change

```<code>public ActionResult Index(string name)
</code>```

to

```<code>public ActionResult Index(int page, string name)
</code>```

In View

Use

```<code>@Html.PagedListPager( (IPagedList)Model, page => Url.Action("Index", new { page = page, name = "***" }) )
</code>```

to show page navigator.

Body:
I am trying to show a list of products and show pagination. So, I decided to use PagedList plugin. I read some examples of how to modify controller and view to do so in the link below.
https://github.com/TroyGoode/PagedList

But, instead of using ViewBag, I managed to send a group of products to controller by doing some modifications to controller:

public ActionResult Index(string name)
{
    IEnumerable<ProductModel> productList = new HashSet<ProductModel>();

    if (string.IsNullOrWhiteSpace(name))
    {

    }
    else
    {
        CategoryModel category = db.Categories.Where(x => x.CategorytUrl == name).FirstOrDefault();
        if (category != null)
        {
            int catId = category.Id;
            string catName = category.Name;
            ViewBag.categoryName = category.Name;
            List<SpecItemsModel> options = Products.GetFilter(category.Id);
            //initialize the list
            //productList = Products.ProductLists(catId);
            ViewBag.filters = options;
            var childrenIDs = db.Categories.Where(x => x.ParentId == category.Id).Select(x => x.Id);
            var grandchildrenIDs = db.Categories.Where(x => childrenIDs.Contains((int)x.ParentId)).Select(x => x.Id);
            List<int> catIds = new List<int>();
            catIds.Add(category.Id);
            catIds.AddRange(childrenIDs);
            catIds.AddRange(grandchildrenIDs);

            var templates = db.ProductTemplates.Where(t => catIds.Contains(t.CategoryId)).Select(x => x.Id);
            productList = db.Products.Where(p => templates.Contains(p.ProductTemplateId));
        }
    }
                var pageNumber = page ?? 1;
        //var onePageOfProducts = productList.OrderBy(i => i.AdminRate).ToPagedList(pageNumber, 2);
        //ViewBag.OnePageOfProducts = onePageOfProducts;
        return View(productList.OrderBy(i => i.AdminRate).ToPagedList(pageNumber, 2));
}

As the result, products are showing up in he view in 2-product groups. the only thing I don't know is how to modify html pager of the example I mentioned to show paging controls. :

    @model IEnumerable<fardashahr.Models.ProductModel>

        @foreach (var item in Model)
        {

                                @item.ShortName

        }

Any suggestions?

Body:
Sorry, I didn't check the github project you posted.

In Controller

Change

public ActionResult Index(string name)

to

public ActionResult Index(int page, string name)

In View

Use

@Html.PagedListPager( (IPagedList)Model, page => Url.Action("Index", new { page = page, name = "***" }) )

to show page navigator.


问:
Accessing a collection inside of a document in firestore
I have a document, and inside of it there is a collection called relatives. In cloud functions, I have onUpdate() listener for this document. Once something is changed, I want to access that collection inside of my document. Also documents in the collection relatives.

Here is how it looks like:

What I have tried

exports.UpdateLocations = functions.firestore.document("users/{userID}").onUpdate((change, context) => {
    const userEmail = change.after.data().email;
    const prevLocation = change.before.data().userLocation;
    const currentLocation = change.after.data().userLocation;

    if (prevLocation === currentLocation) return 0;

    if (change.after.data().userType.toString() === "Patient") {
        const userLocation = change.after.data().userLocation;
        const relatives = change.after.data().relatives;

        console.log("User's Current Location: " + userLocation);
        console.log("Relatives : "+relatives );

    }
    return;

});

```

I want to access relatives and its documents. So I can search and compare field and update them on purpose.

答:
To get a subcollection from a DocumentSnapshot, you must first get a DocumentReference to the document for that snapshot, and then find the CollectionReference under that.

In code:

```<code>change.after.ref.collection("relatives")
</code>```

In here:

change.after gives you the DocumentSnapshot of the modified document.

change.after.ref then gives you the DocumentReference of that document, so its location in the database.

change.after.ref.collection("relatives") then gives you the CollectionReference to the relatives subcollection of the document.

So get data from these subcollections you'll have to actually load that data, it is not already included in the change object that is passed to your function.

So if you want to load all relatives for the user that triggered the function, it'd be something like:

```<code>let relativesRef = change.after.ref.collection("relatives");
return relatives.get().then((querySnapshot) => {
  querySnapshot.forEach((relativeDoc) => {
    console.log(doc.id, doc.data().relativeaccount);
  });
});
</code>```

Body:
I have a document, and inside of it there is a collection called relatives. In cloud functions, I have onUpdate() listener for this document. Once something is changed, I want to access that collection inside of my document. Also documents in the collection relatives.

Here is how it looks like:

What I have tried

exports.UpdateLocations = functions.firestore.document("users/{userID}").onUpdate((change, context) => {
    const userEmail = change.after.data().email;
    const prevLocation = change.before.data().userLocation;
    const currentLocation = change.after.data().userLocation;

    if (prevLocation === currentLocation) return 0;

    if (change.after.data().userType.toString() === "Patient") {
        const userLocation = change.after.data().userLocation;
        const relatives = change.after.data().relatives;

        console.log("User's Current Location: " + userLocation);
        console.log("Relatives : "+relatives );

    }
    return;

});

I want to access relatives and its documents. So I can search and compare field and update them on purpose.

Body:
To get a subcollection from a DocumentSnapshot, you must first get a DocumentReference to the document for that snapshot, and then find the CollectionReference under that.

In code:

change.after.ref.collection("relatives")

In here:

change.after gives you the DocumentSnapshot of the modified document.

change.after.ref then gives you the DocumentReference of that document, so its location in the database.

change.after.ref.collection("relatives") then gives you the CollectionReference to the relatives subcollection of the document.

So get data from these subcollections you'll have to actually load that data, it is not already included in the change object that is passed to your function.

So if you want to load all relatives for the user that triggered the function, it'd be something like:

let relativesRef = change.after.ref.collection("relatives");
return relatives.get().then((querySnapshot) => {
  querySnapshot.forEach((relativeDoc) => {
    console.log(doc.id, doc.data().relativeaccount);
  });
});


问:
Write to a pointer address in C#
Normally, I can write to a process using this:

```<code>WriteProcessMemory((int)processHandle, 0x01C0FE40, buffer, buffer.Length, ref bytesWritten);
</code>```

But now I have address that looks like this "BlackOps.exe"+0208173C which is also supposed to have an offset of 18. How can I write to the address it points to? Is this even a pointer?

EDIT: The goal is to write a float to the target address. The above pointer points to the games time-scale variable, which will be changeable by the user using the program.

Thanks for any help!

答:
The built in Process and ProcessModule class can give you the base address of the module, then you just add the relative offset, de-reference it using a multi level pointer function called FindDMAAddy(), which uses ReadProcessMemory.  This will yield the address after de-referencing each pointer and adding the appropriate offsets.

Then you just use WriteProcessMemory() on the result.

```<code>public static IntPtr FindDMAAddy(IntPtr hProc, IntPtr ptr, int[] offsets)
{
    var buffer = new byte[IntPtr.Size];
    foreach (int i in offsets)
    {
        ReadProcessMemory(hProc, ptr, buffer, buffer.Length, out var read);

        ptr = (IntPtr.Size == 4)
        ? IntPtr.Add(new IntPtr(BitConverter.ToInt32(buffer, 0)), i)
        : ptr = IntPtr.Add(new IntPtr(BitConverter.ToInt64(buffer, 0)), i);
    }
    return ptr;
}

Process proc = Process.GetProcessesByName("BlackOps")[0];

IntPtr modBaseAddr = proc.MainModule.BaseAddress;

float newTimeScale = 1.0;

IntPtr timeScaleAddr = FindDMAAddy(proc.Handle, modBaseAddr + 0x208173c, new int[] { 0x18 });

WriteProcessMemory(hProc, timeScaleAddr, newTimeScale, 4, out _);
</code>```

Make sure you run as administrator, use pinvoke to get access to native WinAPI functions and check the return values and Marshal.GetLastWin32Error() for error checking if required.

Title: Write to a pointer address in C#

Body:
Normally, I can write to a process using this:

WriteProcessMemory((int)processHandle, 0x01C0FE40, buffer, buffer.Length, ref bytesWritten);

But now I have address that looks like this "BlackOps.exe"+0208173C which is also supposed to have an offset of 18. How can I write to the address it points to? Is this even a pointer?

EDIT: The goal is to write a float to the target address. The above pointer points to the games time-scale variable, which will be changeable by the user using the program.

Thanks for any help!

Body:
The built in Process and ProcessModule class can give you the base address of the module, then you just add the relative offset, de-reference it using a multi level pointer function called FindDMAAddy(), which uses ReadProcessMemory.  This will yield the address after de-referencing each pointer and adding the appropriate offsets.

Then you just use WriteProcessMemory() on the result.

public static IntPtr FindDMAAddy(IntPtr hProc, IntPtr ptr, int[] offsets)
{
    var buffer = new byte[IntPtr.Size];
    foreach (int i in offsets)
    {
        ReadProcessMemory(hProc, ptr, buffer, buffer.Length, out var read);

        ptr = (IntPtr.Size == 4)
        ? IntPtr.Add(new IntPtr(BitConverter.ToInt32(buffer, 0)), i)
        : ptr = IntPtr.Add(new IntPtr(BitConverter.ToInt64(buffer, 0)), i);
    }
    return ptr;
}

Process proc = Process.GetProcessesByName("BlackOps")[0];

IntPtr modBaseAddr = proc.MainModule.BaseAddress;

float newTimeScale = 1.0;

IntPtr timeScaleAddr = FindDMAAddy(proc.Handle, modBaseAddr + 0x208173c, new int[] { 0x18 });

WriteProcessMemory(hProc, timeScaleAddr, newTimeScale, 4, out _);

Make sure you run as administrator, use pinvoke to get access to native WinAPI functions and check the return values and Marshal.GetLastWin32Error() for error checking if required.


问:
How can I use an href link within a "data" attribute - or rewrite it with jQuery?
I'm using the data attribute to show a credit for a photo on a site:

```<code><div id="test" data-credit="name">
</code>```

But how do I do use a link, like this?:

```<code><div id="test" data-credit="<a href="http://mydomain.com">name</a>">
</code>```

Escaping the html, like this, doesn't work:

```<code><a href="http://mydomain.com" >name</a>
</code>```

It that can't be done, how would I use jQuery to rewrite the data-credit "name" into "name" on document ready?

JSfiddle here: http://jsfiddle.net/8muBm/58/

答:
Basically, you are using double quotes inside of double quotes, this invalidates the attribute.  You either have to change the encapsulating quotes to single quotes, or change the quotes inside the attribute value to single quotes.

Here's what I mean:

```<code><div id="test" data-credit="<a href='http://example.com'>name</a>">
</code>```

Here's a simple example you can use to test:

```<code><head>
<!-- Assume jQuery is loaded -->
<script type="text/javascript">
$(document).ready(function() {
    $("#v").val($("#test").attr("data-credit"));
});
</script>

</head>
<body>

<div id="test"
    data-credit="<a href='http://example.com'>name</a>">
<input id="v" type="text" value="" />

</body>
</html>
</code>```

Note that using the escaped html does seem to work.

Body:
I'm using the data attribute to show a credit for a photo on a site:

But how do I do use a link, like this?:

<div id="test" data-credit="name">

Escaping the html, like this, doesn't work:

name

It that can't be done, how would I use jQuery to rewrite the data-credit "name" into "name" on document ready?

JSfiddle here: http://jsfiddle.net/8muBm/58/

Body:
Basically, you are using double quotes inside of double quotes, this invalidates the attribute.  You either have to change the encapsulating quotes to single quotes, or change the quotes inside the attribute value to single quotes.

Here's what I mean:

<div id="test" data-credit="<a href='http://example.com'>name</a>">

Here's a simple example you can use to test:

<head>
<!-- Assume jQuery is loaded -->
<script type="text/javascript">
$(document).ready(function() {
    $("#v").val($("#test").attr("data-credit"));
});
</script>

</head>
<body>

<div id="test"
    data-credit="<a href='http://example.com'>name</a>">
<input id="v" type="text" value="" />

</body>
</html>

Note that using the escaped html does seem to work.