问:
Getting combinations of strings in C#

When I run my code, it asks for an input string and gets the list of similar words with probability for each word token (beautiful and queen).

What I would like to do is get a mixture of the output so that I can get a list of wonderful queen, wounderful princess, lovely queen, lovely empress, etc...

My current code in the main looks like this:

```<code>    while (true)
    {
        Console.Write("Input 1 > ");

        String word1 = Console.ReadLine();
        String[] splitted = word1.Split(' ');

        for(int i = 0; i < splitted.Length; i++)
        {
            foreach (var item in model.NearestWords(splitted[i], 10))
                Console.WriteLine("{0:0.000} {1}", item.Value, item.Key);
        }

        Console.WriteLine();
    }
</code>```

What is a good way to get all possibilities of similar strings of beautiful + similar strings of queen?

答:
Actually, I don't know the structure of your framework, but I can point you out to a solution to get all the possible combinations of adjectives and nouns:

```<code>List<String> adjectives = new List<String> { "Beautiful", "Wonderful", "Lovely" };
List<String> nouns = new List<String> { "Queen", "Princess", "Empress" };

List<String> combinations = adjectives.SelectMany(a => nouns.Select(n => String.Concat(a, " ", n))).ToList();

for (Int32 i = 0; i < combinations.Count; ++i)
    Console.WriteLine(combinations[i]);
</code>```

Output:

```<code>Beautiful Queen
Beautiful Princess
Beautiful Empress
Wonderful Queen
Wonderful Princess
Wonderful Empress
Lovely Queen
Lovely Princess
Lovely Empress
</code>```

In order to obtain the combinations together with the average probability:

```<code>public sealed class Word
{
    public Single Probability { get; private set; }
    public String Text { get; private set; }

    public Word(Single probability, String text)
    {
        Probability = probability;
        Text = text;
    }
}

List<Word> adjectives = new List<Word>
{
    new Word(1.000f, "Beautiful"),
    new Word(0.748f, "Wonderful"),
    new Word(0.732f, "Lovely")
};

List<Word> nouns = new List<Word>
{
    new Word(1.000f, "Queen"),
    new Word(0.767f, "Princess"),
    new Word(0.702f, "Empress")
};

List<Word> words = adjectives
    .SelectMany(
        a =>
        nouns.Select(
            n =>
            new Word(((a.Probability + n.Probability) / 2.0f), String.Concat(a.Text, " ", n.Text))
        )
    )
    .ToList();

for (Int32 i = 0; i < words.Count; ++i)
{
    Word word = words[i];

    Console.WriteLine(word.Probability.ToString("N4") + " - " + word.Text);
}
</code>```

Output:

```<code>1,0000 - Beautiful Queen
0,8835 - Beautiful Princess
0,8510 - Beautiful Empress
0,8740 - Wonderful Queen
0,7575 - Wonderful Princess
0,7250 - Wonderful Empress
0,8660 - Lovely Queen
0,7495 - Lovely Princess
0,7170 - Lovely Empress
</code>```

Title: Getting combinations of strings in C#

Body:
When I run my code, it asks for an input string and gets the list of similar words with probability for each word token (beautiful and queen).

What I would like to do is get a mixture of the output so that I can get a list of wonderful queen, wounderful princess, lovely queen, lovely empress, etc...

My current code in the main looks like this:

    while (true)
    {
        Console.Write("Input 1 > ");

        String word1 = Console.ReadLine();
        String[] splitted = word1.Split(' ');

        for(int i = 0; i < splitted.Length; i++)
        {
            foreach (var item in model.NearestWords(splitted[i], 10))
                Console.WriteLine("{0:0.000} {1}", item.Value, item.Key);
        }

        Console.WriteLine();
    }

What is a good way to get all possibilities of similar strings of beautiful + similar strings of queen?

Body:
Actually, I don't know the structure of your framework, but I can point you out to a solution to get all the possible combinations of adjectives and nouns:

List<String> adjectives = new List<String> { "Beautiful", "Wonderful", "Lovely" };
List<String> nouns = new List<String> { "Queen", "Princess", "Empress" };

List<String> combinations = adjectives.SelectMany(a => nouns.Select(n => String.Concat(a, " ", n))).ToList();

for (Int32 i = 0; i < combinations.Count; ++i)
    Console.WriteLine(combinations[i]);

Output:

Beautiful Queen
Beautiful Princess
Beautiful Empress
Wonderful Queen
Wonderful Princess
Wonderful Empress
Lovely Queen
Lovely Princess
Lovely Empress

In order to obtain the combinations together with the average probability:

public sealed class Word
{
    public Single Probability { get; private set; }
    public String Text { get; private set; }

    public Word(Single probability, String text)
    {
        Probability = probability;
        Text = text;
    }
}

List<Word> adjectives = new List<Word>
{
    new Word(1.000f, "Beautiful"),
    new Word(0.748f, "Wonderful"),
    new Word(0.732f, "Lovely")
};

List<Word> nouns = new List<Word>
{
    new Word(1.000f, "Queen"),
    new Word(0.767f, "Princess"),
    new Word(0.702f, "Empress")
};

List<Word> words = adjectives
    .SelectMany(
        a =>
        nouns.Select(
            n =>
            new Word(((a.Probability + n.Probability) / 2.0f), String.Concat(a.Text, " ", n.Text))
        )
    )
    .ToList();

for (Int32 i = 0; i < words.Count; ++i)
{
    Word word = words[i];

    Console.WriteLine(word.Probability.ToString("N4") + " - " + word.Text);
}

Output:

1,0000 - Beautiful Queen
0,8835 - Beautiful Princess
0,8510 - Beautiful Empress
0,8740 - Wonderful Queen
0,7575 - Wonderful Princess
0,7250 - Wonderful Empress
0,8660 - Lovely Queen
0,7495 - Lovely Princess
0,7170 - Lovely Empress


来源: stackexchange

问:
iOS Swift base64encoding different than PAW app Base64 Encoding
Hoping to get some help with this.  I am trying to post an image to a server and it requires base64 encoding of a PNG file.  When I use the PAW app and encode the image everything shows up on the server beautifully.  When I attempt to do the same with iOS Swift 4, the string produced is similar but also has differences and thus an incorrect image.  Any idea of how to match the string that is correctly created in the PAW app in iOS.  I have included code below along with screenshots of the strings (small samples) created.

Thanks!

```<code>    let image : UIImage = UIImage(named:"STG.png")!
    let imageData = UIImagePNGRepresentation(image)
    var base64String = imageData?.base64EncodedString(options: [])
</code>```

答: Ok went down several rabbit holes and found some folks with similar issues to this.  I eventually solved it by switching over to Alamofire instead of using the native urlsession.  I also found out the server I was posting to would allow for multipart/form-data as well which I ended up using for my request.  I was unable to get that to work using the native urlsession either.</p>

ContentLicense: CC BY-SA 3.0

Body:
Hoping to get some help with this.  I am trying to post an image to a server and it requires base64 encoding of a PNG file.  When I use the PAW app and encode the image everything shows up on the server beautifully.  When I attempt to do the same with iOS Swift 4, the string produced is similar but also has differences and thus an incorrect image.  Any idea of how to match the string that is correctly created in the PAW app in iOS.  I have included code below along with screenshots of the strings (small samples) created.

Thanks!

    let image : UIImage = UIImage(named:"STG.png")!
    let imageData = UIImagePNGRepresentation(image)
    var base64String = imageData?.base64EncodedString(options: [])


问:
Google reCAPTCHA: How many tries of the puzzle does user get?
Got a request with a list of questions from Business to investigate the possibility of integration Google reCaptcha with our Site and one of the questions is:

How many tries of the puzzle does user get?

and the second one:

What happens if the user fails the puzzle as many times as it is allowed to attempt?

I spend a few hours to find the proper answers to the questions above and unfortunately, I didn't get success. No required information on official site, Google Search did not help as well.

答:
Google reCaptchas do not have a default "unsuccessful attempt limit" and I'm not aware of any option set one up.  Captchas are not intended to turn away humans (or hackers), regardless of how many tries it take.

Captchas (an acronym for "Completely Automated Public Turing test to tell Computers and Humans Apart") are unnecessary unless your site is at risk of excessive scraping or automated spam.

Invisible Captcha's seem to be the preferred choice nowadays, to reduce user annoyance with the security feature.

Here are links to:

Google's reCaptcha demo

Google's Invisible reCaptcha demo

FunCaptcha Verification by Puzzle

21 Free CAPTCHA Sources


问:
jQuery time picker
I'm looking to fill a text input with a time that the user can choose in 15 minute intervals. I know there are a few plugins out there. I was wondering if there was any “industry standard” plugin, or strong objective reasons to prefer a particular one in common scenarios.</p>

答: Check out Maxime Haineault's jQuery.timepicker. Pretty cool, IMHO...</p>

OwnerDisplayName: Bernardo

Title: jQuery time picker

ContentLicense: CC BY-SA 2.5


问:
How can I pass parameter for get() when I use generics
```<code>public class Test {

public static void main(String[] args) throws Exception
{
    Generic<Customer> x = new Generic(Customer.class);
    Customer cust = x.get("1");
    System.out.println(cust.getFullname());
}

class Generic<T> {
private Class<T> clazz;

public Generic(Class<T> clazz) {
    this.clazz = clazz;
}

public  Session openSession() {
    Configuration config = new AnnotationConfiguration().configure();
    SessionFactory sf = config.buildSessionFactory();
    Session session = sf.openSession();
    return session;
}

public T get(String id) {
    Session session = openSession();
    T t = (T) session.get(clazz.getClass(), id);
    return t;
}
</code>```

}

When i run this program it dont except my Customer.class(Customer is just an entity class) and throw exception

 org.hibernate.MappingException: Unknown entity: java.lang.Class.Please explain me why

答:
You need to pass an additional Class object of type Class<T>.

Edit: I may be wrong, haven't used Hibernate for too long. Some versions of get() require a Class object.

Either way, look up the definition of Session.get here.

Body:
public class Test {

public static void main(String[] args) throws Exception
{
    Generic<Customer> x = new Generic(Customer.class);
    Customer cust = x.get("1");
    System.out.println(cust.getFullname());
}

class Generic<T> {
private Class<T> clazz;

public Generic(Class<T> clazz) {
    this.clazz = clazz;
}

public  Session openSession() {
    Configuration config = new AnnotationConfiguration().configure();
    SessionFactory sf = config.buildSessionFactory();
    Session session = sf.openSession();
    return session;
}

public T get(String id) {
    Session session = openSession();
    T t = (T) session.get(clazz.getClass(), id);
    return t;
}

}

When i run this program it dont except my Customer.class(Customer is just an entity class) and throw exception

 org.hibernate.MappingException: Unknown entity: java.lang.Class.Please explain me why


问:
Java: Generator of true's & false's combinations by giving the number N;
I tied to simplify the task as much as possible, so I could apply it to my algorithm.

And here is the challenge for mathematicians and programmers:

I need to create a method where I pass parameter int n:

```<code>public void optionality_generator(int n){
  //some kind of loops, or recursions...to make it workable
  System.out.println("current combination: ...");
}
</code>```

The output should show all possible combinations of true's and false's.

Here is examples where N=1; N=2; N=3; N=4; N=5 where x=false and 0=true; Please note, empty break lines is just for you to recognise easier the patterns. Hopefully, I included all possible combinations):

```<code>Combination of 1:
0
x

Combination of 2:
00
x0
0x
xx

Combination of 3:
000
X00
0X0
00X
XX0
0XX
XXX

Combination of 4:
0000

X000
0X00
00X0
000X

XX00
X0X0
X00X

0XX0
0X0X

00XX

XXX0
XX0X
X0XX
0XXX

XXXX

Combination of 5:
00000
X0000
0X000
00X00
000X0
0000X

XX000
X0X00
X00X0
X000X

X0X00
X00X0
X000X

0XX00
0X0X0
0X00X

00XX0
00X0X

000XX

XXX00
XX0X0
XX00X

X0XX0
X0X0X
X00XX

0XXX0
0XX0X

00XXX

XXXX0
XXX0X
XX0XX
X0XXX
0XXXX

XXXXX
</code>```

Also, If you see the output, here is the pattern I recognized, that all combinations are inverted on half (e.g first combination is 00000 last one will be XXXXX, second one X0000, one before the last one will be 0XXXX etc..). Maybe, this pattern will help to make the whole algorithm more efficient, not sure about this.
Thank you in advance!

答:
Here is a modification from Erics code above, that uses c# and allows input of any number of boolean variable names. It will output all possible combinations in c# code ready for insert into an if statement. Just edit the 1st line of code with var names, and then run in LINQpad to get a text output.

Output example...

```<code>!VariableNameA && !VariableNameB && !VariableNameC
!VariableNameA && !VariableNameB &&  VariableNameC
!VariableNameA &&  VariableNameB && !VariableNameC
!VariableNameA &&  VariableNameB &&  VariableNameC
 VariableNameA && !VariableNameB && !VariableNameC
 VariableNameA && !VariableNameB &&  VariableNameC
 VariableNameA &&  VariableNameB && !VariableNameC
 VariableNameA &&  VariableNameB &&  VariableNameC
</code>```

    //To setup edit var names below
    string[] varNames = { "VariableNameA", "VariableNameB", "VariableNameC" };

    int n = varNames.Count();
    for (int i = 0; i < Math.Pow(2, n); i++) {
      String bin = Convert.ToString(i, 2);
      while (bin.Length < n) {
          bin = "0" + bin;
      }
      string and = " && ";
      string f = "!";
      string t = " ";
      var currentNot = bin[0] == '0' ? f : t;
      //string visual = bin[0].ToString();
      string visual = currentNot + varNames[0];
        for (var j = 1; j < n; j++) {
        currentNot = bin[j] == '0' ? f : t;
        //visual = visual + and + bin[j].ToString();
        visual = visual + and + currentNot + varNames[j];
      }
      Console.WriteLine(visual);
    }```

Body:
I tied to simplify the task as much as possible, so I could apply it to my algorithm.

And here is the challenge for mathematicians and programmers:

I need to create a method where I pass parameter int n:

public void optionality_generator(int n){
  //some kind of loops, or recursions...to make it workable
  System.out.println("current combination: ...");
}

The output should show all possible combinations of true's and false's.

Here is examples where N=1; N=2; N=3; N=4; N=5 where x=false and 0=true; Please note, empty break lines is just for you to recognise easier the patterns. Hopefully, I included all possible combinations):

Combination of 1:
0
x

Combination of 2:
00
x0
0x
xx

Combination of 3:
000
X00
0X0
00X
XX0
0XX
XXX

Combination of 4:
0000

X000
0X00
00X0
000X

XX00
X0X0
X00X

0XX0
0X0X

00XX

XXX0
XX0X
X0XX
0XXX

XXXX

Combination of 5:
00000
X0000
0X000
00X00
000X0
0000X

XX000
X0X00
X00X0
X000X

X0X00
X00X0
X000X

0XX00
0X0X0
0X00X

00XX0
00X0X

000XX

XXX00
XX0X0
XX00X

X0XX0
X0X0X
X00XX

0XXX0
0XX0X

00XXX

XXXX0
XXX0X
XX0XX
X0XXX
0XXXX

XXXXX

Also, If you see the output, here is the pattern I recognized, that all combinations are inverted on half (e.g first combination is 00000 last one will be XXXXX, second one X0000, one before the last one will be 0XXXX etc..). Maybe, this pattern will help to make the whole algorithm more efficient, not sure about this.
Thank you in advance!

Body:
Here is a modification from Erics code above, that uses c# and allows input of any number of boolean variable names. It will output all possible combinations in c# code ready for insert into an if statement. Just edit the 1st line of code with var names, and then run in LINQpad to get a text output.

Output example...

!VariableNameA && !VariableNameB && !VariableNameC
!VariableNameA && !VariableNameB &&  VariableNameC
!VariableNameA &&  VariableNameB && !VariableNameC
!VariableNameA &&  VariableNameB &&  VariableNameC
 VariableNameA && !VariableNameB && !VariableNameC
 VariableNameA && !VariableNameB &&  VariableNameC
 VariableNameA &&  VariableNameB && !VariableNameC
 VariableNameA &&  VariableNameB &&  VariableNameC

    //To setup edit var names below
    string[] varNames = { "VariableNameA", "VariableNameB", "VariableNameC" };

    int n = varNames.Count();
    for (int i = 0; i < Math.Pow(2, n); i++) {
      String bin = Convert.ToString(i, 2);
      while (bin.Length < n) {
          bin = "0" + bin;
      }
      string and = " && ";
      string f = "!";
      string t = " ";
      var currentNot = bin[0] == '0' ? f : t;
      //string visual = bin[0].ToString();
      string visual = currentNot + varNames[0];
        for (var j = 1; j < n; j++) {
        currentNot = bin[j] == '0' ? f : t;
        //visual = visual + and + bin[j].ToString();
        visual = visual + and + currentNot + varNames[j];
      }
      Console.WriteLine(visual);
    }


问:
iOS 11 large navigation bar title unexpected velocity
I am trying to implement the iOS 11 native large navigation bar title on my new application.  By calling below functions in viewDidLoad():

navigationController?.navigationBar.prefersLargeTitles = true navigationController?.navigationItem.largeTitleDisplayMode = .always

I do get what I desired.

But, when I start scrolling up (the only view inside the main view is a scroll view), the scrolling makes the large title disappear at a faster velocity than actual scroll with the finger.  (that is, if I move 2cm on screen, the scroll view actually scrolls more than 2cm, up until the large title shrinks to the 'usual' size.)

The below is the gif of my app being scrolled.  I actually move very little, and it automatically scrolls up that much.  This differs from the Apple-made applications (the app store for instance, shown below my app).

Does anyone have solution to solving this abnormal behaviour?

EDIT:
Per request, I am adding the current View hierarchy.  There isn't anything special in my code, I just set the title and flag for prefersLargeTitles.

答:
I have been debugging this for a couple days, and I have found a workaround.

First, What Was Going On?

It is the UIScrollView that is not performing well with the largeTitle.  Since there is scrolling up on the scroll view at the same time as the navigation bar becoming smaller, there exists twice the scrolling compared to the actual scroll.

I confirmed this by intentionally setting:

```<code>scrollView.contentOffset.y = scrollView.contentOffset.y * 0.5
</code>```

This indeed made it move as desired.  But, this couldn't solve the problem entire problem because it did not yield a smooth transition while going from large navigation bar to small navigation bar.  You can try the below code out.

```<code>if scrollView.contentOffset.y > 0 {
  if self.navigationController!.navigationBar.frame.size.height > 44.0 {
    scrollView.contentOffset.y = scrollView.contentOffset.y * 0.5
  }
}
</code>```

This worked 'okay' when scrolled slowly, but when you fling downward, it acts slow at first (while navigation height is large), and then speeds up afterwards.

WORKAROUND

Simply put, you CANNOT use UIScrollView with the iOS 11 large navigation bar.  You ought to use UITableViewController instead.

Since my view is composed of multiple horizontal UICollectionViews spread along vertically, I used UITableView with different sections to form the UI using storyboard.
If you use UITableViewController, it performs as desired.

AppStore and all other Apple-made native apps must do it this way.

Body:
I have been debugging this for a couple days, and I have found a workaround.

First, What Was Going On?

It is the UIScrollView that is not performing well with the largeTitle.  Since there is scrolling up on the scroll view at the same time as the navigation bar becoming smaller, there exists twice the scrolling compared to the actual scroll.

I confirmed this by intentionally setting:

scrollView.contentOffset.y = scrollView.contentOffset.y * 0.5

This indeed made it move as desired.  But, this couldn't solve the problem entire problem because it did not yield a smooth transition while going from large navigation bar to small navigation bar.  You can try the below code out.

if scrollView.contentOffset.y > 0 {
  if self.navigationController!.navigationBar.frame.size.height > 44.0 {
    scrollView.contentOffset.y = scrollView.contentOffset.y * 0.5
  }
}

This worked 'okay' when scrolled slowly, but when you fling downward, it acts slow at first (while navigation height is large), and then speeds up afterwards.

WORKAROUND

Simply put, you CANNOT use UIScrollView with the iOS 11 large navigation bar.  You ought to use UITableViewController instead.

Since my view is composed of multiple horizontal UICollectionViews spread along vertically, I used UITableView with different sections to form the UI using storyboard.
If you use UITableViewController, it performs as desired.

AppStore and all other Apple-made native apps must do it this way.

ContentLicense: CC BY-SA 4.0


问:
Rendering List with Fetch in React
Trying to render a list of movies from a random API and eventually filter them.

```<code>componentDidMount() {
    var myRequest = new Request(website);
    let movies = [];

    fetch(myRequest)
        .then(function(response) { return response.json(); })
        .then(function(data) {
            data.forEach(movie =>{
                movies.push(movie.title);
            })
        });
     this.setState({movies: movies});
}

render() {
    console.log(this.state.movies);
    console.log(this.state.movies.length);
    return (
        <h1>Movie List</h1>
    )
}
</code>```

If I render this I can only print my state and not access what is inside.
How would I create a list of LIs and render a UL?
Thanks

答:
A few things. fetch is asynchronous, so you're essentially just going to be setting movies to an empty array as this is written. If data is an array of movies, you can just set that directly in your state rather than copying it to a new array first. Finally, using an arrow function for the final callback in the promise will allow you to use this.setState without having to explicitly bind the function.

Finally, you can use JSX curly brace syntax to map over the movies in your state object, and render them as items in a list.

```<code>class MyComponent extends React.Component {
  constructor() {
    super()
    this.state = { movies: [] }
  }

  componentDidMount() {
    var myRequest = new Request(website);
    let movies = [];

    fetch(myRequest)
      .then(response => response.json())
      .then(data => {
        this.setState({ movies: data })
      })
  }

  render() {
    return (
      <div>
        <h1>Movie List</h1>
        <ul>
          {this.state.movies.map(movie => {
            return <li key={`movie-${movie.id}`}>{movie.name}</li>
          })}
        </ul>
      </div>
    )
  }
}
</code>```

Title: Rendering List with Fetch in React

Body:
Trying to render a list of movies from a random API and eventually filter them.

componentDidMount() {
    var myRequest = new Request(website);
    let movies = [];

    fetch(myRequest)
        .then(function(response) { return response.json(); })
        .then(function(data) {
            data.forEach(movie =>{
                movies.push(movie.title);
            })
        });
     this.setState({movies: movies});
}

render() {
    console.log(this.state.movies);
    console.log(this.state.movies.length);
    return (

Movie List

    )
}

If I render this I can only print my state and not access what is inside.
How would I create a list of LIs and render a UL?
Thanks

Body:
A few things. fetch is asynchronous, so you're essentially just going to be setting movies to an empty array as this is written. If data is an array of movies, you can just set that directly in your state rather than copying it to a new array first. Finally, using an arrow function for the final callback in the promise will allow you to use this.setState without having to explicitly bind the function.

Finally, you can use JSX curly brace syntax to map over the movies in your state object, and render them as items in a list.

class MyComponent extends React.Component {
  constructor() {
    super()
    this.state = { movies: [] }
  }

  componentDidMount() {
    var myRequest = new Request(website);
    let movies = [];

    fetch(myRequest)
      .then(response => response.json())
      .then(data => {
        this.setState({ movies: data })
      })
  }

  render() {
    return (
      <div>
        <h1>Movie List</h1>
        <ul>
          {this.state.movies.map(movie => {
            return <li key={`movie-${movie.id}`}>{movie.name}</li>
          })}
        </ul>
      </div>
    )
  }
}


问:
Azure webjobs suddenly stopped working
From one day to the other, my manually triggered Azure webjobs does not work anymore. I am trying to trigger them using the "Run" button in the Azure portal.

My WebJob does not do anything "fancy", they just read from an Azure blob queue, do some processing and uploads a csv file afterwards.

The error message I am seeing in the Azure portal is:

```<code>"Failed to run [JOBNAME].: "No route registered for '/api/triggeredwebjobs/[JOBNAME]/history?api-version=2016-03-01'"
</code>```

If I check the browser console I can see an http 404 error, when a http POST is being made to the following endpoint:

https://web1.appsvcux.ext.azure.com/websites/api/Websites/RunWebJob

If I click that link, I am shown an 401.1 error page with the following text:

```<code>Access is denied.

Description: An error occurred while accessing the resources required to serve this request. This may have been caused by an incorrect user name and/or password.
</code>```

Error message 401.1: Logon credentials were not recognized. Make sure you are providing the correct user name and password. Otherwise, contact the Web server's administrator for help.

I have not made any changes in the Azure portal or to the webjob code since long ago (> month ago).
I even tried to setup a completely new Azure webjob, but I get the same error message.

Any help is much appreciated!

答:
This was caused by an Azure issue that caused WebJobs invocations from the worker to fail with that error.

The issue has now been resolved, and you will no longer encounter this. See this page for related info.

Apologies for the inconvenience.

Title: Azure webjobs suddenly stopped working

Body:
From one day to the other, my manually triggered Azure webjobs does not work anymore. I am trying to trigger them using the "Run" button in the Azure portal.

My WebJob does not do anything "fancy", they just read from an Azure blob queue, do some processing and uploads a csv file afterwards.

The error message I am seeing in the Azure portal is:

"Failed to run [JOBNAME].: "No route registered for '/api/triggeredwebjobs/[JOBNAME]/history?api-version=2016-03-01'"

If I check the browser console I can see an http 404 error, when a http POST is being made to the following endpoint:

https://web1.appsvcux.ext.azure.com/websites/api/Websites/RunWebJob

If I click that link, I am shown an 401.1 error page with the following text:

Access is denied.

Description: An error occurred while accessing the resources required to serve this request. This may have been caused by an incorrect user name and/or password.

Error message 401.1: Logon credentials were not recognized. Make sure you are providing the correct user name and password. Otherwise, contact the Web server's administrator for help.

I have not made any changes in the Azure portal or to the webjob code since long ago (> month ago).
I even tried to setup a completely new Azure webjob, but I get the same error message.

Any help is much appreciated!


问:
Find all available wireless networks in range, using Java
I want to list all the wireless networks in range using Java. The application needs to be platform-independent, i.e., it should work on both Windows and Linux. I found answers listing different methods for different operating systems for the same. Is there a way in which this can be done directly in Java regardless of the operating system being used?</p>

答: For Windows, you can use jWlanScan. However, you may need to implement your own JNI wrapper for OSes. </p>


问:
Angular CLI project load component as base URL
I have a Angular CLI project that i built with multiple components and uploaded via FileZilla to my school domain. I want it so that on load of the application it redirects to the HomeComponent instead of AppComponent. What can i do to accomplish this?</p>

答:
In your router set the default route to your home component URL.</p>

```<code>const appRoutes: Routes = [
  { path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  },
  { path: 'home', component: HomeComponent },
];
</code>```

Body:
In your router set the default route to your home component URL.

const appRoutes: Routes = [
  { path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  },
  { path: 'home', component: HomeComponent },
];


问:
Return Column Based on Another Specific Value
I'm trying to show which products our company offers have been purchased by a certain point in time. I would like to show each product's name and then a simple Y or N next to each product indicating if it was sold by a certain date. I'm not sure how to structure the query - this is my attempt

```<code>SELECT product_offering as Product
CASE WHEN date_key='2017-03-30' THEN product_sold ELSE product_sold END as Sold
FROM table1
</code>```

It should look like, if, as a shortened example

1st product sold 2017-03-27

2nd product sold 2017-04-03

3rd product sold 2017-3-28

```<code>|Product | Sold |
|1st Prod|   Y  |
|2nd Prod|   N  |
|3rd Prod|   Y  |
</code>```

Instead, the "Sold" column isn't entirely accurate. I think this has something to do with the date being equal to a certain date instead of a range leading up to, but i'm not sure how to fix this.

答:
If I understand correctly, you want something like this:</p>

```<code>SELECT product_offering as Product,
       (CASE WHEN MIN(date_key) <= '2017-03-30' THEN 'Y' ELSE 'N' END) as Sold
FROM table1
GROUP BY table1
</code>```

Body:
I'm trying to show which products our company offers have been purchased by a certain point in time. I would like to show each product's name and then a simple Y or N next to each product indicating if it was sold by a certain date. I'm not sure how to structure the query - this is my attempt

SELECT product_offering as Product
CASE WHEN date_key='2017-03-30' THEN product_sold ELSE product_sold END as Sold
FROM table1

It should look like, if, as a shortened example

1st product sold 2017-03-27

2nd product sold 2017-04-03

3rd product sold 2017-3-28

|Product | Sold |
|1st Prod|   Y  |
|2nd Prod|   N  |
|3rd Prod|   Y  |

Instead, the "Sold" column isn't entirely accurate. I think this has something to do with the date being equal to a certain date instead of a range leading up to, but i'm not sure how to fix this.

Body:
If I understand correctly, you want something like this:

SELECT product_offering as Product,
       (CASE WHEN MIN(date_key) <= '2017-03-30' THEN 'Y' ELSE 'N' END) as Sold
FROM table1
GROUP BY table1


问:
How do I programmatically restore an Apex 5 report to default state?
I have an Interactive report in Apex 5, and each time the page load, I want it to look exactly as it was shown the first time I ran it, with default settings.

The problem is that if the user applies any filter, or hide columns, the next time the page loads, the report remembers that configuration.

I tried to use the APEX_IR.RESET_REPORT procedure undocumented here:

https://docs.oracle.com/database/121/AEAPI/apex_ir.htm#BABEJAFB

but it either doesn't works, or only undoes the last change, or needs many runs to actually work.

I tried a dynamic action at page load with this code:

```<code>DECLARE
  v_region_id APEX_APPLICATION_PAGE_REGIONS.REGION_ID%TYPE;
BEGIN

  SELECT region_id INTO v_region_id
  FROM APEX_APPLICATION_PAGE_REGIONS
  WHERE application_id = :APP_ID
  AND page_id = :APP_PAGE_ID
  AND static_id = 'Images_Report';

   APEX_IR.RESET_REPORT(
       P_page_id => :APP_PAGE_ID,
       P_region_id => v_region_id,
       p_report_id => null

  );

END;
</code>```

And I also tried this code

```<code>DECLARE
  v_region_id APEX_APPLICATION_PAGE_REGIONS.REGION_ID%TYPE;
BEGIN

  SELECT region_id INTO v_region_id
  FROM APEX_APPLICATION_PAGE_REGIONS
  WHERE application_id = :APP_ID
  AND page_id = :APP_PAGE_ID
  AND static_id = 'Images_Report';

   APEX_IR.RESET_REPORT(
       P_page_id => :APP_PAGE_ID,
       P_region_id => v_region_id,
       p_report_id => APEX_IR.GET_LAST_VIEWED_REPORT_ID(
                        p_page_id   => :APP_PAGE_ID,
                        p_region_id => v_region_id
                       )

  );

END;
</code>```

I expect the report to look as in default state (on first run), every time I load the page.

Instead the report shows the last state, even if the user logs out, logs in and restarts the application.

答:
Send RIR as the clear cache parameter in your URL

https://docs.oracle.com/database/apex-5.1/HTMDB/linking-to-interactive-reports.htm#GUID-B917CEB3-A0B9-414B-A90A-7B44DD15EA67

URL would look like

```<code>f?p=102:94:6722612001859::NO:RIR::
</code>```

https://docs.oracle.com/database/apex-5.1/HTMDB/understanding-url-syntax.htm#HTMDB03019

The documentation states this regarding the apex_ir.reset_report procedure

This procedure should only be used in page submit processes.

Which could be why you had trouble

Body:
I have an Interactive report in Apex 5, and each time the page load, I want it to look exactly as it was shown the first time I ran it, with default settings.

The problem is that if the user applies any filter, or hide columns, the next time the page loads, the report remembers that configuration.

I tried to use the APEX_IR.RESET_REPORT procedure undocumented here:

https://docs.oracle.com/database/121/AEAPI/apex_ir.htm#BABEJAFB

but it either doesn't works, or only undoes the last change, or needs many runs to actually work.

I tried a dynamic action at page load with this code:

DECLARE
  v_region_id APEX_APPLICATION_PAGE_REGIONS.REGION_ID%TYPE;
BEGIN

  SELECT region_id INTO v_region_id
  FROM APEX_APPLICATION_PAGE_REGIONS
  WHERE application_id = :APP_ID
  AND page_id = :APP_PAGE_ID
  AND static_id = 'Images_Report';

   APEX_IR.RESET_REPORT(
       P_page_id => :APP_PAGE_ID,
       P_region_id => v_region_id,
       p_report_id => null

  );

END;

And I also tried this code

DECLARE
  v_region_id APEX_APPLICATION_PAGE_REGIONS.REGION_ID%TYPE;
BEGIN

  SELECT region_id INTO v_region_id
  FROM APEX_APPLICATION_PAGE_REGIONS
  WHERE application_id = :APP_ID
  AND page_id = :APP_PAGE_ID
  AND static_id = 'Images_Report';

   APEX_IR.RESET_REPORT(
       P_page_id => :APP_PAGE_ID,
       P_region_id => v_region_id,
       p_report_id => APEX_IR.GET_LAST_VIEWED_REPORT_ID(
                        p_page_id   => :APP_PAGE_ID,
                        p_region_id => v_region_id
                       )

  );

END;

I expect the report to look as in default state (on first run), every time I load the page.

Instead the report shows the last state, even if the user logs out, logs in and restarts the application.

Body:
Send RIR as the clear cache parameter in your URL

https://docs.oracle.com/database/apex-5.1/HTMDB/linking-to-interactive-reports.htm#GUID-B917CEB3-A0B9-414B-A90A-7B44DD15EA67

URL would look like

f?p=102:94:6722612001859::NO:RIR::

https://docs.oracle.com/database/apex-5.1/HTMDB/understanding-url-syntax.htm#HTMDB03019

The documentation states this regarding the apex_ir.reset_report procedure

This procedure should only be used in page submit processes.

Which could be why you had trouble


答:
Gotten your movies in state you can do the next to render the list of movies:</p>

```<code>render() {
  return (
    <h1>Movie List</h1>
    <ul>
      {
        this.state.movies.map((movie) =>
          <li key={movie}>movie</li>
        )
      }
    </ul>
  );
}
</code>```

Title: Rendering List with Fetch in React

Body:
Gotten your movies in state you can do the next to render the list of movies:

render() {
  return (
    <h1>Movie List</h1>
    <ul>
      {
        this.state.movies.map((movie) =>
          <li key={movie}>movie</li>
        )
      }
    </ul>
  );
}


问:
How to pass the data with AJAX to Controller in Laravel?
I am really stuck with AJAX request/response in Laravel and would be glad if someone could help me.

This is my JS Ajax:

```<code>$('#manufacturer_id').change(function(){
  var manuf_id = $(this).val();
  console.log("1:"+manuf_id);

  var dataString = '{manufacturer_id:'+ manuf_id+'}';
  console.log("2:"+dataString);

  // Ajax
  $.ajax({
    url: "/laravel/public/posts/create",
    type: 'GET',
    data: dataString,
    cache: false,
    success: function(data) {
      console.log(dataString);
    },
  });
});
</code>```

And this is the PostsController, where I need to change just one ID:

```<code>public function create(Request $manuf_id)
    {
        $title = 'Add post';

        $categories = Category::all();
        $manufacturers = Manufacturer::all();
        $fuels = Fuel::all();

        $sendedID = \Response::json($manuf_id);
        $cars = Car::where('manufacturer_id', $sendedID)->get();

        return view('posts.create',
            compact(
                'title',
                'categories',
                'fuels',
                'cars',
                'manufacturers'
            )
        );
    }
</code>```

What I really want to achieve: When user select manufacturer from select box in my form, the ID of manufacturer will change the ID which is written here:

```<code>$cars = Car::where('manufacturer_id', $sendedID)->get();
</code>```

Basically when I hardcode the number (ID) instead of variable $sendedID, I get everything I need (I already have releationships between the tables in my database).

All I need to do is to send the value (onchange) of manufacturer and pass it to variable $sendedID in my PostsController. I probably need to change the code in my PostController, just don't know how and I've already researched a lot, but could not find the answer. Thank anybody who has an idea how to repair this.

答:
As far as i understand your question, this is what you need:

There is a dropdown of all your manufacturers. When a user selects one, options for cars will also change.

If you want to achieve this through ajax, you have to create a separate method to return all cars of a specific manufacturer. Let's say

```<code>public function getCars(Request $request) {
    $cars = Car::where("manufacturer_id", $request->get("manufacturer_id"))->get();
    return response()->json($cars);
}
</code>```

Then your ajax method should be able to retrieve this data

```<code>$('#manufacturer_id').change(function() {
    $.ajax({
        url: GET_CARS_URL,
        type: 'GET',
        data: { manufacturer_id: $(this).val() },
        cache: false,
        success: function(data) {
           console.log(data);
        },
    });
});
</code>```

Body:
I am really stuck with AJAX request/response in Laravel and would be glad if someone could help me.

This is my JS Ajax:

$('#manufacturer_id').change(function(){
  var manuf_id = $(this).val();
  console.log("1:"+manuf_id);

  var dataString = '{manufacturer_id:'+ manuf_id+'}';
  console.log("2:"+dataString);

  // Ajax
  $.ajax({
    url: "/laravel/public/posts/create",
    type: 'GET',
    data: dataString,
    cache: false,
    success: function(data) {
      console.log(dataString);
    },
  });
});

And this is the PostsController, where I need to change just one ID:

public function create(Request $manuf_id)
    {
        $title = 'Add post';

        $categories = Category::all();
        $manufacturers = Manufacturer::all();
        $fuels = Fuel::all();

        $sendedID = \Response::json($manuf_id);
        $cars = Car::where('manufacturer_id', $sendedID)->get();

        return view('posts.create',
            compact(
                'title',
                'categories',
                'fuels',
                'cars',
                'manufacturers'
            )
        );
    }

What I really want to achieve: When user select manufacturer from select box in my form, the ID of manufacturer will change the ID which is written here:

$cars = Car::where('manufacturer_id', $sendedID)->get();

Basically when I hardcode the number (ID) instead of variable $sendedID, I get everything I need (I already have releationships between the tables in my database).

All I need to do is to send the value (onchange) of manufacturer and pass it to variable $sendedID in my PostsController. I probably need to change the code in my PostController, just don't know how and I've already researched a lot, but could not find the answer. Thank anybody who has an idea how to repair this.

Body:
As far as i understand your question, this is what you need:

There is a dropdown of all your manufacturers. When a user selects one, options for cars will also change.

If you want to achieve this through ajax, you have to create a separate method to return all cars of a specific manufacturer. Let's say

public function getCars(Request $request) {
    $cars = Car::where("manufacturer_id", $request->get("manufacturer_id"))->get();
    return response()->json($cars);
}

Then your ajax method should be able to retrieve this data

$('#manufacturer_id').change(function() {
    $.ajax({
        url: GET_CARS_URL,
        type: 'GET',
        data: { manufacturer_id: $(this).val() },
        cache: false,
        success: function(data) {
           console.log(data);
        },
    });
});


问:
Changing java file
Can I change a java file, when I'm running it on JVM, using this file?

For example:
I run abc.java. In this program I've a textarea and I want to paste text from the text area into abc.java and save the changes. Is it possible?

答:
3 steps:

modify your .java file just like you would modify a text file.

compile that .java file from within your already running JVM using javax.tools compilation tools

Instantiate your freshly compiled class using the ClassLoader.

Title: Changing java file


问:
Extra tabstop on VSCode snippet with choices
I have a snippet that stops an "extra" time. it's been annoying me, so I'm hoping someone can help me clear it up here.

```<code>"pylint": {
    "prefix": "pylint",
    "body": "# pylint: ${1|disable,enable|}=${2|R0102\\, simplifiable-if-statement,R0101\\,too-many-nested-blocks|}",
    "description": "Add a pylint comment"
},
</code>```

For some reason it stops on [disable, enable], then on = ?!, and then again (appropriately) on [R0102, simplifiable-if-statement, R0101, too-many-nested-blocks]. why is it stopping on the equals sign?

答:
According to a maintainer of the project, this is "as-designed".

Choice elements are treated as regular (nested) snippets and we always jump to the end of snippet when it's "finished". That's why the cursor stops there. Unlikely that we will change this behaviour. Closing as designed

So, I tested it with this snippet:

```<code>"dummy": {
    "prefix": "dummy",
    "body": "# dummy: ${1|this,that|} - ${2|is,was|} - ${3|good,bad|}",
    "description": "a dummy snippet",
},
</code>```

and indeed, it appears that tabstops stop before and after choice elements.

Body:
I have a snippet that stops an "extra" time. it's been annoying me, so I'm hoping someone can help me clear it up here.

"pylint": {
    "prefix": "pylint",
    "body": "# pylint: ${1|disable,enable|}=${2|R0102\\, simplifiable-if-statement,R0101\\,too-many-nested-blocks|}",
    "description": "Add a pylint comment"
},

For some reason it stops on [disable, enable], then on = ?!, and then again (appropriately) on [R0102, simplifiable-if-statement, R0101, too-many-nested-blocks]. why is it stopping on the equals sign?

Body:
According to a maintainer of the project, this is "as-designed".

Choice elements are treated as regular (nested) snippets and we always jump to the end of snippet when it's "finished". That's why the cursor stops there. Unlikely that we will change this behaviour. Closing as designed

So, I tested it with this snippet:

"dummy": {
    "prefix": "dummy",
    "body": "# dummy: ${1|this,that|} - ${2|is,was|} - ${3|good,bad|}",
    "description": "a dummy snippet",
},

and indeed, it appears that tabstops stop before and after choice elements.


问:
How to set a value to void * argument of a mock method in google mock testing?
I want to pass a string "Device Name" to a void * pointer argument of a method and retrieve it to a character array later.

For this I've done as shown below.

Here I have created an action to achieve this.

```<code>ACTION_P(SetArg2ToChar, value) {*static_cast<char*>(arg2) = *value; }
</code>```

Actual method to be called/mocked

```<code>bool getDictItem(WORD wIndex, BYTE bSubIndex, void * pObjData, DWORD dwLength, CSdo& sdo)
</code>```

My mock method

```<code>  MOCK_METHOD5(getDictItem,
  bool(WORD wIndex, BYTE bSubIndex, void * pObjData, DWORD dwLength, CSdo& sdo));
</code>```

in code it is called as

```<code>if( !can.getDictItem(wIndex, bSubIndex, pObjData, dwLength, tSdo) )
</code>```

I want to pass a string to this pObjData (3rd argument in the list).

In my google tests, I'm doing like this.

```<code>char szDeviceName[30]= {0};
snprintf(szDeviceName, sizeof(szDeviceName), "%s", "Device Name" );

EXPECT_CALL( mockCan, getDictItem(_,_,_,_,_) )
            .WillOnce(DoAll(SetArg2ToChar(szDeviceName),
            Return(true)))
            .RetiresOnSaturation();

/*    Call a real method within which this mock method is called */
</code>```

If I try to set this argument(pObjData) using "SetArgPointee<2>" directly, I get the below error.

error: 'void' is not a pointer-to-object type*

Hence I'm trying with ACTION_P

Now with this implementation, I only get the first letter of the szDeviceName variable (into this pObjData) i.e., "D" followed by 29 0's in the real code flow after this mock object is called.

I want to get the full string name set into this void * arguement.

I refered to this below question and was able progress this far. But I'm not able to pass the full string. How to set, in google mock, a void* argument to a set of values?

Any information regarding this will be helpful.

答:
I recently had a similar need and came up with this as a generic solution.  It's based on the built-in SetArgPointee and has the same syntax:

```<code>template <size_t N, typename A>
class SetArgumentPointeeVoidAction {
public:
    explicit SetArgumentPointeeVoidAction(const A& value) : value_(value) {}
    void operator=(SetArgumentPointeeVoidAction const&) = delete;

    template <typename Result, typename ArgumentTuple>
    void Perform(const ArgumentTuple& args) const
    {
        ::testing::StaticAssertTypeEq<void, Result>();
        ::testing::StaticAssertTypeEq<void*,
            std::decay<decltype(::testing::get<N>(args))>::type>();
        *static_cast<A*>(::testing::get<N>(args)) = value_;
    }

private:
    const A value_;
};

/**
 * \brief  Sets a \c void* output argument to the contents of the
 *         supplied object.  It's on you to ensure this is safe.
 * \tparam N The argument index.
 * \tparam T The real argument type.
 * \param  x The argument to assign to the output argument.
 * \return A GMock Action that performs the requested assignment.
 * \note   Use \c SetArgPointee when it's not a \c void*.
 */
template <size_t N, typename T>
::testing::PolymorphicAction< SetArgumentPointeeVoidAction<N, T> >
SetArgPointeeVoid(const T& x)
{
    return ::testing::MakePolymorphicAction(
        SetArgumentPointeeVoidAction<N, T>(x));
}
</code>```

It will give you a compile error if you try to use this on an argument that isn't a void*, so it should be relatively safe as long as you ensure you supply the correct argument.

It's also possible to implement this using ACTION_TEMPLATE, which is a bit shorter, but it generates unused argument warnings, which can be irritating.

(In older versions of GMock you might have to use ::std::tr1::get instead of ::testing::get.)

Left as an exercise for the reader: it's possible to enhance this with perfect forwarding to allow this to move-construct and move-assign for a slight efficiency boost.  Although if you're passing anything other than PODs around as void*s then you're probably doing it wrong.

Body:
I want to pass a string "Device Name" to a void * pointer argument of a method and retrieve it to a character array later.

For this I've done as shown below.

Here I have created an action to achieve this.

ACTION_P(SetArg2ToChar, value) {*static_cast<char*>(arg2) = *value; }

Actual method to be called/mocked

bool getDictItem(WORD wIndex, BYTE bSubIndex, void * pObjData, DWORD dwLength, CSdo& sdo)

My mock method

  MOCK_METHOD5(getDictItem,
  bool(WORD wIndex, BYTE bSubIndex, void * pObjData, DWORD dwLength, CSdo& sdo));

in code it is called as

if( !can.getDictItem(wIndex, bSubIndex, pObjData, dwLength, tSdo) )

I want to pass a string to this pObjData (3rd argument in the list).

In my google tests, I'm doing like this.

char szDeviceName[30]= {0};
snprintf(szDeviceName, sizeof(szDeviceName), "%s", "Device Name" );

EXPECT_CALL( mockCan, getDictItem(_,_,_,_,_) )
            .WillOnce(DoAll(SetArg2ToChar(szDeviceName),
            Return(true)))
            .RetiresOnSaturation();

/*    Call a real method within which this mock method is called */

If I try to set this argument(pObjData) using "SetArgPointee<2>" directly, I get the below error.

error: 'void' is not a pointer-to-object type*

Hence I'm trying with ACTION_P

Now with this implementation, I only get the first letter of the szDeviceName variable (into this pObjData) i.e., "D" followed by 29 0's in the real code flow after this mock object is called.

I want to get the full string name set into this void * arguement.

I refered to this below question and was able progress this far. But I'm not able to pass the full string. How to set, in google mock, a void* argument to a set of values?

Any information regarding this will be helpful.

Body:
I recently had a similar need and came up with this as a generic solution.  It's based on the built-in SetArgPointee and has the same syntax:

template <size_t N, typename A>
class SetArgumentPointeeVoidAction {
public:
    explicit SetArgumentPointeeVoidAction(const A& value) : value_(value) {}
    void operator=(SetArgumentPointeeVoidAction const&) = delete;

    template <typename Result, typename ArgumentTuple>
    void Perform(const ArgumentTuple& args) const
    {
        ::testing::StaticAssertTypeEq<void, Result>();
        ::testing::StaticAssertTypeEq<void*,
            std::decay<decltype(::testing::get<N>(args))>::type>();
        *static_cast<A*>(::testing::get<N>(args)) = value_;
    }

private:
    const A value_;
};

/**
 * \brief  Sets a \c void* output argument to the contents of the
 *         supplied object.  It's on you to ensure this is safe.
 * \tparam N The argument index.
 * \tparam T The real argument type.
 * \param  x The argument to assign to the output argument.
 * \return A GMock Action that performs the requested assignment.
 * \note   Use \c SetArgPointee when it's not a \c void*.
 */
template <size_t N, typename T>
::testing::PolymorphicAction< SetArgumentPointeeVoidAction<N, T> >
SetArgPointeeVoid(const T& x)
{
    return ::testing::MakePolymorphicAction(
        SetArgumentPointeeVoidAction<N, T>(x));
}

It will give you a compile error if you try to use this on an argument that isn't a void*, so it should be relatively safe as long as you ensure you supply the correct argument.

It's also possible to implement this using ACTION_TEMPLATE, which is a bit shorter, but it generates unused argument warnings, which can be irritating.

(In older versions of GMock you might have to use ::std::tr1::get instead of ::testing::get.)

Left as an exercise for the reader: it's possible to enhance this with perfect forwarding to allow this to move-construct and move-assign for a slight efficiency boost.  Although if you're passing anything other than PODs around as void*s then you're probably doing it wrong.


问:
Clicking Tableview Cell Does Not Display Data
I'm having trouble with my didSelectRowAt function of my tableview. For some reason, although my segue identifier and destination view are correct, when I click the row, it does not load anything. Furthermore, Xcode informs me:

Cannot assign value of type 'Double?' to type 'String?'

but I cannot find an online resource that tells me how to resolve this. For reference, the data I would like to display is from a nested JSON feed.

JSON Struct

```<code>struct PlayerStatsParent:Decodable{
    let rankings: [PlayerStats]
}

struct PlayerStats:Decodable {
    let personaname: String?
    let score: Double?
    let solo_competitive_rank: Int?
    let avatar: String?
}
</code>```

Cell Select Function

```<code>func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "showDetail", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? RankDetail {
        destination.playerRank = rank[(rankTable.indexPathForSelectedRow?.row)!]
    }
}
</code>```

Destination View Controller Code

```<code>import UIKit

class RankDetail: UIViewController {
    @IBOutlet var rankLabel: UILabel!
    @IBOutlet var scoreLabel: UILabel!

    var playerRank:PlayerStats?

    override func viewDidLoad() {
        super.viewDidLoad()
        rankLabel.text = "\(playerRank?.solo_competitive_rank)"
        scoreLabel.text = playerRank?.score
    }
</code>```

答:
Also check your select method.Should be this.

```<code>  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

}
</code>```

Not this;

```<code>func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showDetail", sender: self)
</code>```

}

If you select the cell.

Body:
I'm having trouble with my didSelectRowAt function of my tableview. For some reason, although my segue identifier and destination view are correct, when I click the row, it does not load anything. Furthermore, Xcode informs me:

Cannot assign value of type 'Double?' to type 'String?'

but I cannot find an online resource that tells me how to resolve this. For reference, the data I would like to display is from a nested JSON feed.

JSON Struct

struct PlayerStatsParent:Decodable{
    let rankings: [PlayerStats]
}

struct PlayerStats:Decodable {
    let personaname: String?
    let score: Double?
    let solo_competitive_rank: Int?
    let avatar: String?
}

Cell Select Function

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "showDetail", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? RankDetail {
        destination.playerRank = rank[(rankTable.indexPathForSelectedRow?.row)!]
    }
}

Destination View Controller Code

import UIKit

class RankDetail: UIViewController {
    @IBOutlet var rankLabel: UILabel!
    @IBOutlet var scoreLabel: UILabel!

    var playerRank:PlayerStats?

    override func viewDidLoad() {
        super.viewDidLoad()
        rankLabel.text = "\(playerRank?.solo_competitive_rank)"
        scoreLabel.text = playerRank?.score
    }

Body:
Also check your select method.Should be this.

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

}

Not this;

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showDetail", sender: self)

}

If you select the cell.


问:
Writing out a CSV to Response.OutputStream also writes out the HTML
I am attempting to write an ASP.NET page that allows a user to download their data from a database in a CSV format. I have written the below code which is in the code behind and will run on a button click. Here is what I have written:

```<code>  private void RunBackup()
  {
    Button1.Enabled = false;

    Response.ContentType = "text/csv";
    Response.AddHeader("content-disposition", "attachment; filename=backup.csv");

    try
    {
        using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString))
        using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8))
        {
            var queryString = "SELECT * FROM [Data] WHERE [ID] = @id";
            SqlCommand command = new SqlCommand(queryString, connection);
            command.Parameters.Add("@id", SqlDbType.Int).Value = userId;
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();

            // Write header row.
            for (int columnCounter = 0; columnCounter < reader.FieldCount; columnCounter++)
            {
                if(columnCounter > 0)
                {
                    writer.Write(separator);
                }
                writer.Write(reader.GetName(columnCounter));
            }
            writer.WriteLine(string.Empty);

            // Write out the data.
            while (reader.Read())
            {
                // Write out the column.
                for (int columnCounter = 0; columnCounter < reader.FieldCount; columnCounter++)
                {
                    if (columnCounter > 0)
                    {
                        writer.Write(separator);
                    }
                    writer.Write(reader.GetValue(columnCounter).ToString().Replace(",", ";").Replace("\"", " "));
                }
                writer.WriteLine(string.Empty);
            }

            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
    }
    catch(Exception e)
    {

    }
    finally
    {
        Button1.Enabled = true;
    }
</code>```

It works great, except for the fact that not only do I get the CSV file with the SQL data, but I also get - at the very end of the file - the HTML of the page. I cannot figure out what is doing that, though I suspect it is something to do with the Response headers OR with the output to the Response.OutputStream.

I would appreciate any pointing in the right direction.

答:
By default ASP.Net renders the form as Html and put it into the response unless you tell the opposite, so that the form returns to the client. That's why you see an Html page into the downloaded file.

Add this code at the end of your RunBackup() method.

```<code>Response.End();
</code>```

This will prevent more stuff to be added to your file.

Your code already has CompleteRequest() which is an important part to gracefully skip other events in the pipeline and prepare to end request. If the application is configured to buffer the output, Response.Flush(); can be added.

Body:
I am attempting to write an ASP.NET page that allows a user to download their data from a database in a CSV format. I have written the below code which is in the code behind and will run on a button click. Here is what I have written:

  private void RunBackup()
  {
    Button1.Enabled = false;

    Response.ContentType = "text/csv";
    Response.AddHeader("content-disposition", "attachment; filename=backup.csv");

    try
    {
        using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString))
        using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8))
        {
            var queryString = "SELECT * FROM [Data] WHERE [ID] = @id";
            SqlCommand command = new SqlCommand(queryString, connection);
            command.Parameters.Add("@id", SqlDbType.Int).Value = userId;
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();

            // Write header row.
            for (int columnCounter = 0; columnCounter < reader.FieldCount; columnCounter++)
            {
                if(columnCounter > 0)
                {
                    writer.Write(separator);
                }
                writer.Write(reader.GetName(columnCounter));
            }
            writer.WriteLine(string.Empty);

            // Write out the data.
            while (reader.Read())
            {
                // Write out the column.
                for (int columnCounter = 0; columnCounter < reader.FieldCount; columnCounter++)
                {
                    if (columnCounter > 0)
                    {
                        writer.Write(separator);
                    }
                    writer.Write(reader.GetValue(columnCounter).ToString().Replace(",", ";").Replace("\"", " "));
                }
                writer.WriteLine(string.Empty);
            }

            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
    }
    catch(Exception e)
    {

    }
    finally
    {
        Button1.Enabled = true;
    }

It works great, except for the fact that not only do I get the CSV file with the SQL data, but I also get - at the very end of the file - the HTML of the page. I cannot figure out what is doing that, though I suspect it is something to do with the Response headers OR with the output to the Response.OutputStream.

I would appreciate any pointing in the right direction.

Body:
By default ASP.Net renders the form as Html and put it into the response unless you tell the opposite, so that the form returns to the client. That's why you see an Html page into the downloaded file.

Add this code at the end of your RunBackup() method.

Response.End();

This will prevent more stuff to be added to your file.

Your code already has CompleteRequest() which is an important part to gracefully skip other events in the pipeline and prepare to end request. If the application is configured to buffer the output, Response.Flush(); can be added.


问:
matplotlib heat map some entries missing values
Right now my data looks like this:

```<code>nn = ["1W", "1F", "1V",,,,,"2W", "2F", "2V",,,,,"260W", 261F', "261V",,,,]
</code>```

Essentially each number has the same number of letters corresponding to it. 19 letters in total. And I have 4798 numbers. Basically, I have 4978*19 points in my list.

I have another list that looks like this:

```<code>value=[1.15, 0.67, 0.88..........]
</code>```

each value corresponds to the character in my nn list. That means I have 4978*19 values in my value list.

Essentially, I want a 2D grid plot with x axis corresponding to the number and y axis corresponding to the letter. Each cell represents the value. I need different colors to present different values. Maybe one color covers a range of values. like red color represents 1-10, blue represents 10-20??
To get a better sense of what I'm trying to plot. I hand drew a plot to visualize.

I could split my nn list into x-aixs and y-axis.

```<code>x_axis = [1,2,3,.......4978]

y_axis = ["W", "V", "F", .....] #19 in total
</code>```

One problem That I may run into is that because I have so many numbers. The plot will look humongous. So maybe I could split one big ass plot into subplots???

Also, some entries in my value list might be missing data, like value[100]=' ', or like value[101]='infinity'. The point is len(value) is still equal to 4978*19. So I also want some color to represent insufficient data.

答:
Given what you've shown of nn, it looks like the corresponding values are in order.
Therefore, I think you could convert your list to a 2D NumPy array

```<code>values = np.array(values).reshape((19, 4978))
</code>```

and then plot them using plt.imshow(values). For example,

```<code>import numpy as np
import matplotlib.pyplot as plt

# generate some random values
values = np.random.random(19*4978).tolist()

# convert the list to a 2D NumPy array
values = np.array(values).reshape((19, 4978))
h, w = values.shape

fig, ax = plt.subplots()
plt.imshow(values)
plt.colorbar()
plt.yticks(np.arange(h), list('PNIYLKCVFWABCDEFGHI'))
ax.set_aspect(w/h)
plt.show()
</code>```

Note that while the default colormap, viridis, is not as colorful as the example
you drew, it does have some very interesting
features. Perhaps the most
important is that the "intensity" of the colors correspond well to a
monotonically increasing scale. Thus you can intuitively "read off" the value
represented by the colors in the plot. The same could not be said of a plot using
the colorful jet colormap, or a colormap like the one you proposed where 1--10 is
colored red and 10--20 is colored blue, etc. The reader would be forced to
constantly refer to the colorbar or a legend to check the correspondences between
colors and values.

Body:
Right now my data looks like this:

nn = ["1W", "1F", "1V",,,,,"2W", "2F", "2V",,,,,"260W", 261F', "261V",,,,]

Essentially each number has the same number of letters corresponding to it. 19 letters in total. And I have 4798 numbers. Basically, I have 4978*19 points in my list.

I have another list that looks like this:

value=[1.15, 0.67, 0.88..........]

each value corresponds to the character in my nn list. That means I have 4978*19 values in my value list.

Essentially, I want a 2D grid plot with x axis corresponding to the number and y axis corresponding to the letter. Each cell represents the value. I need different colors to present different values. Maybe one color covers a range of values. like red color represents 1-10, blue represents 10-20??
To get a better sense of what I'm trying to plot. I hand drew a plot to visualize.

I could split my nn list into x-aixs and y-axis.

x_axis = [1,2,3,.......4978]

y_axis = ["W", "V", "F", .....] #19 in total

One problem That I may run into is that because I have so many numbers. The plot will look humongous. So maybe I could split one big ass plot into subplots???

Also, some entries in my value list might be missing data, like value[100]=' ', or like value[101]='infinity'. The point is len(value) is still equal to 4978*19. So I also want some color to represent insufficient data.

Body:
Given what you've shown of nn, it looks like the corresponding values are in order.
Therefore, I think you could convert your list to a 2D NumPy array

values = np.array(values).reshape((19, 4978))

and then plot them using plt.imshow(values). For example,

import numpy as np
import matplotlib.pyplot as plt

# generate some random values
values = np.random.random(19*4978).tolist()

# convert the list to a 2D NumPy array
values = np.array(values).reshape((19, 4978))
h, w = values.shape

fig, ax = plt.subplots()
plt.imshow(values)
plt.colorbar()
plt.yticks(np.arange(h), list('PNIYLKCVFWABCDEFGHI'))
ax.set_aspect(w/h)
plt.show()

Note that while the default colormap, viridis, is not as colorful as the example
you drew, it does have some very interesting
features. Perhaps the most
important is that the "intensity" of the colors correspond well to a
monotonically increasing scale. Thus you can intuitively "read off" the value
represented by the colors in the plot. The same could not be said of a plot using
the colorful jet colormap, or a colormap like the one you proposed where 1--10 is
colored red and 10--20 is colored blue, etc. The reader would be forced to
constantly refer to the colorbar or a legend to check the correspondences between
colors and values.


问:
How to comment on embedded facebook post on a website without leaving it
I recently made a fanpage and i have used embedded code from one of the post of my fanpage to  my website.

So now It shows the post on my website and number of likes but i would like to show current existing comments which that particular post had got. Right now it is just displays the comment button and if i will click that then it will take me to the fanpage just for the sake of comment.

So heres what i need

1 - Comment on the embedded post without leaving the website to facebook.

2 - Displaying all the current existed comments ..

the image right now look like this

答:
I think David's answer will just post a new comment, not show all post's comments.

Unfortunately there is not a option to show the comments on embed posts.
You need to get the post id, call a api to load all comments and so embed each one of them. Yeah, that's terrible...

Open the graph api explorer:

https://developers.facebook.com/tools/explorer/

Type {post-id}/comments on GET input and send it to see a response example.

And that's how you embed comments:

https://developers.facebook.com/docs/plugins/embedded-comments

I don't think loading all comments from all posts will have a good performance. I suggest you to create a button "see comments" which call the api. After that you can create the input text for new comments, like David said.


问:
Connect Local SQL Server Database using Azure Active Directory Credentials
The SQL Server (version 2016) is located in the local Virtual Machine(Windows Server 2012 R2) and I need to provide authentication for the users in the Azure Active Directory. As I am new to this I am not even sure whether it is possible or not. Can anybody guide me.</p>

答:
No, it is impossible. Please refer to this official document.

Connecting to SQL Server running on an Azure VM is not supported using
  an Azure Active Directory account. Use a domain Active Directory
  account instead.

It means if your local sql server could not use Azure Active Directory Authentication. You could use local domain Active Directory users.

If you use Azure SQL Database and SQL Data Warehouse, you could use Azure Active Directory authentication. Please refer to this link.


问:
C struct and malloc problem (C)
It's amazing how even the littlest program can cause so much trouble in C.

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
    tree* tree = (tree*) malloc(sizeof(tree));
    node *node = (node*) malloc(sizeof(node));
    tree->nodes[0] = node;
    return tree;
}

int main() {
    return 0;
}
</code>```

The compiler says:

```<code>main.c: In function 'initTree':
main.c:17: error: expected expression before ')' token
main.c:18: error: expected expression before ')' token
</code>```

Can you please help?

答:
You're using two variables named tree and node, but you also have structs typedefed as tree and node.

Change your variable names:

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
   /* in C code (not C++), don't have to cast malloc's return pointer, it's implicitly converted from void* */
   tree* atree = malloc(sizeof(tree)); /* different names for variables */
   node* anode = malloc(sizeof(node));
   atree->nodes[0] = anode;
   return atree;
}

int main() {
    return 0;
}
</code>```

Title: C struct and malloc problem (C)

Body:
It's amazing how even the littlest program can cause so much trouble in C.

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
    tree* tree = (tree*) malloc(sizeof(tree));
    node *node = (node*) malloc(sizeof(node));
    tree->nodes[0] = node;
    return tree;
}

int main() {
    return 0;
}

The compiler says:

main.c: In function 'initTree':
main.c:17: error: expected expression before ')' token
main.c:18: error: expected expression before ')' token

Can you please help?

Body:
You're using two variables named tree and node, but you also have structs typedefed as tree and node.

Change your variable names:

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
   /* in C code (not C++), don't have to cast malloc's return pointer, it's implicitly converted from void* */
   tree* atree = malloc(sizeof(tree)); /* different names for variables */
   node* anode = malloc(sizeof(node));
   atree->nodes[0] = anode;
   return atree;
}

int main() {
    return 0;
}


问:
Oracle sql query sum data every month
Let's say i have selected data from oktober until desember like this

i want to get sum of buying customer in every months (okt-des)
The result i want is like table below

i already know how to get last day of months
but i don't have idea query in SQL to get result like i need

答:
Try this</p>

```<code> DESC TABLE_NAME
        NAME    VARCHAR2(20 BYTE)
        BUYING  NUMBER
        BUYING_DATE DATE

    select * from
    (
    select name,buying,RTRIM(to_char(buying_Date,'Month')) dd
    from
    TABLE_NAME
    )
    PIVOT
    (
    SUM(buying)
    for dd IN ('October','November','December')
    );
</code>```

Title: Oracle sql query sum data every month

Body:
Try this

 DESC TABLE_NAME
        NAME    VARCHAR2(20 BYTE)
        BUYING  NUMBER
        BUYING_DATE DATE

    select * from
    (
    select name,buying,RTRIM(to_char(buying_Date,'Month')) dd
    from
    TABLE_NAME
    )
    PIVOT
    (
    SUM(buying)
    for dd IN ('October','November','December')
    );


问:
variables inputs -> html form no webserver ,out put text file, with variables used in strings
new to HTML/Javascript

Trying to create a HTML form that takes in 6 different input values from user, which are all integers.

on submit will then output a text file which is just lines of text which have the inputs in bedded

example
ask for inputs
input1 :
input2 :
input3 :
input4 :
input5 :
input6 :

then on submit have a text file generated with

command1:input1input2:command2,test

command1:input3input4:command2,test

command1:input4:command2,test

command1:input5:command2,test

command1:input6input2:command2,test

essentially its a form, repeating same set of strings in a text, but the inputs are taken into account.

sorry about the missing example here it is

i have been using alerts, and want to switch this to writing the alerts line by line into a text file and download it..

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>
      TEST FORM
    </title>
    <script language="JavaScript" type="text/javascript">
//<![CDATA[
    function testResults (form) {
    var TestVar1 = form.inputbox1.value;
    var TestVar2 = form.inputbox2.value;
    var TestVar3 = form.inputbox3.value;
    var TestVar4 = form.inputbox4.value;
    var TestVar5 = form.inputbox5.value;
    var TestVar6 = "command" + TestVar1 + TestVar2 + "command2"

    alert ("command1: " + TestVar1 );
    alert ("command2: " + TestVar2 + TestVar2 + "command5");
    alert ("command3: " + TestVar3 + "command5;;:" + TestVar2);
    alert ("command4: " + TestVar4 + "command1;;" + TestVar2);
    alert ("command5: " + TestVar5 + "command2" + TestVar2);
    alert ("command6: " + TestVar6 + TestVar2);
                            }
    //]]>
    </script>
  </head>
  <body>
    <form name="myform" action="" method="get" id="myform">
      Enter something in the box:<br />
      <label for="input1">input1</label> <input type="text" name=
      "inputbox1" value="" id="input1" />
      <p>
        <label for="input1">input2</label> <input type="text" name=
        "inputbox2" value="" id="input2" />
      </p>
      <p>
        <label for="input1">input3</label> <input type="text" name=
        "inputbox3" value="" id="input3" />
      </p>
      <p>
        <label for="input1">input4</label> <input type="text" name=
        "inputbox4" value="" id="input4" />
      </p>
      <p>
        <label for="input1">input5</label> <input type="text" name=
        "inputbox5" value="" id="input5" />
      </p>
      <p>
        <input type="button" name="button" value="Click" onclick=
        "testResults(this.form)" />
      </p>
    </form>
  </body>
</code>```

答:
Forms send all input data to a server/webpage which processes the input into whatever it is needed (in your case it's just printing the inputs in a line).

The general form structure:

```<code><form action="send_to_this_server_or_webpage.html" method="get (or) post">
   Input 1: <input name="parameter_name" type="text (or) number">
   ...
   <input type="submit" value="Submit">
</form>
</code>```

Then in the HTML page that is receiving the incoming form, you would write Javascript to get your values from the parameters (names) that you set in your HTML form.

P.S.  Your question is a bit confusing as to what exactly you want to perform but my answer is the general way of retrieving values from forms using parameters.

Body:
new to HTML/Javascript

Trying to create a HTML form that takes in 6 different input values from user, which are all integers.

on submit will then output a text file which is just lines of text which have the inputs in bedded

example
ask for inputs
input1 :
input2 :
input3 :
input4 :
input5 :
input6 :

then on submit have a text file generated with

command1:input1input2:command2,test

command1:input3input4:command2,test

command1:input4:command2,test

command1:input5:command2,test

command1:input6input2:command2,test

essentially its a form, repeating same set of strings in a text, but the inputs are taken into account.

sorry about the missing example here it is

i have been using alerts, and want to switch this to writing the alerts line by line into a text file and download it..

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>
      TEST FORM
    </title>

    <form name="myform" action="" method="get" id="myform">
      Enter something in the box:

      input1 <input type="text" name=
      "inputbox1" value="" id="input1" />

        input2 <input type="text" name=
        "inputbox2" value="" id="input2" />

        input3 <input type="text" name=
        "inputbox3" value="" id="input3" />

        input4 <input type="text" name=
        "inputbox4" value="" id="input4" />

        input5 <input type="text" name=
        "inputbox5" value="" id="input5" />

        <input type="button" name="button" value="Click" onclick=
        "testResults(this.form)" />

    </form>

Body:
Forms send all input data to a server/webpage which processes the input into whatever it is needed (in your case it's just printing the inputs in a line).

The general form structure:

<form action="send_to_this_server_or_webpage.html" method="get (or) post">
   Input 1: <input name="parameter_name" type="text (or) number">
   ...
   <input type="submit" value="Submit">
</form>

Then in the HTML page that is receiving the incoming form, you would write Javascript to get your values from the parameters (names) that you set in your HTML form.

P.S.  Your question is a bit confusing as to what exactly you want to perform but my answer is the general way of retrieving values from forms using parameters.


问:
Rendering List with Fetch in React
Trying to render a list of movies from a random API and eventually filter them.

```<code>componentDidMount() {
    var myRequest = new Request(website);
    let movies = [];

    fetch(myRequest)
        .then(function(response) { return response.json(); })
        .then(function(data) {
            data.forEach(movie =>{
                movies.push(movie.title);
            })
        });
     this.setState({movies: movies});
}

render() {
    console.log(this.state.movies);
    console.log(this.state.movies.length);
    return (
        <h1>Movie List</h1>
    )
}
</code>```

If I render this I can only print my state and not access what is inside.
How would I create a list of LIs and render a UL?
Thanks

答:
First of all, since fetch is asynchronous, you will most likely call setState before the fetch call has completed, and you obviously don't want to do that.

Second, if the data returned is an array of movies, do not iterate over it, just assign the array altogether to the movies state variable.

So, in short, this is what your componentDidMount method should look like :

```<code>componentDidMount() {
  var myRequest = new Request(website);

  fetch(myRequest)
    .then(res => res.json())
    .then(movies =>
      this.setState({ movies }) // little bit of ES6 assignment magic
    );
}
</code>```

Then in your render function you can do something like:

```<code>render() {
  const { movies } = this.state.movies;
  return (
    <ul>
      { movies.length && movies.map(m => <li key={m.title}>{m.title}</li>) }
    </ul>
  );
}
</code>```

Title: Rendering List with Fetch in React

Body:
Trying to render a list of movies from a random API and eventually filter them.

componentDidMount() {
    var myRequest = new Request(website);
    let movies = [];

    fetch(myRequest)
        .then(function(response) { return response.json(); })
        .then(function(data) {
            data.forEach(movie =>{
                movies.push(movie.title);
            })
        });
     this.setState({movies: movies});
}

render() {
    console.log(this.state.movies);
    console.log(this.state.movies.length);
    return (

Movie List

    )
}

If I render this I can only print my state and not access what is inside.
How would I create a list of LIs and render a UL?
Thanks

Body:
First of all, since fetch is asynchronous, you will most likely call setState before the fetch call has completed, and you obviously don't want to do that.

Second, if the data returned is an array of movies, do not iterate over it, just assign the array altogether to the movies state variable.

So, in short, this is what your componentDidMount method should look like :

componentDidMount() {
  var myRequest = new Request(website);

  fetch(myRequest)
    .then(res => res.json())
    .then(movies =>
      this.setState({ movies }) // little bit of ES6 assignment magic
    );
}

Then in your render function you can do something like:

render() {
  const { movies } = this.state.movies;
  return (
    <ul>
      { movies.length && movies.map(m => <li key={m.title}>{m.title}</li>) }
    </ul>
  );
}


问:
Cross Domain REST POST Does Preflight Check But No Follow Up
I'm new to web programming so bear with me.  I've created a simple REST API in python flask, and am hosting it with Apache 2.4.  I've tested it via cURL and it works.  Now I'm trying to access it via a web interface with jQuery.

The REST api is at http://api.localhost and the website that accesses it is at http://localhost.

The code I'm using to try and do a POST looks like this:

```<code>    $.ajax({
        type: 'POST',
        url: 'http://api.localhost/auth',
        data: '{"username":"user1", "password":"abcxyz"}',
        success: function(data) { console.log(data); alert('data: ' + data);  },
        contentType: "application/json",
        dataType: 'json'
    });
</code>```

However, it seems the success function doesn't run.  Looking in dev console (f12) I can see that instead of a POST to that URL, and OPTIONS HTTP request is made.  My understanding is this is a Cross-Origin Resource Sharing (CORS) preflight check, to make sure it's OK for localhost to access api.localhost.

I've added the following lines to my apache config for api.localhost:

```<code>Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS"
</code>```

It seems to be working to because the OPTIONS request returns a 200 (and no other data).  However, there is no follow up.  My understanding is since the server is saying it's OK for anyone to POST to api.localhost, that it should go ahead and do the POST next, but it doesn't.

Here are the preflight check request headers:

```<code>Host: api.localhost
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101
Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Origin: http://localhost
Connection: keep-alive
Cache-Control: max-age=0
</code>```

Here are the response headers for that same request (remember, status 200):

```<code>Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Origin: *
Allow: POST, OPTIONS
Connection: Keep-Alive
Content-Encoding: gzip
Content-Length: 20
Content-Type: text/html; charset=utf-8
Date: Thu, 07 Dec 2017 00:17:08 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.29 (Debian)
Vary: Accept-Encoding
</code>```

You can see that the server is saying any domain is fine (*) and that POST is OK.  However, there is no follow up POST.  What am I missing?

Thanks.

答:
http://api.localhost/auth must also send Access-Control-Allow-Headers: content-type.

So to your Apache config, you also need to add this:

Header always set Access-Control-Allow-Headers "content-type"
```

That’s necessary because the contentType: "application/json" part of your frontend code adds a Content-Type: application/json header to the request, and any values for the Content-Type request header other than text/plain, application/x-www-form-urlencoded, or multipart/form-data will trigger browsers to send a CORS preflight OPTIONS request.

So if you have your http://api.localhost/auth server send back the Access-Control-Allow-Headers: content-type response header, that should cause the preflight to succeed, and so cause the browser to move on to making the POST request from your frontend code.

Body:
I'm new to web programming so bear with me.  I've created a simple REST API in python flask, and am hosting it with Apache 2.4.  I've tested it via cURL and it works.  Now I'm trying to access it via a web interface with jQuery.

The REST api is at http://api.localhost and the website that accesses it is at http://localhost.

The code I'm using to try and do a POST looks like this:

    $.ajax({
        type: 'POST',
        url: 'http://api.localhost/auth',
        data: '{"username":"user1", "password":"abcxyz"}',
        success: function(data) { console.log(data); alert('data: ' + data);  },
        contentType: "application/json",
        dataType: 'json'
    });

However, it seems the success function doesn't run.  Looking in dev console (f12) I can see that instead of a POST to that URL, and OPTIONS HTTP request is made.  My understanding is this is a Cross-Origin Resource Sharing (CORS) preflight check, to make sure it's OK for localhost to access api.localhost.

I've added the following lines to my apache config for api.localhost:

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS"

It seems to be working to because the OPTIONS request returns a 200 (and no other data).  However, there is no follow up.  My understanding is since the server is saying it's OK for anyone to POST to api.localhost, that it should go ahead and do the POST next, but it doesn't.

Here are the preflight check request headers:

Host: api.localhost
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101
Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Origin: http://localhost
Connection: keep-alive
Cache-Control: max-age=0

Here are the response headers for that same request (remember, status 200):

Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Origin: *
Allow: POST, OPTIONS
Connection: Keep-Alive
Content-Encoding: gzip
Content-Length: 20
Content-Type: text/html; charset=utf-8
Date: Thu, 07 Dec 2017 00:17:08 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.29 (Debian)
Vary: Accept-Encoding

You can see that the server is saying any domain is fine (*) and that POST is OK.  However, there is no follow up POST.  What am I missing?

Thanks.

Body:
http://api.localhost/auth must also send Access-Control-Allow-Headers: content-type.

So to your Apache config, you also need to add this:

Header always set Access-Control-Allow-Headers "content-type"

That’s necessary because the contentType: "application/json" part of your frontend code adds a Content-Type: application/json header to the request, and any values for the Content-Type request header other than text/plain, application/x-www-form-urlencoded, or multipart/form-data will trigger browsers to send a CORS preflight OPTIONS request.

So if you have your http://api.localhost/auth server send back the Access-Control-Allow-Headers: content-type response header, that should cause the preflight to succeed, and so cause the browser to move on to making the POST request from your frontend code.


问:
SQL - Can this relation have a primary key?
The relationship between bands and members, 'MemberOf', includes a member id (Mid), band id (Bid), 'StartYear', 'EndYear' and 'Instrument' played. Mid and Bid are both foreign keys to Member and Band relations respectively but I am struggling to identify the primary key in this situation for the 'MemberOf' relation.

Note: start year can be null if a member was in a band from the start and end year can also be null if a member is still in the band.

In this situation, start and end year cannot be used as PK's as they may contain null values, but the member id and band id is not enough information to be unique - e.g. the same member returns to the same band at a later date.

Does this mean no primary key exists? Thanks.

答:
One possible solution would be to store the StartYear value as the year the band was started.  That way you could use (MId, BId, StartYear) as a primary key assuming members can only join and quit once per year (as suggested by your design).

To test for "original member" you compare MemberOf.StartYear with Band.StartYear for equality.

Otherwise no, you don't have a valid primary key and need to add some kind of disambiguating column (JoinNumber or something), which seems like undesirable extra effort.


问:
Change column type in a materialized view
I have a materialized view based on a table that on which a column type changed. and I'd like to change the column on the materialized view.

I'm aware that a view is based on it's definition but I couldn't find how to updated the select in the definition.

Is the only way to do it to drop the view and re-create it with a new definition?

答:
It's not what you were hoping to get, but currently the only way to change the query on which a materialized view is based is to drop and recreate it. Still the case in Postgres 10.

ALTER MATERIALIZED VIEW can only change auxiliary properties. You can also change column names, but not data types.

If concurrent access is required and the MV takes a long time to recreate, you might create a new MV under a different name, populate it and use it instead of the old one to keep downtime to a minimum - if that's an option.

Related:

Replace a materialized view in Postgres


问:
Stream based lambda concurrent execution
I have a python lambda function that is triggered when there is an INSERT or an UPDATE in the Dynamodb. As we know, it is a stream-based invocation. If there are 1000 records that are inserted into the Dynamodb, and I gave batch size as 1. My problem is the lambda is running each record one after the other. How do I change it to run all 1000 records in parallel(Concurrent executions)?  should i import any additional python modules like "from concurrent.futures import ThreadPoolExecutor" other than what i am using for my work?  (My code is really big to post here)</p>

答:
You cannot control the parallelism of the processing of the stream.

AWS DynamoDB streams will separate the DynamoDB table rows into shards. Each shard will be processed serially (one batch at a time). This is to ensure "in order" processing of rows.

However, if your table has heavy writes, then DynamoDB streams may split and re-split shards into smaller parent and child shards. The shards can be processed in parallel.

See http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html

The best control you can do is increase the "batch size" up from 1. If you are confident that your database updates can be processed concurrently, then you can concurrently process the multiple rows you'll receive with a batch size > 1 inside your Lambda function.


问:
Foreign characters in website
I found a website that contains the string "donâ€™t". The obvious intent was the word "don't". I looked at the source expecting to see some character references, but didn't (it just shows the literal string "donâ€™t". A Google search yielded nothing (expect lots of other sites that have the same problem!). Can anyone explain what's happening here?

Edit: Here's the meta tag that was used:

```<code><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</code>```

Would this not cause the page to be served up as Latin-1 in the HTTP header?

答:
According to Character encondings in HTML a lemme in wikipedia:

HTML (Hypertext Markup Language) has
  been in use since 1991, but HTML 4.0
  (December 1997) was the first
  standardized version where
  international characters were given
  reasonably complete treatment. When an
  HTML document includes special
  characters outside the range of
  seven-bit ASCII two goals are worth
  considering: the information's
  integrity, and universal browser
  display.

I suppose the site you checked, isn't impelemented with this in mind.

Title: Foreign characters in website

Body:
I found a website that contains the string "donâ€™t". The obvious intent was the word "don't". I looked at the source expecting to see some character references, but didn't (it just shows the literal string "donâ€™t". A Google search yielded nothing (expect lots of other sites that have the same problem!). Can anyone explain what's happening here?

Edit: Here's the meta tag that was used:

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

Would this not cause the page to be served up as Latin-1 in the HTTP header?


问:
Routes not working on Slim framework
I am learning the slim framework. I got a point where I have to set up my webserver such that I can see something like http://slimapp instead of http://localhost/slimapp/public/index.php.

I have included a .htaccess file in the public folder of my project like so

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]
</code>```

I have also set up a virtual host on my wamp server

```<code><VirtualHost *:80>
    DocumentRoot "C:\wamp64\www\slimapp\public"
    ServerName slimapp

    <Directory "C:\wamp64\www\slimapp\public">
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>
</code>```

I have also added this to my hosts file

```<code>127.0.0.1 slimapp
</code>```

I restarted my server but I get a 'Not Found' error when I try to access my routes.

```<code>"Not Found
The requested URL /hello/uche was not found on this server."
</code>```

This is my index.php file

```<code><?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require '../vendor/autoload.php';

$app = new \Slim\App;
$app->get('/hello/{name}', function (Request $request, Response $response) {
    $name = $request->getAttribute('name');
    $response->getBody()->write("Hello, $name");

    return $response;
});
$app->run();
</code>```

Please help me here.

答: try to move .htaccess file to root directory</p>

Title: Routes not working on Slim framework

Body:
I am learning the slim framework. I got a point where I have to set up my webserver such that I can see something like http://slimapp instead of http://localhost/slimapp/public/index.php.

I have included a .htaccess file in the public folder of my project like so

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]

I have also set up a virtual host on my wamp server

<VirtualHost *:80>
    DocumentRoot "C:\wamp64\www\slimapp\public"
    ServerName slimapp

    <Directory "C:\wamp64\www\slimapp\public">
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

I have also added this to my hosts file

127.0.0.1 slimapp

I restarted my server but I get a 'Not Found' error when I try to access my routes.

"Not Found
The requested URL /hello/uche was not found on this server."

This is my index.php file

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require '../vendor/autoload.php';

$app = new \Slim\App;
$app->get('/hello/{name}', function (Request $request, Response $response) {
    $name = $request->getAttribute('name');
    $response->getBody()->write("Hello, $name");

    return $response;
});
$app->run();

Please help me here.