问:
use csvhelper to download files to a specific location
I want to use the linq and then let the user download a csv file to their speicifc location.

I learn something from internet and learning a csvhelper.
I write something which works and download to a specific location (D:\export.csv) as below.

```<code>    public ActionResult YRecordReport()
    {
        using (var sw = new StreamWriter(@"d:\export.csv", true, Encoding.GetEncoding("big5")))
        using (var writer = new CsvWriter(sw))
        {
            var abc = from t in db.TRecordDBSet
                      join s in db.SInfoDBSet on t.SId equals s.SId
                      orderby s.sId, t.StartToEndDate
                      select new TRecord()
                      {
                          StaffId = t.SId,
                          Date = t.StartToEndDate,
                          Name = s.Cname,
                          CourseName = t.Tname,
                          Organizer = t.Organizer,
                          Hour = t.Hour,
                          Score = t.Score
                      };

            var source = abc.ToList();

            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<TRecord, TRecord_Data>();
            });

            config.AssertConfigurationIsValid();
            Mapper.Initialize(cfg => cfg.CreateMap<TRecord, TRecord_Data>());
            writer.Configuration.Encoding = Encoding.GetEncoding("big5");

            var mapper = config.CreateMapper();

            List<TRecord_Data> records = Mapper.Map<List<TRecord>, List<TRecord_Data>>(source);

            foreach (var item in records)
            {
                writer.WriteRecord(item);
            }
      }
}
</code>```

Because I want to let the user to download the files to their specific location, I modified the code as below, it runs ok and the export.csv files is empty. Is that I write anything not specified? and how can i let the user download and use their filename?

```<code>    [MyAuthFilter(Auth = "Admin")]
    public ActionResult YearTrainingRecordReport()
    {
        var memoryStream = new MemoryStream();
        var stream = new StreamWriter(memoryStream);
        var writer = new CsvWriter(stream);

        var abc = from t in db.TRecordDBSet
                      join s in db.SInfoDBSet on t.SId equals s.SId
                      orderby s.SId, t.StartToEndDate
                      select new TRecord()
                      {
                          Sd = t.SId,
                          Date = t.StartToEndDate,
                          Name = s.Cname,
                          CourseName = t.Tname,
                          Organizer = t.Organizer,
                          Hour = t.Hour,
                          Score = t.Score
                      };

            var source = abc.ToList();

            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<TRecord, TRecord_Data>();
            });

            config.AssertConfigurationIsValid();
            Mapper.Initialize(cfg => cfg.CreateMap<TRecord, TRecord_Data>());
            writer.Configuration.Encoding = Encoding.GetEncoding("big5");

            var mapper = config.CreateMapper();

            List<TRecord_Data> records = Mapper.Map<List<TRecord>, List<TRecord_Data>>(source);

            foreach (var item in records)
            {
                writer.WriteRecord(item);
            }

            return File(memoryStream, "text/csv", "export.csv");

}
</code>```

答:
You need to flush your writer and reset the stream.

```<code>writer.Flush();
stream.Position = 0;
</code>```

If you're using CsvHelper 3.0 or later (currently in pre-release), you'll also need to force a new record.

```<code>writer.NextRecord();
</code>```

Body:
I want to use the linq and then let the user download a csv file to their speicifc location.

I learn something from internet and learning a csvhelper.
I write something which works and download to a specific location (D:\export.csv) as below.

    public ActionResult YRecordReport()
    {
        using (var sw = new StreamWriter(@"d:\export.csv", true, Encoding.GetEncoding("big5")))
        using (var writer = new CsvWriter(sw))
        {
            var abc = from t in db.TRecordDBSet
                      join s in db.SInfoDBSet on t.SId equals s.SId
                      orderby s.sId, t.StartToEndDate
                      select new TRecord()
                      {
                          StaffId = t.SId,
                          Date = t.StartToEndDate,
                          Name = s.Cname,
                          CourseName = t.Tname,
                          Organizer = t.Organizer,
                          Hour = t.Hour,
                          Score = t.Score
                      };

            var source = abc.ToList();

            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<TRecord, TRecord_Data>();
            });

            config.AssertConfigurationIsValid();
            Mapper.Initialize(cfg => cfg.CreateMap<TRecord, TRecord_Data>());
            writer.Configuration.Encoding = Encoding.GetEncoding("big5");

            var mapper = config.CreateMapper();

            List<TRecord_Data> records = Mapper.Map<List<TRecord>, List<TRecord_Data>>(source);

            foreach (var item in records)
            {
                writer.WriteRecord(item);
            }
      }
}

Because I want to let the user to download the files to their specific location, I modified the code as below, it runs ok and the export.csv files is empty. Is that I write anything not specified? and how can i let the user download and use their filename?

    [MyAuthFilter(Auth = "Admin")]
    public ActionResult YearTrainingRecordReport()
    {
        var memoryStream = new MemoryStream();
        var stream = new StreamWriter(memoryStream);
        var writer = new CsvWriter(stream);

        var abc = from t in db.TRecordDBSet
                      join s in db.SInfoDBSet on t.SId equals s.SId
                      orderby s.SId, t.StartToEndDate
                      select new TRecord()
                      {
                          Sd = t.SId,
                          Date = t.StartToEndDate,
                          Name = s.Cname,
                          CourseName = t.Tname,
                          Organizer = t.Organizer,
                          Hour = t.Hour,
                          Score = t.Score
                      };

            var source = abc.ToList();

            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<TRecord, TRecord_Data>();
            });

            config.AssertConfigurationIsValid();
            Mapper.Initialize(cfg => cfg.CreateMap<TRecord, TRecord_Data>());
            writer.Configuration.Encoding = Encoding.GetEncoding("big5");

            var mapper = config.CreateMapper();

            List<TRecord_Data> records = Mapper.Map<List<TRecord>, List<TRecord_Data>>(source);

            foreach (var item in records)
            {
                writer.WriteRecord(item);
            }

            return File(memoryStream, "text/csv", "export.csv");

}

Body:
You need to flush your writer and reset the stream.

writer.Flush();
stream.Position = 0;

If you're using CsvHelper 3.0 or later (currently in pre-release), you'll also need to force a new record.

writer.NextRecord();


来源: stackexchange

问:
How do I make a vertical graph based on inputs?
Input

```<code>1 1 3 1
</code>```

Output

```<code>  #
  #
####
</code>```

Input

```<code>0 3 0 4 5
</code>```

Output

```<code>    #
   ##
 # ##
 # ##
 # ##
</code>```

This is the code I have so far..

```<code>#include <stdio.h>
int main (void){
    int height[80],length=0,max=0;
    while ((scanf("%d",&height[length++])) != EOF && length <=79) {
        if (height[length-1] > max) {
            max=height[length-1];
        }
    }
}
</code>```

The input may not contain no more than 80 values.
I am not entire certain on how to add on more codes from here.

答:
This could work for you.

```<code>#include <stdio.h>
#define MAX 100

int main(void) {
    int st[MAX];
    int n = 0;
    int i, j;
    int max_value = -1;

    while (scanf("%d", st + n) != EOF) {
        if (st[n] > max_value)
            max_value = st[n];
        ++n;
    }

    for (i = max_value; i > 0; --i) {
        for (j = 0; j < n; ++j) {
            if (st[j] >= i)
                printf("#");
            else
                printf(" ");
        }
        printf("\n");
    }

    return 0;
}
</code>```

Input

0 3 0 4 5 "Enter" "Ctrl+D"

Output

```<code>    #
   ##
 # ##
 # ##
 # ##
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Input

1 1 3 1

Output

  #
  #
####

Input

0 3 0 4 5

Output

    #
   ##
 # ##
 # ##
 # ##

This is the code I have so far..

#include <stdio.h>
int main (void){
    int height[80],length=0,max=0;
    while ((scanf("%d",&height[length++])) != EOF && length <=79) {
        if (height[length-1] > max) {
            max=height[length-1];
        }
    }
}

The input may not contain no more than 80 values.
I am not entire certain on how to add on more codes from here.

Body:
This could work for you.

#include <stdio.h>
#define MAX 100

int main(void) {
    int st[MAX];
    int n = 0;
    int i, j;
    int max_value = -1;

    while (scanf("%d", st + n) != EOF) {
        if (st[n] > max_value)
            max_value = st[n];
        ++n;
    }

    for (i = max_value; i > 0; --i) {
        for (j = 0; j < n; ++j) {
            if (st[j] >= i)
                printf("#");
            else
                printf(" ");
        }
        printf("\n");
    }

    return 0;
}

Input

0 3 0 4 5 "Enter" "Ctrl+D"

Output

    #
   ##
 # ##
 # ##
 # ##


问:
How do I add am image in a TableView from URL
I am confused about how I can take the DownloadURL which is a link and turn it into an image and add it in my tableview cell? I have an imageview in my storyboard and dont know how to connect it to the tableview cell either. Thanks!</p>

```<code>override func viewDidLoad() { super.viewDidLoad()

    let ref = FIRDatabase.database().reference().child("Posts")

    ref.observeSingleEvent(of: .value, with: { snapshot in

        print(snapshot.childrenCount)

        for rest in snapshot.children.allObjects as! [FIRDataSnapshot] {

            guard let value = rest.value as? Dictionary<String,Any> else { continue }

            guard let  downloadURL = value["DownloadURL"] as? String else { continue }

            let post = postStruct(title: title, date: date, author: author, article: article, downloadURL: downloadURL)

            self.posts.append(post)

        }

        self.posts = self.posts.reversed(); self.tableView.reloadData()

    })

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return posts.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")

    let label1 = cell?.viewWithTag(1) as! UILabel
    label1.text = posts[indexPath.row].title
    return cell!
}
</code>```

答:
I think you do wrong way to download image from firebase

To download image url from firebase storage. You need define an imageView inside tableCell

`

```<code>let imagesRef = FIRStorage.storage().reference()
let imageRef = self.imagesRef.child("imageName.jpg")
imageRef.downloadURL { url, error in
    if let error = error {
    } else {
        DispatchQueue.main.async {
            cell.imageView.kf.setImage(with: url)
        }
    }
}
</code>```

`

Your code have problem, idk why you try using firebase database to download image, because you can't.

Body:
I am confused about how I can take the DownloadURL which is a link and turn it into an image and add it in my tableview cell? I have an imageview in my storyboard and dont know how to connect it to the tableview cell either. Thanks!

override func viewDidLoad() { super.viewDidLoad()

    let ref = FIRDatabase.database().reference().child("Posts")

    ref.observeSingleEvent(of: .value, with: { snapshot in

        print(snapshot.childrenCount)

        for rest in snapshot.children.allObjects as! [FIRDataSnapshot] {

            guard let value = rest.value as? Dictionary<String,Any> else { continue }

            guard let  downloadURL = value["DownloadURL"] as? String else { continue }

            let post = postStruct(title: title, date: date, author: author, article: article, downloadURL: downloadURL)

            self.posts.append(post)

        }

        self.posts = self.posts.reversed(); self.tableView.reloadData()

    })

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return posts.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")

    let label1 = cell?.viewWithTag(1) as! UILabel
    label1.text = posts[indexPath.row].title
    return cell!
}

Body:
I think you do wrong way to download image from firebase

To download image url from firebase storage. You need define an imageView inside tableCell

`

let imagesRef = FIRStorage.storage().reference()
let imageRef = self.imagesRef.child("imageName.jpg")
imageRef.downloadURL { url, error in
    if let error = error {
    } else {
        DispatchQueue.main.async {
            cell.imageView.kf.setImage(with: url)
        }
    }
}

`

Your code have problem, idk why you try using firebase database to download image, because you can't.


问:
Unable to resolve org.scalatest#scalatest;3.0.1: not found dependency issue
Newbie in scala here, going through a scala tutorial.

I am trying to use scalatest as mentioned in the tutorial but getting this error:

```<code>[error] (*:update) sbt.ResolveException: unresolved dependency: org.scalatest#scalatest;3.0.1: not found

> scalaVersion
[info] 2.10.6
</code>```

My build.sbt file looks like this:

```<code>name := "tasky"
version := "0.1.0"
libraryDependencies += "org.scalactic" %% "scalactic" % "3.0.1"
libraryDependencies += "org.scalatest" % "scalatest" % "3.0.1" % "test"
</code>```

Also as mentioned here, I have created the global.sbt and plugins.sbt file at the respective locations with the required details. But, I am still getting the error:

```<code>[info] Updating {file:/home/tushar/lsbt/tasky/}tasky...
[info] Resolving org.scalatest#scalatest;3.0.1 ...
[warn]  module not found: org.scalatest#scalatest;3.0.1
[warn] ==== local: tried
[warn]   /home/tushar/.ivy2/local/org.scalatest/scalatest/3.0.1/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/org/scalatest/scalatest/3.0.1/scalatest-3.0.1.pom
[warn] ==== local-preloaded-ivy: tried
[warn]   /home/tushar/.sbt/preloaded/org.scalatest/scalatest/3.0.1/ivys/ivy.xml
[warn] ==== local-preloaded: tried
[warn]   file:////home/tushar/.sbt/preloaded/org/scalatest/scalatest/3.0.1/scalatest-3.0.1.pom
[warn] ==== Artima Maven Repository: tried
[warn]   http://repo.artima.com/releases/org/scalatest/scalatest/3.0.1/scalatest-3.0.1.pom
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: org.scalatest#scalatest;3.0.1: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]
[warn]  Note: Unresolved dependencies path:
[warn]      org.scalatest:scalatest:3.0.1 (/home/tushar/lsbt/tasky/built.sbt#L4-5)
[warn]        +- default:tasky_2.10:0.1.0
[trace] Stack trace suppressed: run last *:update for the full output.
[error] (*:update) sbt.ResolveException: unresolved dependency: org.scalatest#scalatest;3.0.1: not found
</code>```

Any pointers to resolve this issue?

答:
If you are using maven repository then it should be </p>

```<code>libraryDependencies += "org.scalatest" % "scalatest_2.11" % "3.0.1"
</code>```

<p>And your scalactic should be </p>

```<code>libraryDependencies += "org.scalactic" % "scalactic_2.11" % "3.0.1"
</code>```

Body:
Newbie in scala here, going through a scala tutorial.

I am trying to use scalatest as mentioned in the tutorial but getting this error:

[error] (*:update) sbt.ResolveException: unresolved dependency: org.scalatest#scalatest;3.0.1: not found

> scalaVersion
[info] 2.10.6

My build.sbt file looks like this:

name := "tasky"
version := "0.1.0"
libraryDependencies += "org.scalactic" %% "scalactic" % "3.0.1"
libraryDependencies += "org.scalatest" % "scalatest" % "3.0.1" % "test"

Also as mentioned here, I have created the global.sbt and plugins.sbt file at the respective locations with the required details. But, I am still getting the error:

[info] Updating {file:/home/tushar/lsbt/tasky/}tasky...
[info] Resolving org.scalatest#scalatest;3.0.1 ...
[warn]  module not found: org.scalatest#scalatest;3.0.1
[warn] ==== local: tried
[warn]   /home/tushar/.ivy2/local/org.scalatest/scalatest/3.0.1/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/org/scalatest/scalatest/3.0.1/scalatest-3.0.1.pom
[warn] ==== local-preloaded-ivy: tried
[warn]   /home/tushar/.sbt/preloaded/org.scalatest/scalatest/3.0.1/ivys/ivy.xml
[warn] ==== local-preloaded: tried
[warn]   file:////home/tushar/.sbt/preloaded/org/scalatest/scalatest/3.0.1/scalatest-3.0.1.pom
[warn] ==== Artima Maven Repository: tried
[warn]   http://repo.artima.com/releases/org/scalatest/scalatest/3.0.1/scalatest-3.0.1.pom
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: org.scalatest#scalatest;3.0.1: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]
[warn]  Note: Unresolved dependencies path:
[warn]      org.scalatest:scalatest:3.0.1 (/home/tushar/lsbt/tasky/built.sbt#L4-5)
[warn]        +- default:tasky_2.10:0.1.0
[trace] Stack trace suppressed: run last *:update for the full output.
[error] (*:update) sbt.ResolveException: unresolved dependency: org.scalatest#scalatest;3.0.1: not found

Any pointers to resolve this issue?

Body:
If you are using maven repository then it should be

libraryDependencies += "org.scalatest" % "scalatest_2.11" % "3.0.1"

And your scalactic should be

libraryDependencies += "org.scalactic" % "scalactic_2.11" % "3.0.1"


问:
How To Set Sources For Jupyter Notebooks
I've just bought a new computer, and can't remember/don't know how I had Jupyter notebooks set up on my old machine. Specifically, how do you tell Jupyter about sources.

If I have a conda environment called django, and I do source activate django followed by jupyter notebook, I end up with a notebook, but then when I do from django.http import HttpResponse I get the error message

```<code>ModuleNotFoundError: No module named 'django'
</code>```

Which is bizarre (I think), because Django is definitely installed in the Django environment.

How do I set up my Jupyter notebooks so that they know about the various sources that I want them to know about?

答:
I create a kernel for each of my virtual environments. On MacOS Jupyter kernels are located here $HOME/Library/Jupyter/kernels. Make sure ipykernel is installed in your virtual env.

So $HOME/Library/Jupyter/kernels/myenv/kernel.json looks like:

```<code>{
 "env": { "VIRTUAL_ENV": "/Users/<User>/<myenv>" },
 "argv": [ "/Users/<User>/<myenv>/bin/python3", "-m", "ipykernel", "-f", "{connection_file}" ],
 "display_name": "My Virtual Env",
 "language": "python"
}
</code>```

Body:
I've just bought a new computer, and can't remember/don't know how I had Jupyter notebooks set up on my old machine. Specifically, how do you tell Jupyter about sources.

If I have a conda environment called django, and I do source activate django followed by jupyter notebook, I end up with a notebook, but then when I do from django.http import HttpResponse I get the error message

ModuleNotFoundError: No module named 'django'

Which is bizarre (I think), because Django is definitely installed in the Django environment.

How do I set up my Jupyter notebooks so that they know about the various sources that I want them to know about?

Body:
I create a kernel for each of my virtual environments. On MacOS Jupyter kernels are located here $HOME/Library/Jupyter/kernels. Make sure ipykernel is installed in your virtual env.

So $HOME/Library/Jupyter/kernels/myenv/kernel.json looks like:

{
 "env": { "VIRTUAL_ENV": "/Users/<User>/<myenv>" },
 "argv": [ "/Users/<User>/<myenv>/bin/python3", "-m", "ipykernel", "-f", "{connection_file}" ],
 "display_name": "My Virtual Env",
 "language": "python"
}


问:
Object.assign or declared class properties?
I am creating an angular application which accesses the twitch API. The data is returned in varying outlays, some of which I want to deserialize and store in a couple classes.

What I want to know is what are the risks of using Object.assign to instantiate a class compared to manually assigning properties from deserialized json data?

What I currently have:

```<code>export class UserDetails implements Serializable<UserDetails>{
    public _id: number;
    public bio: string;
    public created_at: string;
    public display_name: string;
    public email: string;
    public email_verified: boolean;
    public logo: string;
    public name: string;
    public notifications: Object;
    public partnered: boolean;
    public twitter_connected: boolean;
    public type: string;
    public updated_at: string;

    constructor() {}

    deserialize(input: any) {
        this._id = input._id;
        this.bio = input.bio;
        this.created_at = input.created_at;
        this.display_name = input.display_name;
        this.email = input.email;
        this.email_verified = input.email_verified;
        this.logo = input.logo;
        this.name = input.name;
        this.notifications = input.notifications;
        this.partnered = input.partnered;
        this.twitter_connected = input.twitter_connected;
        this.type = input.type;
        this.updated_at = input.updated_at;

        return this;
    }
}
</code>```

What I could have using Object.assign.

```<code>export class UserDetails implements Serializable<UserDetails>{

    constructor() {}

    deserialize(input: any) {
        Object.assign(this, input);

        return this;
    }
}
</code>```

I am about to create a new class which will have almost 70 properties.... Is this the best approach?

Afterthought... OR should I actually mix the 2 so I still get intellisense?

```<code>export class UserDetails implements Serializable<UserDetails>{
    public _id: number;
    public bio: string;
    public created_at: string;
    public display_name: string;
    public email: string;
    public email_verified: boolean;
    public logo: string;
    public name: string;
    public notifications: Object;
    public partnered: boolean;
    public twitter_connected: boolean;
    public type: string;
    public updated_at: string;

    constructor() {}

    deserialize(input: any) {
        Object.assign(this, input);

        return this;
    }
}
</code>```

答:
In my opinion, having the public class level fields would be beneficial for two reasons:

It should provide intellisense.

Using any non declared field, should raise an error (this is also applicable if no field is declared). Note that using Object.assign can add non declared fields to the object.

Example (fiddle link):

```<code>class Person {
  firstName;
  lastName;

  deserialize(input: any) {
    Object.assign(this, input);
    return this;
  }
}

let p = new Person();
p.deserialize({firstName:"John", lastName:"Doe", sex:"M"});

console.log(p);     //<-- logs: Person { firstName: 'John', lastName: 'Doe', sex: 'M' }
console.log(p.sex); //<-- this logs 'M' to console in JSFiddle.
</code>```

Note that the the propoerty sex is added to p, however, accessing the property directly like it is done in the 2nd console.log should raise the following compilation error (though it works on JSFiddle, not exactly sure why):

TSError: ⨯ Unable to compile TypeScript

nodesrc\test.ts (13,15): Property 'sex' does not exist on type 'Person'. (2339) ...

So if you would like to go with this kind of type-safety then declaring the fields might be helpful.

Hope this helps.

Body:
I am creating an angular application which accesses the twitch API. The data is returned in varying outlays, some of which I want to deserialize and store in a couple classes.

What I want to know is what are the risks of using Object.assign to instantiate a class compared to manually assigning properties from deserialized json data?

What I currently have:

export class UserDetails implements Serializable<UserDetails>{
    public _id: number;
    public bio: string;
    public created_at: string;
    public display_name: string;
    public email: string;
    public email_verified: boolean;
    public logo: string;
    public name: string;
    public notifications: Object;
    public partnered: boolean;
    public twitter_connected: boolean;
    public type: string;
    public updated_at: string;

    constructor() {}

    deserialize(input: any) {
        this._id = input._id;
        this.bio = input.bio;
        this.created_at = input.created_at;
        this.display_name = input.display_name;
        this.email = input.email;
        this.email_verified = input.email_verified;
        this.logo = input.logo;
        this.name = input.name;
        this.notifications = input.notifications;
        this.partnered = input.partnered;
        this.twitter_connected = input.twitter_connected;
        this.type = input.type;
        this.updated_at = input.updated_at;

        return this;
    }
}

What I could have using Object.assign.

export class UserDetails implements Serializable<UserDetails>{

    constructor() {}

    deserialize(input: any) {
        Object.assign(this, input);

        return this;
    }
}

I am about to create a new class which will have almost 70 properties.... Is this the best approach?

Afterthought... OR should I actually mix the 2 so I still get intellisense?

export class UserDetails implements Serializable<UserDetails>{
    public _id: number;
    public bio: string;
    public created_at: string;
    public display_name: string;
    public email: string;
    public email_verified: boolean;
    public logo: string;
    public name: string;
    public notifications: Object;
    public partnered: boolean;
    public twitter_connected: boolean;
    public type: string;
    public updated_at: string;

    constructor() {}

    deserialize(input: any) {
        Object.assign(this, input);

        return this;
    }
}

Body:
In my opinion, having the public class level fields would be beneficial for two reasons:

It should provide intellisense.

Using any non declared field, should raise an error (this is also applicable if no field is declared). Note that using Object.assign can add non declared fields to the object.

Example (fiddle link):

class Person {
  firstName;
  lastName;

  deserialize(input: any) {
    Object.assign(this, input);
    return this;
  }
}

let p = new Person();
p.deserialize({firstName:"John", lastName:"Doe", sex:"M"});

console.log(p);     //<-- logs: Person { firstName: 'John', lastName: 'Doe', sex: 'M' }
console.log(p.sex); //<-- this logs 'M' to console in JSFiddle.

Note that the the propoerty sex is added to p, however, accessing the property directly like it is done in the 2nd console.log should raise the following compilation error (though it works on JSFiddle, not exactly sure why):

TSError: ⨯ Unable to compile TypeScript

nodesrc\test.ts (13,15): Property 'sex' does not exist on type 'Person'. (2339) ...

So if you would like to go with this kind of type-safety then declaring the fields might be helpful.

Hope this helps.


问:
How to search through POSTed form values using regex and return results
I'm working on a project where all of the members and their info are stored in a JSON file. I'm in the process of creating a search form and I need help on how to iterate through the members and check to see if there's an exact match or a similar match.

The members are stored in a SESSION variable:

```<code>$_SESSION['members'] = json_decode($jsonFile);
</code>```

but I'm uncertain how to use regex to check for matches that are similar (and not just exact). For example, if a member's name is "Jonathan", I'd like that result to be returned even if the user searches "Jon". Is regex the correct approach? Any help will be greatly appreciated - thank you!

-Manoj

答:
If the $jsonFile contents is an array of some sort, you may find preg_grep() of use, though it doesn't work on multidimensional arrays. You might have have to loop over each individual member record and grep the relevant fields yourself, something like:

```<code>foreach ($_SESSION['members'] as $idx => $member) {
     ... match relevant fields...
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm working on a project where all of the members and their info are stored in a JSON file. I'm in the process of creating a search form and I need help on how to iterate through the members and check to see if there's an exact match or a similar match.

The members are stored in a SESSION variable:

$_SESSION['members'] = json_decode($jsonFile);

but I'm uncertain how to use regex to check for matches that are similar (and not just exact). For example, if a member's name is "Jonathan", I'd like that result to be returned even if the user searches "Jon". Is regex the correct approach? Any help will be greatly appreciated - thank you!

-Manoj

Body:
If the $jsonFile contents is an array of some sort, you may find preg_grep() of use, though it doesn't work on multidimensional arrays. You might have have to loop over each individual member record and grep the relevant fields yourself, something like:

foreach ($_SESSION['members'] as $idx => $member) {
     ... match relevant fields...
}


问:
Execution failed for task ':app:mergeDebugResources' & Build errors
In every project I'm getting same following error

Information:Gradle tasks [clean, :app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :app:generateDebugAndroidTestSources]
  Error:Execution failed for task ':app:mergeDebugResources'.
  Error: Some file crunching failed, see logs for details
  Error:Some file crunching failed, see logs for details
  Information:BUILD FAILED

Even if I'm creating new project, without adding anything I'm getting above error, also getting an

Cannot resolve symbol 'R'

in every project.

答:
Please check any resource file is missing or not.

Otherwise go to Build in the top menu and click on Clean Project.

If this also not works then restart Android Studio.


问:
aggregate and concatenate the remaining unique elements in the output
I want to aggregate based on two columns and get the output with all the unique elements in each column. For example, in the dataset below, the blank space are NAs and I want to sum the trips based on o and d (which I did). But the element A in both o and d column does not have its other pair and hence not appearing in output. How can I include A once in both column and make trips 0 (corresponding to all As). The output matrix I want is also attached.
Thanks in advance!

CODE

```<code>df<-read.csv("smallexample.csv",header = TRUE)
df[["trips"]][is.na(df[["trips"]])] <- 0
#aggregating the trips
result1<-aggregate(trips ~o+d, data=df,sum)
#change from long to wide format
result2<-dcast(result1, o ~ d)
</code>```

DATA

```<code>structure(list(o = structure(c(2L, 1L, 4L, 2L, 1L, 5L, 1L, 6L,
2L, 1L, 4L, 5L, 2L, 4L, 6L, 3L), .Label = c("", "A", "B", "C",
"D", "E"), class = "factor"), d = structure(c(1L, 2L, 3L, 1L,
2L, 1L, 2L, 3L, 1L, 2L, 5L, 1L, 1L, 3L, 3L, 4L), .Label = c("",
"A", "B", "C", "E"), class = "factor"), trips = c(2, 3, 4, 5,
1.5, NA, NA, 1, 4, NA, 6, NA, 0.5, 6, 2, 1)), .Names = c("o",
"d", "trips"), class = "data.frame", row.names = c(NA, -16L))
</code>```

OUPUT:

```<code>structure(list(X = structure(1:5, .Label = c("A", "B", "C", "D",
"E"), class = "factor"), A = c(0L, 0L, 0L, 0L, 0L), B = c(0L,
0L, 10L, 0L, 3L), C = c(0L, 1L, 0L, 0L, 0L), D = c(0L, 0L, 0L,
0L, 0L), E = c(0L, 0L, 6L, 0L, 0L)), .Names = c("X", "A", "B",
"C", "D", "E"), class = "data.frame", row.names = c(NA, -5L))
</code>```

答:
Here is another option using data.table

```<code>library(data.table)
dcast(setDT(df1)[, (1:2) := lapply(.SD, factor, levels = LETTERS[1:5]),
       .SDcols = o:d][!is.na(o) & !is.na(d)], o ~d, sum, drop = FALSE)
#   o A  B C D E
#1: A 0  0 0 0 0
#2: B 0  0 1 0 0
#3: C 0 10 0 0 6
#4: D 0  0 0 0 0
#5: E 0  3 0 0 0
</code>```

Body:
I want to aggregate based on two columns and get the output with all the unique elements in each column. For example, in the dataset below, the blank space are NAs and I want to sum the trips based on o and d (which I did). But the element A in both o and d column does not have its other pair and hence not appearing in output. How can I include A once in both column and make trips 0 (corresponding to all As). The output matrix I want is also attached.
Thanks in advance!

CODE

df<-read.csv("smallexample.csv",header = TRUE)
df[["trips"]][is.na(df[["trips"]])] <- 0
#aggregating the trips
result1<-aggregate(trips ~o+d, data=df,sum)
#change from long to wide format
result2<-dcast(result1, o ~ d)

DATA

structure(list(o = structure(c(2L, 1L, 4L, 2L, 1L, 5L, 1L, 6L,
2L, 1L, 4L, 5L, 2L, 4L, 6L, 3L), .Label = c("", "A", "B", "C",
"D", "E"), class = "factor"), d = structure(c(1L, 2L, 3L, 1L,
2L, 1L, 2L, 3L, 1L, 2L, 5L, 1L, 1L, 3L, 3L, 4L), .Label = c("",
"A", "B", "C", "E"), class = "factor"), trips = c(2, 3, 4, 5,
1.5, NA, NA, 1, 4, NA, 6, NA, 0.5, 6, 2, 1)), .Names = c("o",
"d", "trips"), class = "data.frame", row.names = c(NA, -16L))

OUPUT:

structure(list(X = structure(1:5, .Label = c("A", "B", "C", "D",
"E"), class = "factor"), A = c(0L, 0L, 0L, 0L, 0L), B = c(0L,
0L, 10L, 0L, 3L), C = c(0L, 1L, 0L, 0L, 0L), D = c(0L, 0L, 0L,
0L, 0L), E = c(0L, 0L, 6L, 0L, 0L)), .Names = c("X", "A", "B",
"C", "D", "E"), class = "data.frame", row.names = c(NA, -5L))

Body:
Here is another option using data.table

library(data.table)
dcast(setDT(df1)[, (1:2) := lapply(.SD, factor, levels = LETTERS[1:5]),
       .SDcols = o:d][!is.na(o) & !is.na(d)], o ~d, sum, drop = FALSE)
#   o A  B C D E
#1: A 0  0 0 0 0
#2: B 0  0 1 0 0
#3: C 0 10 0 0 6
#4: D 0  0 0 0 0
#5: E 0  3 0 0 0


问:
Java algorithm to check to detect if all characters in string are unique not working with Hashmap? Is there a better solution using map operators?
I have the following code for detecting if all the characters in a string are unique, return true if unique or false if not. Why do the characters in my map never increment beyond 1?

```<code>public static boolean hasUniqueChars(String word) {
    HashMap<String, Integer> map = new HashMap<>();
    for(int i = 0; i < word.length(); i++) {
        if(map.get(word.charAt(i)) == null) { // this appears to always equal null even though there is data after the first instance of a character is put into it?
            map.put(""+word.charAt(i), 1);
        } else {
            map.put(""+word.charAt(i), (Integer)map.get(""+word.charAt(i))+1);
        }
    }
    Iterator it = map.entrySet().iterator();
    while(it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        if((Integer)pair.getValue() != 1) {
            return false;
        }
    }
    return true;

}
</code>```

Also is there a more "reactive" way to do this like maybe using map operators for each of the chars to help determine whether there is a duplicate character?

答:
Try this.</p>

```<code>public static boolean hasUniqueChars(String word) {
    return word.chars().distinct().count() == word.length();
}
</code>```

Body:
I have the following code for detecting if all the characters in a string are unique, return true if unique or false if not. Why do the characters in my map never increment beyond 1?

public static boolean hasUniqueChars(String word) {
    HashMap<String, Integer> map = new HashMap<>();
    for(int i = 0; i < word.length(); i++) {
        if(map.get(word.charAt(i)) == null) { // this appears to always equal null even though there is data after the first instance of a character is put into it?
            map.put(""+word.charAt(i), 1);
        } else {
            map.put(""+word.charAt(i), (Integer)map.get(""+word.charAt(i))+1);
        }
    }
    Iterator it = map.entrySet().iterator();
    while(it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        if((Integer)pair.getValue() != 1) {
            return false;
        }
    }
    return true;

}

Also is there a more "reactive" way to do this like maybe using map operators for each of the chars to help determine whether there is a duplicate character?

Body:
Try this.

public static boolean hasUniqueChars(String word) {
    return word.chars().distinct().count() == word.length();
}


问:
Webpack frozen during '91% additional asset processing'
I've recently added a great UI library called 'Antd' to my project.
https://ant.design/docs/react/introduce

It worked flawlessly in my dev environment and I've implemented a lot of components into my Electron App. Now when I come to package it for release, my Webpack is completely stuck at the '91% additional asset processing' stage and eventually V8 runs out of memory. I have no further output. Is there anywhere I can get more detailed logs to determine whats going on?

The problematic web pack config is below, its heavily based off the React Electron Boilerplate GitHub repo and its served me extremely well up until now.

```<code>import path from 'path';
import webpack from 'webpack';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import merge from 'webpack-merge';
import BabiliPlugin from 'babili-webpack-plugin';
import baseConfig from './webpack.config.base';

export default merge.smart(baseConfig, {
  // devtool: 'source-map',

  target: 'electron-renderer',

  entry: ['babel-polyfill', './app/index'],

  output: {
    path: path.join(__dirname, 'app/dist'),
    publicPath: '../dist/'
  },

  module: {
    rules: [
      // Extract all .global.css to style.css as is
      {
        test: /\.global\.css$/,
        use: ExtractTextPlugin.extract({
          use: 'css-loader',
          fallback: 'style-loader',
        })
      },
      // Pipe other styles through css modules and append to style.css
      {
        test: /^((?!\.global).)*\.css$/,
        use: ExtractTextPlugin.extract({
          use: {
            loader: 'css-loader',
            options: {
              modules: true,
              importLoaders: 1,
              localIdentName: '[name]__[local]__[hash:base64:5]',
            }
          }
        }),
      },
      // Add SASS support  - compile all .global.scss files and pipe it to style.css
      {
        test: /\.global\.scss$/,
        use: ExtractTextPlugin.extract({
          use: [
            {
              loader: 'css-loader'
            },
            {
              loader: 'sass-loader'
            }
          ],
          fallback: 'style-loader',
        })
      },
      // Add SASS support  - compile all other .scss files and pipe it to style.css
      {
        test: /^((?!\.global).)*\.scss$/,
        use: ExtractTextPlugin.extract({
          use: [{
            loader: 'css-loader',
            options: {
              modules: true,
              importLoaders: 1,
              localIdentName: '[name]__[local]__[hash:base64:5]',
            }
          },
          {
            loader: 'sass-loader'
          }]
        }),
      },
      // WOFF Font
      {
        test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 10000,
            mimetype: 'application/font-woff',
          }
        },
      },
      // WOFF2 Font
      {
        test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 10000,
            mimetype: 'application/font-woff',
          }
        }
      },
      // TTF Font
      {
        test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 10000,
            mimetype: 'application/octet-stream'
          }
        }
      },
      // EOT Font
      {
        test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
        use: 'file-loader',
      },
      // SVG Font
      {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 10000,
            mimetype: 'image/svg+xml',
          }
        }
      },
      // Common Image Formats
      {
        test: /\.(?:ico|gif|png|jpg|jpeg|webp)$/,
        use: 'url-loader',
      }
    ]
  },

  plugins: [
    /**
     * Create global constants which can be configured at compile time.
     *
     * Useful for allowing different behaviour between development builds and
     * release builds
     *
     * NODE_ENV should be production so that modules do not perform certain
     * development checks
     */
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production')
    }),

    /**
     * Babli is an ES6+ aware minifier based on the Babel toolchain (beta)
     */
    new BabiliPlugin(),

    new ExtractTextPlugin('style.css'),

    new BundleAnalyzerPlugin({
      analyzerMode: process.env.OPEN_ANALYZER === 'true' ? 'server' : 'disabled',
      openAnalyzer: process.env.OPEN_ANALYZER === 'true'
    }),
  ],
});
</code>```

And here is the stack trace from the webpack output;

```<code>16706ms building modules
137ms sealing
10ms optimizing
0ms basic module optimization
17ms module optimization
1ms advanced module optimization
0ms basic chunk optimization
0ms chunk optimization
25ms advanced chunk optimization
2162ms building modules
0ms module and chunk tree optimization
15ms module reviving
8ms module order optimization
7ms module id optimization
4ms chunk reviving
0ms chunk order optimization
22ms chunk id optimization
55ms hashing
1ms module assets processing
109ms chunk assets processing
4ms additional chunk assets processing
1ms recording
 91% additional asset processing
<--- Last few GCs --->

[1279:0x103801600]   485158 ms: Mark-sweep 1339.5 (1509.3) -> 1339.5 (1509.8) MB, 2810.3 / 0.0 ms  allocation failure GC in old space requested
[1279:0x103801600]   488159 ms: Mark-sweep 1339.5 (1509.8) -> 1339.4 (1463.3) MB, 3001.2 / 0.0 ms  last resort
[1279:0x103801600]   491070 ms: Mark-sweep 1339.4 (1463.3) -> 1339.4 (1456.3) MB, 2910.5 / 0.0 ms  last resort
<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 0x2511c21a66a1 <JS Object>
    1: set [native weak-collection.js:~43] [pc=0x2de514c759df](this=0x28fdfc5c2d29 <JS WeakMap>,m=0x267d0ab55949 <a Node with map 0x2b746f329501>,o=0x1fe36e4c1f89 <JS Array[0]>)
    2: get [/Users/alexmorris/Documents/FCA/eBundleViewer/node_modules/babel-traverse/lib/path/index.js:~76] [pc=0x2de515031fe1](this=0x13d83be85de1 <JS Function NodePath (SharedFunctionInfo 0x7dd00c3dae1)>,_ref=0x2129c...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
 1: node::Abort() [/usr/local/bin/node]
</code>```

Any help would be HUGELY appreciated! Thanks,
Alex

答:
Try setting devtool: 'cheap'. If you have a large app, generating sourcemaps can be expensive. Its a temporary solution until this issue fully gets gets

Also it seems like this project is based off of electron-react-boilerplate, which I am a core maintainer of. You should open bug reports/issues there.

Body:
I've recently added a great UI library called 'Antd' to my project.
https://ant.design/docs/react/introduce

It worked flawlessly in my dev environment and I've implemented a lot of components into my Electron App. Now when I come to package it for release, my Webpack is completely stuck at the '91% additional asset processing' stage and eventually V8 runs out of memory. I have no further output. Is there anywhere I can get more detailed logs to determine whats going on?

The problematic web pack config is below, its heavily based off the React Electron Boilerplate GitHub repo and its served me extremely well up until now.

import path from 'path';
import webpack from 'webpack';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import merge from 'webpack-merge';
import BabiliPlugin from 'babili-webpack-plugin';
import baseConfig from './webpack.config.base';

export default merge.smart(baseConfig, {
  // devtool: 'source-map',

  target: 'electron-renderer',

  entry: ['babel-polyfill', './app/index'],

  output: {
    path: path.join(__dirname, 'app/dist'),
    publicPath: '../dist/'
  },

  module: {
    rules: [
      // Extract all .global.css to style.css as is
      {
        test: /\.global\.css$/,
        use: ExtractTextPlugin.extract({
          use: 'css-loader',
          fallback: 'style-loader',
        })
      },
      // Pipe other styles through css modules and append to style.css
      {
        test: /^((?!\.global).)*\.css$/,
        use: ExtractTextPlugin.extract({
          use: {
            loader: 'css-loader',
            options: {
              modules: true,
              importLoaders: 1,
              localIdentName: '[name]__[local]__[hash:base64:5]',
            }
          }
        }),
      },
      // Add SASS support  - compile all .global.scss files and pipe it to style.css
      {
        test: /\.global\.scss$/,
        use: ExtractTextPlugin.extract({
          use: [
            {
              loader: 'css-loader'
            },
            {
              loader: 'sass-loader'
            }
          ],
          fallback: 'style-loader',
        })
      },
      // Add SASS support  - compile all other .scss files and pipe it to style.css
      {
        test: /^((?!\.global).)*\.scss$/,
        use: ExtractTextPlugin.extract({
          use: [{
            loader: 'css-loader',
            options: {
              modules: true,
              importLoaders: 1,
              localIdentName: '[name]__[local]__[hash:base64:5]',
            }
          },
          {
            loader: 'sass-loader'
          }]
        }),
      },
      // WOFF Font
      {
        test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 10000,
            mimetype: 'application/font-woff',
          }
        },
      },
      // WOFF2 Font
      {
        test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 10000,
            mimetype: 'application/font-woff',
          }
        }
      },
      // TTF Font
      {
        test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 10000,
            mimetype: 'application/octet-stream'
          }
        }
      },
      // EOT Font
      {
        test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
        use: 'file-loader',
      },
      // SVG Font
      {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 10000,
            mimetype: 'image/svg+xml',
          }
        }
      },
      // Common Image Formats
      {
        test: /\.(?:ico|gif|png|jpg|jpeg|webp)$/,
        use: 'url-loader',
      }
    ]
  },

  plugins: [
    /**
     * Create global constants which can be configured at compile time.
     *
     * Useful for allowing different behaviour between development builds and
     * release builds
     *
     * NODE_ENV should be production so that modules do not perform certain
     * development checks
     */
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production')
    }),

    /**
     * Babli is an ES6+ aware minifier based on the Babel toolchain (beta)
     */
    new BabiliPlugin(),

    new ExtractTextPlugin('style.css'),

    new BundleAnalyzerPlugin({
      analyzerMode: process.env.OPEN_ANALYZER === 'true' ? 'server' : 'disabled',
      openAnalyzer: process.env.OPEN_ANALYZER === 'true'
    }),
  ],
});

And here is the stack trace from the webpack output;

16706ms building modules
137ms sealing
10ms optimizing
0ms basic module optimization
17ms module optimization
1ms advanced module optimization
0ms basic chunk optimization
0ms chunk optimization
25ms advanced chunk optimization
2162ms building modules
0ms module and chunk tree optimization
15ms module reviving
8ms module order optimization
7ms module id optimization
4ms chunk reviving
0ms chunk order optimization
22ms chunk id optimization
55ms hashing
1ms module assets processing
109ms chunk assets processing
4ms additional chunk assets processing
1ms recording
 91% additional asset processing
<--- Last few GCs --->

[1279:0x103801600]   485158 ms: Mark-sweep 1339.5 (1509.3) -> 1339.5 (1509.8) MB, 2810.3 / 0.0 ms  allocation failure GC in old space requested
[1279:0x103801600]   488159 ms: Mark-sweep 1339.5 (1509.8) -> 1339.4 (1463.3) MB, 3001.2 / 0.0 ms  last resort
[1279:0x103801600]   491070 ms: Mark-sweep 1339.4 (1463.3) -> 1339.4 (1456.3) MB, 2910.5 / 0.0 ms  last resort
<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 0x2511c21a66a1 <JS Object>
    1: set [native weak-collection.js:~43] [pc=0x2de514c759df](this=0x28fdfc5c2d29 <JS WeakMap>,m=0x267d0ab55949 ,o=0x1fe36e4c1f89 <JS Array[0]>)
    2: get [/Users/alexmorris/Documents/FCA/eBundleViewer/node_modules/babel-traverse/lib/path/index.js:~76] [pc=0x2de515031fe1](this=0x13d83be85de1 <JS Function NodePath (SharedFunctionInfo 0x7dd00c3dae1)>,_ref=0x2129c...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
 1: node::Abort() [/usr/local/bin/node]

Any help would be HUGELY appreciated! Thanks,
Alex


问:
How to store username entered into database table
I am trying to store username entered during login in the table Login Details. I am keeping track of users trying to login into the application. My code crashes at conn.Open. Please help me with this. Thanks in advance.

Here is the code I have written in Homecontroller:

```<code>public  ActionResult Login(LoginViewModel model, string returnUrl)
        {

            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var wwid = ActiveDirectoryUserHelper.returnWWid(model.UserName, model.UserName.Substring(model.UserName.IndexOf("\\")+1), model.Password);
            if(wwid==null)
            {
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
            }
            else
            {
                Session["UserId"] = model.UserName.Substring(model.UserName.IndexOf("\\") + 1);
                Session["UserPassword"] = model.Password;
                ViewBag.userId = Crypto.EncryptData(model.UserName.Substring(model.UserName.IndexOf("\\") + 1));
                ViewBag.pwd = Crypto.EncryptData(model.Password);
            }

            SqlConnection conn = new SqlConnection(@"data source = XYZ,1433;initial catalog=Application;integrated security=True");

            string sql = "INSERT INTO LoginDetails (username) values (@username)";
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.Add("@username", System.Data.SqlDbType.VarChar, 50).Value = model.UserName;
            //cmd.Parameters["@username"].Value = model.UserName;
            cmd.ExecuteNonQuery();

            return View("Management");

        }
</code>```

答:
It looks like something is wrong with the connection string you are using.

Make sure you are passing correct ServerName and database name.

Also please double check if you want to use Windows Authentication or have any user configured in the database to login with.

You can also check the following URL to know more about the connection string:

https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx

https://www.connectionstrings.com/sql-server/

If you are still facing the error, please share the error detail here.

Body:
I am trying to store username entered during login in the table Login Details. I am keeping track of users trying to login into the application. My code crashes at conn.Open. Please help me with this. Thanks in advance.

Here is the code I have written in Homecontroller:

public  ActionResult Login(LoginViewModel model, string returnUrl)
        {

            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var wwid = ActiveDirectoryUserHelper.returnWWid(model.UserName, model.UserName.Substring(model.UserName.IndexOf("\\")+1), model.Password);
            if(wwid==null)
            {
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
            }
            else
            {
                Session["UserId"] = model.UserName.Substring(model.UserName.IndexOf("\\") + 1);
                Session["UserPassword"] = model.Password;
                ViewBag.userId = Crypto.EncryptData(model.UserName.Substring(model.UserName.IndexOf("\\") + 1));
                ViewBag.pwd = Crypto.EncryptData(model.Password);
            }

            SqlConnection conn = new SqlConnection(@"data source = XYZ,1433;initial catalog=Application;integrated security=True");

            string sql = "INSERT INTO LoginDetails (username) values (@username)";
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.Add("@username", System.Data.SqlDbType.VarChar, 50).Value = model.UserName;
            //cmd.Parameters["@username"].Value = model.UserName;
            cmd.ExecuteNonQuery();

            return View("Management");

        }


问:
Recommendations regarding TextField in modal Dialog
What are the recommendations for inputting texts and especially for entering texts in modal dialogues?

When having a modal dialog with a text field one probably wishes to start editing immediately when the dialog is shown - what's the best way to do that?

In the past I received recommendations like not to use text fields in modal dialogs. Is this still true? What are the alternatives?

That works - but is probably not the way to go:

```<code>            TextField textFieldDialog = new TextField() {
                @Override
                public void paint(Graphics g) {
                    startEditingAsync();
                    super.paint(g);
                }
            };
            Dialog.show(
                    "Text Input",
                    FlowLayout.encloseCenterMiddle(textFieldDialog),
                    Command.create("Cancel", null, (aActionEvent2)->{}),
                    Command.create("OK", null, (aActionEvent2)->{}));
</code>```

答:
The recommendation is not to put a text field in a dialog, modal or otherwise. It's a problematic as the screen sometimes resizes to fit the UI and this doesn't work well at all with dialogs.

You can launch editing using startEditing or startEditingAsync on TextField.

Body:
What are the recommendations for inputting texts and especially for entering texts in modal dialogues?

When having a modal dialog with a text field one probably wishes to start editing immediately when the dialog is shown - what's the best way to do that?

In the past I received recommendations like not to use text fields in modal dialogs. Is this still true? What are the alternatives?

That works - but is probably not the way to go:

            TextField textFieldDialog = new TextField() {
                @Override
                public void paint(Graphics g) {
                    startEditingAsync();
                    super.paint(g);
                }
            };
            Dialog.show(
                    "Text Input",
                    FlowLayout.encloseCenterMiddle(textFieldDialog),
                    Command.create("Cancel", null, (aActionEvent2)->{}),
                    Command.create("OK", null, (aActionEvent2)->{}));


问:
Simple jQuery problem
This one should be easy

I've got this HTML

```<code><table class="PageNumbers">
<tr>
    <td colspan="3">text3
    </td>
</tr>
<tr>
    <td colspan="2">text
    </td>
    <td>text2
    </td>
</tr>
<tr>
    <td>moretext
    </td>
    <td>moretext2
    </td>
<td>moretext3
    </td>
</tr>
</table>
</code>```

I need to change the colspan of the first rows first column to one

This is what i've got

```<code>$('.PageNumbers tr:first td:first').attr('colspan') = '1'
</code>```

Doesn't seem to work though

Any ideas?

Thanks

答:
You should do this:</p>

```<code>$('table.PageNumbers').find('tr:first td:first').attr('colspan', '1');
</code>```

Title: Simple jQuery problem

Body:
This one should be easy

I've got this HTML

    text3

    text

    text2

    moretext

    moretext2

moretext3

I need to change the colspan of the first rows first column to one

This is what i've got

$('.PageNumbers tr:first td:first').attr('colspan') = '1'

Doesn't seem to work though

Any ideas?

Thanks

Body:
You should do this:

$('table.PageNumbers').find('tr:first td:first').attr('colspan', '1');


问:
PHP cURL: how to set body to binary data?
I'm using an API that wants me to send a POST with the binary data from a file as the body of the request. How can I accomplish this using PHP cURL?

The command line equivalent of what I'm trying to achieve is:

```<code>curl --request POST --data-binary "@myimage.jpg" https://myapiurl
</code>```

答:
Try this:</p>

```<code>$postfields = array(
    'upload_file' => '@'.$tmpFile
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url.'/instances');
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);//require php 5.6^
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$postResult = curl_exec($ch);

if (curl_errno($ch)) {
    print curl_error($ch);
}
curl_close($ch);
</code>```

Body:
I'm using an API that wants me to send a POST with the binary data from a file as the body of the request. How can I accomplish this using PHP cURL?

The command line equivalent of what I'm trying to achieve is:

curl --request POST --data-binary "@myimage.jpg" https://myapiurl

Body:
Try this:

$postfields = array(
    'upload_file' => '@'.$tmpFile
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url.'/instances');
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);//require php 5.6^
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$postResult = curl_exec($ch);

if (curl_errno($ch)) {
    print curl_error($ch);
}
curl_close($ch);


问:
laravel with phpexcel using columnIndexFromString
I am current using this

```<code>Excel::create('Export Test',function($excel) use($printData){
    $excel->sheet("Paper Print", function($sheet) use($printData){
        return $sheet->stringFromColumnIndex(5);
    }
}
</code>```

the problem is it says the method doesnt exist.

I have tried PHPExcel_Cell::stringFromColumnIndex(5);

This says PHPExcel_Cell doesnt exist which would make since.

$excel->stringFromColumnIndex(5) also doesnt work because $excel doesnt exist.

From the documentation these methods should be available from both $excel and $sheet.

答:
You just need to add the \ in front of the PHPExcel_Cell class reference because  it doesn't exist in your App\Http\Controllers namespace.

```<code>Excel::create('Export Test',function($excel) use($printData){
    $excel->sheet("Paper Print", function($sheet) use($printData){
        return \PHPExcel_Cell::stringFromColumnIndex(5);
    }
}
</code>```

This ensures you are calling the Class::Method from the Global Namespace - otherwise you could add the line below to the top of your controller to use it without the \ in your anonymous function.

```<code>use PHPExcel_Cell;
</code>```

Body:
I am current using this

Excel::create('Export Test',function($excel) use($printData){
    $excel->sheet("Paper Print", function($sheet) use($printData){
        return $sheet->stringFromColumnIndex(5);
    }
}

the problem is it says the method doesnt exist.

I have tried PHPExcel_Cell::stringFromColumnIndex(5);

This says PHPExcel_Cell doesnt exist which would make since.

$excel->stringFromColumnIndex(5) also doesnt work because $excel doesnt exist.

From the documentation these methods should be available from both $excel and $sheet.

Body:
You just need to add the \ in front of the PHPExcel_Cell class reference because  it doesn't exist in your App\Http\Controllers namespace.

Excel::create('Export Test',function($excel) use($printData){
    $excel->sheet("Paper Print", function($sheet) use($printData){
        return \PHPExcel_Cell::stringFromColumnIndex(5);
    }
}

This ensures you are calling the Class::Method from the Global Namespace - otherwise you could add the line below to the top of your controller to use it without the \ in your anonymous function.

use PHPExcel_Cell;


问:
Why do I need to migrate the test database in Rails?
After creating a new migration file, running the migration, then running my tests I receive:

```<code>Failure/Error: ActiveRecord::Migration.maintain_test_schema!

ActiveRecord::PendingMigrationError:

  Migrations are pending. To resolve this issue, run:

          bin/rails db:migrate RAILS_ENV=test
</code>```

Isn't the following snippet in the rails_helper.rb supposed to apply the migrations to the test database for me?

```<code># Checks for pending migration and applies them before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
</code>```

Update

Here is my config/environments/test.rb as requested:

```<code>Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # The test environment is used exclusively to run your application's
  # test suite. You never need to work with it otherwise. Remember that
  # your test database is "scratch space" for the test suite and is wiped
  # and recreated between test runs. Don't rely on the data there!
  config.cache_classes = true

  # Do not eager load code on boot. This avoids loading your whole application
  # just for the purpose of running a single test. If you are using a tool that
  # preloads Rails for running tests, you may have to set it to true.
  config.eager_load = false

  # Configure public file server for tests with Cache-Control for performance.
  config.public_file_server.enabled = true
  config.public_file_server.headers = {
    'Cache-Control' => 'public, max-age=3600'
  }

  # Show full error reports and disable caching.
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false

  # Raise exceptions instead of rendering exception templates.
  config.action_dispatch.show_exceptions = false

  # Disable request forgery protection in test environment.
  config.action_controller.allow_forgery_protection = false
  config.action_mailer.perform_caching = false

  # Tell Action Mailer not to deliver emails to the real world.
  # The :test delivery method accumulates sent emails in the
  # ActionMailer::Base.deliveries array.
  config.action_mailer.delivery_method = :test

  # Print deprecation notices to the stderr.
  config.active_support.deprecation = :stderr

  # Raises error for missing translations
  # config.action_view.raise_on_missing_translations = true
end
</code>```

答:
You should run rails db:migrate RAILS_ENV=test to update your test DB first.

What this does is that, rather than just raising when the test schema has pending migrations, Rails will try to load the schema. An exception will now only be raised if there are pending migrations afterwards the schema has been loaded.

There are a few caveats to be aware of when using this:

Migrations still need to be run manually; although now this only has to be done in the 'development' environment.

An exception will be raised if the schema has not been initialized. The exception will provide instructions stating rake db:migrate needs to be run.

Body:
After creating a new migration file, running the migration, then running my tests I receive:

Failure/Error: ActiveRecord::Migration.maintain_test_schema!

ActiveRecord::PendingMigrationError:

  Migrations are pending. To resolve this issue, run:

          bin/rails db:migrate RAILS_ENV=test

Isn't the following snippet in the rails_helper.rb supposed to apply the migrations to the test database for me?

# Checks for pending migration and applies them before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!

Update

Here is my config/environments/test.rb as requested:

Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # The test environment is used exclusively to run your application's
  # test suite. You never need to work with it otherwise. Remember that
  # your test database is "scratch space" for the test suite and is wiped
  # and recreated between test runs. Don't rely on the data there!
  config.cache_classes = true

  # Do not eager load code on boot. This avoids loading your whole application
  # just for the purpose of running a single test. If you are using a tool that
  # preloads Rails for running tests, you may have to set it to true.
  config.eager_load = false

  # Configure public file server for tests with Cache-Control for performance.
  config.public_file_server.enabled = true
  config.public_file_server.headers = {
    'Cache-Control' => 'public, max-age=3600'
  }

  # Show full error reports and disable caching.
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false

  # Raise exceptions instead of rendering exception templates.
  config.action_dispatch.show_exceptions = false

  # Disable request forgery protection in test environment.
  config.action_controller.allow_forgery_protection = false
  config.action_mailer.perform_caching = false

  # Tell Action Mailer not to deliver emails to the real world.
  # The :test delivery method accumulates sent emails in the
  # ActionMailer::Base.deliveries array.
  config.action_mailer.delivery_method = :test

  # Print deprecation notices to the stderr.
  config.active_support.deprecation = :stderr

  # Raises error for missing translations
  # config.action_view.raise_on_missing_translations = true
end


问:
want to display duplicate ranks selected along with exactly which ranks are duplicated using javascript/ jquery
Here we added the logic to display which ranks are duplicated but I also want to display exactly which rank is duplicated. Ranks are from 0 to 18.</p>

```<code>function validate(sdd_ejrp_form)
    {
        var duplicateRanksDetected = false;
        var validate_rank_str = ",";
        jq("\[data-dom-id=gsc-containers\]").find("\[data-dom-id=gsc-container\]").each(function (index)
        {     var jqThis = jq(this);
              var gsc_uri = jqThis.attr("data-gsc-data-gsc-uri");
              var prof_lvl_rank = jqThis.find("select\[name='prof-lvl-rank'\]").val();
              jqThis.find("\[data-dom-id=proficiency-level\]").each(function (index2)
             {
               var btn = jq(this);
               if (btn.hasClass("active"))
              {
             if (validate_rank_str.indexOf("," + prof_lvl_rank + ",") != -1)
                     {
                        duplicateRanksDetected = true;
                        return false;
                     } else
                        {
                            validate_rank_str += prof_lvl_rank + ",";
                        }
                    }
                });
            });

            if (duplicateRanksDetected == true)
            {
               // here I want to display exactly which rank is duplicated
               alert("Duplicate ranks detected!");
               return false;
            }
        }
    }
</code>```

答:
It's easy as 3 modifications:</p>

```<code>function validate(sdd_ejrp_form) {

  var duplicateRanksDetected = []; //create an array here

  var validate_rank_str = ",";
  jq("\[data-dom-id=gsc-containers\]").find("\[data-dom-id=gsc-container\]").each(function(index) {
    var jqThis = jq(this);
    var gsc_uri = jqThis.attr("data-gsc-data-gsc-uri");
    var prof_lvl_rank = jqThis.find("select\[name='prof-lvl-rank'\]").val();
    jqThis.find("\[data-dom-id=proficiency-level\]").each(function(index2) {
      var btn = jq(this);
      if (btn.hasClass("active")) {
        if (validate_rank_str.indexOf("," + prof_lvl_rank + ",") != -1) {

          duplicateRanksDetected.push(prof_lvl_rank); // fill the array here

          return false;
        } else {
          validate_rank_str += prof_lvl_rank + ",";
        }
      }
    });
  });

  if (duplicateRanksDetected.length > 0) {
    // here I want to display exactly which rank is duplicated
    alert(
      "Duplicate ranks detected: " +
      duplicateRanksDetected.join(', ') // display the result here
    );
    return false;
  }
}
</code>```

Body:
Here we added the logic to display which ranks are duplicated but I also want to display exactly which rank is duplicated. Ranks are from 0 to 18.

function validate(sdd_ejrp_form)
    {
        var duplicateRanksDetected = false;
        var validate_rank_str = ",";
        jq("\[data-dom-id=gsc-containers\]").find("\[data-dom-id=gsc-container\]").each(function (index)
        {     var jqThis = jq(this);
              var gsc_uri = jqThis.attr("data-gsc-data-gsc-uri");
              var prof_lvl_rank = jqThis.find("select\[name='prof-lvl-rank'\]").val();
              jqThis.find("\[data-dom-id=proficiency-level\]").each(function (index2)
             {
               var btn = jq(this);
               if (btn.hasClass("active"))
              {
             if (validate_rank_str.indexOf("," + prof_lvl_rank + ",") != -1)
                     {
                        duplicateRanksDetected = true;
                        return false;
                     } else
                        {
                            validate_rank_str += prof_lvl_rank + ",";
                        }
                    }
                });
            });

            if (duplicateRanksDetected == true)
            {
               // here I want to display exactly which rank is duplicated
               alert("Duplicate ranks detected!");
               return false;
            }
        }
    }

Body:
It's easy as 3 modifications:

function validate(sdd_ejrp_form) {

  var duplicateRanksDetected = []; //create an array here

  var validate_rank_str = ",";
  jq("\[data-dom-id=gsc-containers\]").find("\[data-dom-id=gsc-container\]").each(function(index) {
    var jqThis = jq(this);
    var gsc_uri = jqThis.attr("data-gsc-data-gsc-uri");
    var prof_lvl_rank = jqThis.find("select\[name='prof-lvl-rank'\]").val();
    jqThis.find("\[data-dom-id=proficiency-level\]").each(function(index2) {
      var btn = jq(this);
      if (btn.hasClass("active")) {
        if (validate_rank_str.indexOf("," + prof_lvl_rank + ",") != -1) {

          duplicateRanksDetected.push(prof_lvl_rank); // fill the array here

          return false;
        } else {
          validate_rank_str += prof_lvl_rank + ",";
        }
      }
    });
  });

  if (duplicateRanksDetected.length > 0) {
    // here I want to display exactly which rank is duplicated
    alert(
      "Duplicate ranks detected: " +
      duplicateRanksDetected.join(', ') // display the result here
    );
    return false;
  }
}


问:
URL not reversing in template Django
Right now I'm having issues getting the url tag to reverse back to my urls. I'm getting the NoReverseMatch. Specifically its

Error

django.urls.exceptions.NoReverseMatch: Reverse for 'documents' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

I've tried narrowing it down using other url names to reverse, but they also don't work. I'm guessing its something to do with calling the url. Any help will be awesome. If anything else is needed just let me know.

urls.py

```<code>"""urls for vivid"""
from django.conf.urls import url
from . import views

app_name = 'website'
urlpatterns = [
    url(r'^$',
        views.login_view,
        name='login'),
    url(r'^dashboard/$',
        views.dashboard_view,
        name='dashboard'),
    url(r'^home/$',
        views.home_view,
        name='home'),
    url(r'^addshow/$',
        views.show_add_view,
        name='addshow'),
    url(r'^regis/$',
        views.regis_view,
        name='regis'),
    url(r'^show/(?P<show_id>[0-9]+)/$',
        views.detail_show_view,
        name='detailshow'),
    url(r'^show/(?P<show_id>[0-9]+)/documents$',
        views.documents_view,
        name='documents'),
    url(r'^addcardcomp/$',
        views.add_card_comp,
        name='addcomp'),
    url(r'^homecardcomp/$',
        views.home_card_comp,
        name='homecomp'),

]
</code>```

templates

```<code><a href="{% url 'documents' show_id=showDocumentID %}"
</code>```

答:
Try to use:

```<code><a href="{% url 'website:documents' show_id=showDocumentID %}"
</code>```

Because: <"app_name">: <"url_name"> is better (don't conflict with other app)

Title: URL not reversing in template Django

Body:
Right now I'm having issues getting the url tag to reverse back to my urls. I'm getting the NoReverseMatch. Specifically its

Error

django.urls.exceptions.NoReverseMatch: Reverse for 'documents' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

I've tried narrowing it down using other url names to reverse, but they also don't work. I'm guessing its something to do with calling the url. Any help will be awesome. If anything else is needed just let me know.

urls.py

"""urls for vivid"""
from django.conf.urls import url
from . import views

app_name = 'website'
urlpatterns = [
    url(r'^$',
        views.login_view,
        name='login'),
    url(r'^dashboard/$',
        views.dashboard_view,
        name='dashboard'),
    url(r'^home/$',
        views.home_view,
        name='home'),
    url(r'^addshow/$',
        views.show_add_view,
        name='addshow'),
    url(r'^regis/$',
        views.regis_view,
        name='regis'),
    url(r'^show/(?P<show_id>[0-9]+)/$',
        views.detail_show_view,
        name='detailshow'),
    url(r'^show/(?P<show_id>[0-9]+)/documents$',
        views.documents_view,
        name='documents'),
    url(r'^addcardcomp/$',
        views.add_card_comp,
        name='addcomp'),
    url(r'^homecardcomp/$',
        views.home_card_comp,
        name='homecomp'),

]

templates

<a href="{% url 'documents' show_id=showDocumentID %}"

Body:
Try to use:

<a href="{% url 'website:documents' show_id=showDocumentID %}"

Because: <"app_name">: <"url_name"> is better (don't conflict with other app)


问:
IndexError: list index out of range python sorting array
i write this code to sort the element of an array but iam getting this error
    line 9, in
    if(a[i]>a[j]):
    IndexError: list index out of range
    the same logic for sorting array elements work with java or c correctly.
     help me to find why this is happening in python .
     is this due to python syntax or another</p>

```<code>from array import *
a=[]
n=int(input("enter number of elements:"))
for i in range(0,n):
    b=input("enter element")
    a.append(b)
for i in range(0,n):
    for j in range(i+1,n):
        if(a[i]>a[j]):
            temp=a[i]
            a[i]=a[j]
            a[j]=temp
print("sorted")
for i in range(0,n-1):
    print(a[i])
    print(a[n-1])
</code>```

答:
Here is some improvement to your current code:

```<code>a =[]
n = int(input("enter number of elements: "))

for i in range(0, n):
    b=input("enter element: ")
    a.append(b)
# You can also, use:
# for i in range(len(a))
for i in range(0, n):
    # Same:
    # for j in range(i+1, len(a))
    for j in range(i+1, n):
        # Be aware:
        # if the data passed to the list a cannot be converted
        # into an integer, this code will throw a ValueError exception
        if int(a[i]) > int(a[j]):
            # You don't need to create a 'temp' variable
            # Python can handle it dynamically
            a[i], a[j] = a[j], a[i]

            print("Sorted")
            print(" ".join(a))
</code>```

Demo:

```<code>enter number of elements: 4
enter element: 5
enter element: 1
enter element: 4
enter element: 3
Sorted
1 5 4 3
Sorted
1 4 5 3
Sorted
1 3 5 4
Sorted
1 3 4 5
</code>```

PS: I recommend you using the Python built-in sorted(), or list.sort() which is a in-place list sorting

Body:
i write this code to sort the element of an array but iam getting this error
    line 9, in
    if(a[i]>a[j]):
    IndexError: list index out of range
    the same logic for sorting array elements work with java or c correctly.
     help me to find why this is happening in python .
     is this due to python syntax or another

from array import *
a=[]
n=int(input("enter number of elements:"))
for i in range(0,n):
    b=input("enter element")
    a.append(b)
for i in range(0,n):
    for j in range(i+1,n):
        if(a[i]>a[j]):
            temp=a[i]
            a[i]=a[j]
            a[j]=temp
print("sorted")
for i in range(0,n-1):
    print(a[i])
    print(a[n-1])

Body:
Here is some improvement to your current code:

a =[]
n = int(input("enter number of elements: "))

for i in range(0, n):
    b=input("enter element: ")
    a.append(b)
# You can also, use:
# for i in range(len(a))
for i in range(0, n):
    # Same:
    # for j in range(i+1, len(a))
    for j in range(i+1, n):
        # Be aware:
        # if the data passed to the list a cannot be converted
        # into an integer, this code will throw a ValueError exception
        if int(a[i]) > int(a[j]):
            # You don't need to create a 'temp' variable
            # Python can handle it dynamically
            a[i], a[j] = a[j], a[i]

            print("Sorted")
            print(" ".join(a))

Demo:

enter number of elements: 4
enter element: 5
enter element: 1
enter element: 4
enter element: 3
Sorted
1 5 4 3
Sorted
1 4 5 3
Sorted
1 3 5 4
Sorted
1 3 4 5

PS: I recommend you using the Python built-in sorted(), or list.sort() which is a in-place list sorting


问:
Scraping https returns an error on Mac but works on Windows
I would like to scrape table from the webpage into R on Mac:

```<code>library("rvest")
url <- "https://www.gpw.pl/wskazniki_spolek_full"
gpw <- url %>%
read_html() %>%
html_nodes(xpath='//table') %>%
html_table(fill = TRUE)
gpw

  Error: Failure when receiving data from the peer
  Error: object 'gpw' not found
</code>```

When I am downloading table from this website in RStudio on Windows or via excel (Data tab -> Get External Data -> From Web) it works.

EDIT:
I have problem with accessing this specific webpage. It seems like there is no connection at all.
When I try same code on different webpage it works.
for example:

```<code>url <- "https://pl.wikipedia.org/wiki/Mapa"
Map <- url %>%
  read_html()
Map
{xml_document}
<html class="client-nojs" lang="pl" dir="ltr">
[1] <head>\n  <meta charset="UTF-8"/>\n  <title>Mapa – Wikipedia, wolna encyklopedia</title>\n  <s ...
[2] <body class="mediawiki ltr sitedir-ltr mw-hide-empty-elt ns-0 ns-subject page-Mapa rootpage-Ma ...
</code>```

I was looking for similar cases but there was no answers for R (only some for php curl).

答:
The following code is working, but if you want a clean table, you will have to carry out some cleaning:</p>

```<code>library("rvest")
url <- "https://www.gpw.pl/wskazniki_spolek_full"
population <- url %>%
  read_html() %>%
  html_nodes(xpath='//table') %>%
  html_table(fill = TRUE)

population
</code>```

Body:
I would like to scrape table from the webpage into R on Mac:

library("rvest")
url <- "https://www.gpw.pl/wskazniki_spolek_full"
gpw <- url %>%
read_html() %>%
html_nodes(xpath='//table') %>%
html_table(fill = TRUE)
gpw

  Error: Failure when receiving data from the peer
  Error: object 'gpw' not found

When I am downloading table from this website in RStudio on Windows or via excel (Data tab -> Get External Data -> From Web) it works.

EDIT:
I have problem with accessing this specific webpage. It seems like there is no connection at all.
When I try same code on different webpage it works.
for example:

url <- "https://pl.wikipedia.org/wiki/Mapa"
Map <- url %>%
  read_html()
Map
{xml_document}

[1] \n  <meta charset="UTF-8"/>\n  <title>Mapa – Wikipedia, wolna encyklopedia</title>\n  <s ...
[2] <body class="mediawiki ltr sitedir-ltr mw-hide-empty-elt ns-0 ns-subject page-Mapa rootpage-Ma ...

I was looking for similar cases but there was no answers for R (only some for php curl).

Body:
The following code is working, but if you want a clean table, you will have to carry out some cleaning:

library("rvest")
url <- "https://www.gpw.pl/wskazniki_spolek_full"
population <- url %>%
  read_html() %>%
  html_nodes(xpath='//table') %>%
  html_table(fill = TRUE)

population


问:
Android Studio error: "Method getText must be called from the UI Thread, currently inferred thread is worker
I got a problem about gettext(), Android studio says that 'method getText must be called from the UI Thread,currently inferred thread is worker'. Can someone help me with this or can someone give an idea how to fix this?
Thanks!

```<code>package com.ibm.watsonvoicetts;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.ibm.watson.developer_cloud.android.library.audio.StreamPlayer;
import com.ibm.watson.developer_cloud.text_to_speech.v1.TextToSpeech;
import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Voice;

public class MainActivity extends AppCompatActivity {

TextView textView;
EditText editText;
Button button;

StreamPlayer streamPlayer;

private TextToSpeech initTextToSpeechService(){
    TextToSpeech service = new TextToSpeech();
    String username = "";
    String password = "";
    service.setUsernameAndPassword(username, password);
    return service;
}

private class WatsonTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... textToSpeak) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                textView.setText("running the Watson thread");
            }
        });

        TextToSpeech textToSpeech = initTextToSpeechService();
        streamPlayer = new StreamPlayer();
        streamPlayer.playStream(textToSpeech.synthesize(
                String.valueOf(editText.getText()),【**here is the problem**】
                Voice.EN_MICHAEL).execute());

        return "text to speech done";
    }

    @Override
    protected void onPostExecute(String result) {
        textView.setText("TTS status: " + result);
    }

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editText = (EditText) findViewById(R.id.editText);
    button = (Button) findViewById(R.id.button);
    textView = (TextView) findViewById(R.id.textView);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("the text to speech: " + editText.getText());
            textView.setText("TTS: " + editText.getText());

            WatsonTask task = new WatsonTask();
            task.execute(new String[]{});

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

}

答:
You shouldn't call getText from an AsyncTask like you're doing. The solution is to pass the value into the task's constructor.

Change

```<code>WatsonTask task = new WatsonTask(editText.getText());
</code>```

and

```<code>private class WatsonTask extends AsyncTask<String, Void, String> {
    private final String text;
    public WatsonTask(String text) {
        super();
        this.text = text;
    }
</code>```

and

```<code>streamPlayer.playStream(textToSpeech.synthesize(
            String.valueOf(text),
            Voice.EN_MICHAEL).execute());
</code>```

Body:
I got a problem about gettext(), Android studio says that 'method getText must be called from the UI Thread,currently inferred thread is worker'. Can someone help me with this or can someone give an idea how to fix this?
Thanks!

package com.ibm.watsonvoicetts;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.ibm.watson.developer_cloud.android.library.audio.StreamPlayer;
import com.ibm.watson.developer_cloud.text_to_speech.v1.TextToSpeech;
import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Voice;

public class MainActivity extends AppCompatActivity {

TextView textView;
EditText editText;
Button button;

StreamPlayer streamPlayer;

private TextToSpeech initTextToSpeechService(){
    TextToSpeech service = new TextToSpeech();
    String username = "";
    String password = "";
    service.setUsernameAndPassword(username, password);
    return service;
}

private class WatsonTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... textToSpeak) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                textView.setText("running the Watson thread");
            }
        });

        TextToSpeech textToSpeech = initTextToSpeechService();
        streamPlayer = new StreamPlayer();
        streamPlayer.playStream(textToSpeech.synthesize(
                String.valueOf(editText.getText()),【**here is the problem**】
                Voice.EN_MICHAEL).execute());

        return "text to speech done";
    }

    @Override
    protected void onPostExecute(String result) {
        textView.setText("TTS status: " + result);
    }

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editText = (EditText) findViewById(R.id.editText);
    button = (Button) findViewById(R.id.button);
    textView = (TextView) findViewById(R.id.textView);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("the text to speech: " + editText.getText());
            textView.setText("TTS: " + editText.getText());

            WatsonTask task = new WatsonTask();
            task.execute(new String[]{});

        }
    });
}

}

Body:
You shouldn't call getText from an AsyncTask like you're doing. The solution is to pass the value into the task's constructor.

Change

WatsonTask task = new WatsonTask(editText.getText());

and

private class WatsonTask extends AsyncTask<String, Void, String> {
    private final String text;
    public WatsonTask(String text) {
        super();
        this.text = text;
    }

and

streamPlayer.playStream(textToSpeech.synthesize(
            String.valueOf(text),
            Voice.EN_MICHAEL).execute());


问:
Could not generate BIRT Report using spudsoft-birt-excel-emitters - Error.InvalidEmitterID
I'm using the BIRT Runtime engine 4.2.1 & following this link.

1.I have moved the following jars to the birt-runtime-4_2_1\ReportEngine\lib folder.
uk.co.spudsoft.birt.emitters.excel_0.8.0.201310230652
commons-codec-1.5
dom4j-1.6.1
poi-3.9-20121203
poi-ooxml-3.9-20121203
poi-ooxml-schemas-3.9-20121203
slf4j-api-1.6.2
stax-api-1.0.1
xmlbeans-2.3.0

2.Changed the code to use spudsoft emitter.`public class RunReport {

```<code>public static void runReport() throws Exception {

    IReportEngine engine = null;
    EngineConfig config = new EngineConfig();
    config.setEngineHome("C:/BIRT/BIRT_2_6_1/birt-runtime-4_2_1/birt-runtime-4_2_1/ReportEngine");
     Platform.startup(config);
    IReportEngineFactory factory = (IReportEngineFactory) Platform
            .createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
    engine = factory.createReportEngine(config);
    IReportRunnable design = engine.openReportDesign("C:/reports/csvReport2.rptdesign");
    IRunAndRenderTask task = engine.createRunAndRenderTask(design);
    IRenderOption options = new RenderOption();
    options.setOutputFormat("xls");
    options.setOutputFileName("C:/reports/native.xls");
    options.setEmitterID( "uk.co.spudsoft.birt.emitters.excel.XlsEmitter" );
    task.setRenderOption(options);
    task.run();
    task.close();

    Platform.shutdown();
    System.out.println("Report Generated Sucessfully!!");
}`
</code>```

Getting the following error while executing the report.

```<code>Jun 05, 2017 9:32:33 AM org.eclipse.birt.report.engine.api.impl.EngineTask setupRenderOption
SEVERE: Error.InvalidEmitterID
org.eclipse.birt.report.engine.api.EngineException: EmitterID uk.co.spudsoft.birt.emitters.excel.XlsEmitter for render option is invalid.
    at org.eclipse.birt.report.engine.api.impl.EngineTask.setupRenderOption(EngineTask.java:2022)
    at org.eclipse.birt.report.engine.api.impl.RunAndRenderTask.doRun(RunAndRenderTask.java:96)
    at org.eclipse.birt.report.engine.api.impl.RunAndRenderTask.run(RunAndRenderTask.java:77)
    at RunReport.runReport(RunReport.java:49)
    at RunReport.main(RunReport.java:58)
Picked up _JAVA_OPTIONS:  -Xmx512M
</code>```

Is there any step or configuration that I miss !

Note: I'm trying to use the spudsoft emitter as with the default emitter, below Error prompts while opening the excel.

File format and extension of 'orders.xls' don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?

答:
I have done couple of changes to make it work !

Step One  Changed the code - to replace default IRenderOption  to EXCELRenderOption

```<code>import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.engine.api.*;
public class RunReport {
    public static void runReport() throws Exception {
        IReportEngine engine = null;
        EngineConfig config = new EngineConfig();
        config.setEngineHome("C:/Projects/My Works Related/BIRT/BIRT_2_6_1/birt-runtime-4_2_1/birt-runtime-4_2_1/ReportEngine");
         Platform.startup(config);
        IReportEngineFactory factory = (IReportEngineFactory) Platform
                .createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
        engine = factory.createReportEngine(config);
        IReportRunnable design = engine.openReportDesign("C:/Projects/My Works Related/Backup From My System and Proton/Backup from Proton/SEM/rk/rk/birt-runtime-Eclipse _workspace2_6_2/eclipse-reporting-helios-SR2-win32/workSpace/ExecuteCSVReport/reports/csvReport2.rptdesign");
        IRunAndRenderTask task = engine.createRunAndRenderTask(design);
        EXCELRenderOption excelOptions = new EXCELRenderOption();
        excelOptions.setOutputFormat("xls");
        excelOptions.setOutputFileName("C:/Projects/My Works Related/Backup From My System and Proton/Backup from Proton/SEM/rk/rk/birt-runtime-Eclipse _workspace2_6_2/eclipse-reporting-helios-SR2-win32/workSpace/ExecuteCSVReport/reports/native.xls");
        excelOptions.setEmitterID( "uk.co.spudsoft.birt.emitters.excel.XlsEmitter" );
        task.setRenderOption(excelOptions);
        task.run();
        task.close();
        Platform.shutdown();
        System.out.println("Report Generated Sucessfully!!");
    }
    public static void main(String[] args) {
        try {
            runReport();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

Step Two  Deleted the poi directory in org.eclipse.birt.runtime_4.2.1.v20120918-1113.jar which was placed in the path birt-runtime-4_2_1\ReportEngine\lib to resolve POI conflict issue.

Body:
I'm using the BIRT Runtime engine 4.2.1 & following this link.

1.I have moved the following jars to the birt-runtime-4_2_1\ReportEngine\lib folder.
uk.co.spudsoft.birt.emitters.excel_0.8.0.201310230652
commons-codec-1.5
dom4j-1.6.1
poi-3.9-20121203
poi-ooxml-3.9-20121203
poi-ooxml-schemas-3.9-20121203
slf4j-api-1.6.2
stax-api-1.0.1
xmlbeans-2.3.0

2.Changed the code to use spudsoft emitter.`public class RunReport {

public static void runReport() throws Exception {

    IReportEngine engine = null;
    EngineConfig config = new EngineConfig();
    config.setEngineHome("C:/BIRT/BIRT_2_6_1/birt-runtime-4_2_1/birt-runtime-4_2_1/ReportEngine");
     Platform.startup(config);
    IReportEngineFactory factory = (IReportEngineFactory) Platform
            .createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
    engine = factory.createReportEngine(config);
    IReportRunnable design = engine.openReportDesign("C:/reports/csvReport2.rptdesign");
    IRunAndRenderTask task = engine.createRunAndRenderTask(design);
    IRenderOption options = new RenderOption();
    options.setOutputFormat("xls");
    options.setOutputFileName("C:/reports/native.xls");
    options.setEmitterID( "uk.co.spudsoft.birt.emitters.excel.XlsEmitter" );
    task.setRenderOption(options);
    task.run();
    task.close();

    Platform.shutdown();
    System.out.println("Report Generated Sucessfully!!");
}`

Getting the following error while executing the report.

Jun 05, 2017 9:32:33 AM org.eclipse.birt.report.engine.api.impl.EngineTask setupRenderOption
SEVERE: Error.InvalidEmitterID
org.eclipse.birt.report.engine.api.EngineException: EmitterID uk.co.spudsoft.birt.emitters.excel.XlsEmitter for render option is invalid.
    at org.eclipse.birt.report.engine.api.impl.EngineTask.setupRenderOption(EngineTask.java:2022)
    at org.eclipse.birt.report.engine.api.impl.RunAndRenderTask.doRun(RunAndRenderTask.java:96)
    at org.eclipse.birt.report.engine.api.impl.RunAndRenderTask.run(RunAndRenderTask.java:77)
    at RunReport.runReport(RunReport.java:49)
    at RunReport.main(RunReport.java:58)
Picked up _JAVA_OPTIONS:  -Xmx512M

Is there any step or configuration that I miss !

Note: I'm trying to use the spudsoft emitter as with the default emitter, below Error prompts while opening the excel.

File format and extension of 'orders.xls' don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?

Body:
I have done couple of changes to make it work !

Step One  Changed the code - to replace default IRenderOption  to EXCELRenderOption

import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.engine.api.*;
public class RunReport {
    public static void runReport() throws Exception {
        IReportEngine engine = null;
        EngineConfig config = new EngineConfig();
        config.setEngineHome("C:/Projects/My Works Related/BIRT/BIRT_2_6_1/birt-runtime-4_2_1/birt-runtime-4_2_1/ReportEngine");
         Platform.startup(config);
        IReportEngineFactory factory = (IReportEngineFactory) Platform
                .createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
        engine = factory.createReportEngine(config);
        IReportRunnable design = engine.openReportDesign("C:/Projects/My Works Related/Backup From My System and Proton/Backup from Proton/SEM/rk/rk/birt-runtime-Eclipse _workspace2_6_2/eclipse-reporting-helios-SR2-win32/workSpace/ExecuteCSVReport/reports/csvReport2.rptdesign");
        IRunAndRenderTask task = engine.createRunAndRenderTask(design);
        EXCELRenderOption excelOptions = new EXCELRenderOption();
        excelOptions.setOutputFormat("xls");
        excelOptions.setOutputFileName("C:/Projects/My Works Related/Backup From My System and Proton/Backup from Proton/SEM/rk/rk/birt-runtime-Eclipse _workspace2_6_2/eclipse-reporting-helios-SR2-win32/workSpace/ExecuteCSVReport/reports/native.xls");
        excelOptions.setEmitterID( "uk.co.spudsoft.birt.emitters.excel.XlsEmitter" );
        task.setRenderOption(excelOptions);
        task.run();
        task.close();
        Platform.shutdown();
        System.out.println("Report Generated Sucessfully!!");
    }
    public static void main(String[] args) {
        try {
            runReport();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Step Two  Deleted the poi directory in org.eclipse.birt.runtime_4.2.1.v20120918-1113.jar which was placed in the path birt-runtime-4_2_1\ReportEngine\lib to resolve POI conflict issue.