问:
Swift - How to detect orientation changes
I want to add two images to single image view (i.e for landscape one image and for portrait another image)but i don't know how to detect orientation changes using swift languages.

I tried this answer but it takes only one image

```<code>override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.currentDevice().orientation.isLandscape.boolValue {
        print("Landscape")
    } else {
        print("Portrait")
    }
}
</code>```

I am new to iOS development,any advice would be greatly appreciated!

答:
You can use viewWillTransition(to:with:) and tap into animate(alongsideTransition:completion:) to get the interface orientation AFTER the transition is complete. You just have to define and implement a protocol similar to this in order to tap into the event. Note that this code was used for a SpriteKit game and your specific implementation may differ.

```<code>protocol CanReceiveTransitionEvents {
    func viewWillTransition(to size: CGSize)
    func interfaceOrientationChanged(to orientation: UIInterfaceOrientation)
}
</code>```

```<code>override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)

        guard
            let skView = self.view as? SKView,
            let canReceiveRotationEvents = skView.scene as? CanReceiveTransitionEvents else { return }

        coordinator.animate(alongsideTransition: nil) { _ in
            if let interfaceOrientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation {
                canReceiveRotationEvents.interfaceOrientationChanged(to: interfaceOrientation)
            }
        }

        canReceiveRotationEvents.viewWillTransition(to: size)
    }
</code>```

You can set breakpoints in these functions and observe that interfaceOrientationChanged(to orientation: UIInterfaceOrientation) is always called after viewWillTransition(to size: CGSize) with the updated orientation.

Body:
I want to add two images to single image view (i.e for landscape one image and for portrait another image)but i don't know how to detect orientation changes using swift languages.

I tried this answer but it takes only one image

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.currentDevice().orientation.isLandscape.boolValue {
        print("Landscape")
    } else {
        print("Portrait")
    }
}

I am new to iOS development,any advice would be greatly appreciated!

Body:
You can use viewWillTransition(to:with:) and tap into animate(alongsideTransition:completion:) to get the interface orientation AFTER the transition is complete. You just have to define and implement a protocol similar to this in order to tap into the event. Note that this code was used for a SpriteKit game and your specific implementation may differ.

protocol CanReceiveTransitionEvents {
    func viewWillTransition(to size: CGSize)
    func interfaceOrientationChanged(to orientation: UIInterfaceOrientation)
}

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)

        guard
            let skView = self.view as? SKView,
            let canReceiveRotationEvents = skView.scene as? CanReceiveTransitionEvents else { return }

        coordinator.animate(alongsideTransition: nil) { _ in
            if let interfaceOrientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation {
                canReceiveRotationEvents.interfaceOrientationChanged(to: interfaceOrientation)
            }
        }

        canReceiveRotationEvents.viewWillTransition(to: size)
    }

You can set breakpoints in these functions and observe that interfaceOrientationChanged(to orientation: UIInterfaceOrientation) is always called after viewWillTransition(to size: CGSize) with the updated orientation.


来源: stackexchange

问:
continue ALLWAYS Illegal in switch in JS but break works fine
```<code>switch ("B")
{
case "A":
    break;
case "B":
    continue;
case "C":
    break;
default:
    break;
}
</code>```

simple correct code in C++, but when made in javascript in stable chrome it just throws an error "Illegal continue statement", looks like continue statement is just disallowed in switch in javascript... Heard about return but it just returns and doesnt continue... So is there a way to continue switch in js?

答:
Actually you can use it in switch inside loops, in this cases break/continue are a useful combo

take a look at this example

```<code>var array = [1, 2, "I am a string", function(){}, {}, 1,2,3]
for(let i in array){
    switch(typeof array[i]) {
    case "number":
        array[i] += " I was a number"
        break; // break from the switch but go on in the for-loop
               // ie. go to *put esclamation mark*
    case "function":
        array[i] = "function"
        // fall through
    default:
        array[i] = `this is a ${JSON.stringify(array[i])} object`
        break; // also here goes to *put esclamation mark*
    case "string":
        continue; // continue with the next iteration of the loop
                  // ie. do not put exclamation mark in this case
    }
    array[i] += "!" // *put esclamation mark*
}
/*
array will become
[ "1 I was a number!", "2 I was a number!", "I am a string", "this is a \"function\" object!", "this is a {} object!", "1 I was a number!", "2 I was a number!", "3 I was a number!" ]
*/
</code>```

ContentLicense: CC BY-SA 3.0

Body:
switch ("B")
{
case "A":
    break;
case "B":
    continue;
case "C":
    break;
default:
    break;
}

simple correct code in C++, but when made in javascript in stable chrome it just throws an error "Illegal continue statement", looks like continue statement is just disallowed in switch in javascript... Heard about return but it just returns and doesnt continue... So is there a way to continue switch in js?

Body:
Actually you can use it in switch inside loops, in this cases break/continue are a useful combo

take a look at this example

var array = [1, 2, "I am a string", function(){}, {}, 1,2,3]
for(let i in array){
    switch(typeof array[i]) {
    case "number":
        array[i] += " I was a number"
        break; // break from the switch but go on in the for-loop
               // ie. go to *put esclamation mark*
    case "function":
        array[i] = "function"
        // fall through
    default:
        array[i] = `this is a ${JSON.stringify(array[i])} object`
        break; // also here goes to *put esclamation mark*
    case "string":
        continue; // continue with the next iteration of the loop
                  // ie. do not put exclamation mark in this case
    }
    array[i] += "!" // *put esclamation mark*
}
/*
array will become
[ "1 I was a number!", "2 I was a number!", "I am a string", "this is a \"function\" object!", "this is a {} object!", "1 I was a number!", "2 I was a number!", "3 I was a number!" ]
*/

ContentLicense: CC BY-SA 4.0


答:
Here's an alternative: (\w+):. In your example it looks like you're trying to get the usernames or whatever that is, after a ( and before a :. \w+ finds "word" characters and the : allows excluding the float that follows.

Also, I can never recommend enough this website for regexp testing:
https://regex101.com/

Title: Regular expression to match a string between parenthesis and comma, but with multiple parenthesis present

Body:
I am trying to use regex to match strings (which are species names+codes, e.g. diadema1479) in a phylogenetic tree in parenthetical notation, but I'm not being successful to deal with all the parenthesis.

Here's a sample of my data

(diadema1479:0.20268621848058304691,longipes1483:0.18941326141716441356):0.05754190478991345892,((sp1_11269:0.08954446656323425402,(davidovi11375:0.12866818058352805232):0.02407442773179632040):0.11326732171695803875,(((S_willeyi:0.16019503647856672690,(((((S_sp2:0.13155607959902493320,S_sp3:0.04602288122852762897):0.09795419683476988548,S_sp4:0.03464730266968370220):0.06696262102745857703,S_sp5_Lombok:0.00000100000050002909):0.01699644302538915949,((S_javensis:0.12205647213742974733,(S_sp6:0.07046365005123975123,((yayukae12168:0.01496242382530112158,(yayukae12109:0.01287526689678352571...

When I use:

/(?<=\()[^:]+/g

It matches, for example, 'diadema1479' and 'davidovi11375', but includes all extra parenthesis in '((((S_sp2'. How can I set it not to match any parenthesis at all?

Thanks!


问:
Regex form to get each person's points as a JS object
I have this string:

Phantom_FR - 5 Points\n\nmineblox17,Dominus_Loading - 0 Points\n\ndavidroks528,beeks567,JohnDoe54631 - 4 Points\n\n\n\n **PLEASE ARCHIVE THIS CARD WHEN YOU ARE FINISHED WITH IT**,

I need it to return something like:

```<code>{"5":["Phantom_FR], "0":[mineblox17, Dominus_Loading]}
</code>```

...and so on. I cant seem to figure it out.

It is encoded to this format in another language so that wouldn't help. How can I extract the information I need?

答:
The pattern /([^\n][\w,]+) - (\d+) Points/g seems sufficient for your use case. This places the comma-delimited list of usernames in the first group and the points in the second group.

Note that it's assumed that the points are pre-grouped and there will be no clashes between them otherwise a key would be overwritten. It also assumes that each username group is preceded by a newline or beginning of string.

Browser JS:

const s = "Phantom_FR - 5 Points\n\nmineblox17,Dominus_Loading - 0 Points\n\ndavidroks528,beeks567,JohnDoe54631 - 4 Points\n\n\n\n **PLEASE ARCHIVE THIS CARD WHEN YOU ARE FINISHED WITH IT**";

const pattern = /([^\n][\w,]+) - (\d+) Points/g;
const usersByPoints = Object.fromEntries([...s.matchAll(pattern)]
  .map(([, users, points]) => [points, users.split(",")]));
console.log(usersByPoints);```
</div>
</div>
</p>

<p>NodeJS:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const s = "Phantom_FR - 5 Points\n\nmineblox17,Dominus_Loading - 0 Points\n\ndavidroks528,beeks567,JohnDoe54631 - 4 Points\n\n\n\n **PLEASE ARCHIVE THIS CARD WHEN YOU ARE FINISHED WITH IT**";

const pattern = /([^\n][\w,]+) - (\d+) Points/g;
const usersByPoints = {};

for (let m; m = pattern.exec(s); usersByPoints[m[2]] = m[1].split(","));

console.log(usersByPoints);</code>```

Body:
I have this string:

Phantom_FR - 5 Points\n\nmineblox17,Dominus_Loading - 0 Points\n\ndavidroks528,beeks567,JohnDoe54631 - 4 Points\n\n\n\n **PLEASE ARCHIVE THIS CARD WHEN YOU ARE FINISHED WITH IT**,

I need it to return something like:

{"5":["Phantom_FR], "0":[mineblox17, Dominus_Loading]}

...and so on. I cant seem to figure it out.

It is encoded to this format in another language so that wouldn't help. How can I extract the information I need?

Body:
The pattern /([^\n][\w,]+) - (\d+) Points/g seems sufficient for your use case. This places the comma-delimited list of usernames in the first group and the points in the second group.

Note that it's assumed that the points are pre-grouped and there will be no clashes between them otherwise a key would be overwritten. It also assumes that each username group is preceded by a newline or beginning of string.

Browser JS:

const s = "Phantom_FR - 5 Points\n\nmineblox17,Dominus_Loading - 0 Points\n\ndavidroks528,beeks567,JohnDoe54631 - 4 Points\n\n\n\n **PLEASE ARCHIVE THIS CARD WHEN YOU ARE FINISHED WITH IT**";

const pattern = /([^\n][\w,]+) - (\d+) Points/g;
const usersByPoints = Object.fromEntries([...s.matchAll(pattern)]
  .map(([, users, points]) => [points, users.split(",")]));
console.log(usersByPoints);

NodeJS:

const s = "Phantom_FR - 5 Points\n\nmineblox17,Dominus_Loading - 0 Points\n\ndavidroks528,beeks567,JohnDoe54631 - 4 Points\n\n\n\n **PLEASE ARCHIVE THIS CARD WHEN YOU ARE FINISHED WITH IT**";

const pattern = /([^\n][\w,]+) - (\d+) Points/g;
const usersByPoints = {};

for (let m; m = pattern.exec(s); usersByPoints[m[2]] = m[1].split(","));

console.log(usersByPoints);


问:
Reading .data files using pandas
Recently i encountered a file with .data extension and i searched google, i found irrelevant answers. I tried different solutions provided by blogs and websites. Nothing seems helpful. I am providing solution which was suggested to me by my colleague. Before i tried reading with read_csv.

```<code>import pandas as pd
data = pd.read_csv("example.data")
</code>```

It processed the csv file but with irrelevant data.

Hope it will be helpful.

答:
The solution to read .data file using pandas is read_fwf(). For better knowledge refer read_fwf.

Example:

```<code>import pandas as pd
data = pd.read_fwf("example.data")
</code>```

By default data will not contains columns because in .data will contain any columns. In order to get column names we have to pass the column names while reading the file.

Example:

```<code>import pandas as pd
data = pd.read_fwf("example.data", names=["col1", "col2"])
print(data.columns)
>>> [col1, col2]
</code>```

Hope this is useful..!!!

Title: Reading .data files using pandas

Body:
Recently i encountered a file with .data extension and i searched google, i found irrelevant answers. I tried different solutions provided by blogs and websites. Nothing seems helpful. I am providing solution which was suggested to me by my colleague. Before i tried reading with read_csv.

import pandas as pd
data = pd.read_csv("example.data")

It processed the csv file but with irrelevant data.

Hope it will be helpful.

Body:
The solution to read .data file using pandas is read_fwf(). For better knowledge refer read_fwf.

Example:

import pandas as pd
data = pd.read_fwf("example.data")

By default data will not contains columns because in .data will contain any columns. In order to get column names we have to pass the column names while reading the file.

Example:

import pandas as pd
data = pd.read_fwf("example.data", names=["col1", "col2"])
print(data.columns)
>>> [col1, col2]

Hope this is useful..!!!


问:
What is the easiest way to ignore a JPA field during persistence?
I'm essentially looking for a "@Ignore" type annotation with which I can stop a particular field from being persisted. How can this be achieved?</p>

答:
There are multiple solutions depending on the entity attribute type.

Basic attributes

Consider you have the following account table:

The account table is mapped to the Account entity like this:

```<code>@Entity(name = "Account")
public class Account {

    @Id
    private Long id;

    @ManyToOne
    private User owner;

    private String iban;

    private long cents;

    private double interestRate;

    private Timestamp createdOn;

    @Transient
    private double dollars;

    @Transient
    private long interestCents;

    @Transient
    private double interestDollars;

    @PostLoad
    private void postLoad() {
        this.dollars = cents / 100D;

        long months = createdOn.toLocalDateTime()
            .until(LocalDateTime.now(), ChronoUnit.MONTHS);
        double interestUnrounded = ( ( interestRate / 100D ) * cents * months ) / 12;
        this.interestCents = BigDecimal.valueOf(interestUnrounded)
            .setScale(0, BigDecimal.ROUND_HALF_EVEN).longValue();

        this.interestDollars = interestCents / 100D;
    }

    //Getters and setters omitted for brevity
}
</code>```

The basic entity attributes are mapped to table columns, so properties like id, iban, cents are basic attributes.

But the dollars, interestCents, and interestDollars are computed properties, so you annotate them with @Transient to exclude them from SELECT, INSERT, UPDATE, and DELETE SQL statements.

So, for basic attributes, you need to use @Transient in order to exclude a given property from being persisted.

Associations

Assuming you have the following post and post_comment tables:

You want to map the latestComment association in the Post entity to the latest PostComment entity that was added.

To do that, you can use the @JoinFormula annotation:

```<code>@Entity(name = "Post")
@Table(name = "post")
public class Post {

    @Id
    private Long id;

    private String title;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinFormula("(" +
        "SELECT pc.id " +
        "FROM post_comment pc " +
        "WHERE pc.post_id = id " +
        "ORDER BY pc.created_on DESC " +
        "LIMIT 1" +
    ")")
    private PostComment latestComment;

    //Getters and setters omitted for brevity
}
</code>```

When fetching the Post entity, you can see that the latestComment is fetched, but if you want to modify it, the change is going to be ignored.

So, for associations, you can use @JoinFormula to ignore the write operations while still allowing reading the association.

@MapsId

Another way to ignore associations that are already mapped by the entity identifier is to use @MapsId.

For instance, consider the following one-to-one table relationship:

The PostDetails entity is mapped like this:

```<code>@Entity(name = "PostDetails")
@Table(name = "post_details")
public class PostDetails {

    @Id
    private Long id;

    @Column(name = "created_on")
    private Date createdOn;

    @Column(name = "created_by")
    private String createdBy;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private Post post;

    public PostDetails() {}

    public PostDetails(String createdBy) {
        createdOn = new Date();
        this.createdBy = createdBy;
    }

    //Getters and setters omitted for brevity
}
</code>```

Notice that both the id attribute and the post association map the same database column, which is the post_details Primary Key column.

To exclude the id attribute, the @MapsId annotation will tell Hibernate that the post association takes care of the table Primary Key column value.

So, when the entity identifier and an association share the same column, you can use @MapsId to ignore the entity identifier attribute and use the association instead.

Using insertable = false, updatable = false

Another option is to use insertable = false, updatable = false for the association which you want to be ignored by Hibernate.

For instance, we can map the previous one-to-one association like this:

```<code>@Entity(name = "PostDetails")
@Table(name = "post_details")
public class PostDetails {

    @Id
    @Column(name = "post_id")
    private Long id;

    @Column(name = "created_on")
    private Date createdOn;

    @Column(name = "created_by")
    private String createdBy;

    @OneToOne
    @JoinColumn(name = "post_id", insertable = false, updatable = false)
    private Post post;

    //Getters and setters omitted for brevity

    public void setPost(Post post) {
        this.post = post;
        if (post != null) {
            this.id = post.getId();
        }
    }
}
</code>```

The insertable and updatable attributes of the @JoinColumn annotation will instruct Hibernate to ignore the post association since the entity identifier takes care of the post_id Primary Key column.

Body:
There are multiple solutions depending on the entity attribute type.

Basic attributes

Consider you have the following account table:

The account table is mapped to the Account entity like this:

@Entity(name = "Account")
public class Account {

    @Id
    private Long id;

    @ManyToOne
    private User owner;

    private String iban;

    private long cents;

    private double interestRate;

    private Timestamp createdOn;

    @Transient
    private double dollars;

    @Transient
    private long interestCents;

    @Transient
    private double interestDollars;

    @PostLoad
    private void postLoad() {
        this.dollars = cents / 100D;

        long months = createdOn.toLocalDateTime()
            .until(LocalDateTime.now(), ChronoUnit.MONTHS);
        double interestUnrounded = ( ( interestRate / 100D ) * cents * months ) / 12;
        this.interestCents = BigDecimal.valueOf(interestUnrounded)
            .setScale(0, BigDecimal.ROUND_HALF_EVEN).longValue();

        this.interestDollars = interestCents / 100D;
    }

    //Getters and setters omitted for brevity
}

The basic entity attributes are mapped to table columns, so properties like id, iban, cents are basic attributes.

But the dollars, interestCents, and interestDollars are computed properties, so you annotate them with @Transient to exclude them from SELECT, INSERT, UPDATE, and DELETE SQL statements.

So, for basic attributes, you need to use @Transient in order to exclude a given property from being persisted.

Associations

Assuming you have the following post and post_comment tables:

You want to map the latestComment association in the Post entity to the latest PostComment entity that was added.

To do that, you can use the @JoinFormula annotation:

@Entity(name = "Post")
@Table(name = "post")
public class Post {

    @Id
    private Long id;

    private String title;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinFormula("(" +
        "SELECT pc.id " +
        "FROM post_comment pc " +
        "WHERE pc.post_id = id " +
        "ORDER BY pc.created_on DESC " +
        "LIMIT 1" +
    ")")
    private PostComment latestComment;

    //Getters and setters omitted for brevity
}

When fetching the Post entity, you can see that the latestComment is fetched, but if you want to modify it, the change is going to be ignored.

So, for associations, you can use @JoinFormula to ignore the write operations while still allowing reading the association.

@MapsId

Another way to ignore associations that are already mapped by the entity identifier is to use @MapsId.

For instance, consider the following one-to-one table relationship:

The PostDetails entity is mapped like this:

@Entity(name = "PostDetails")
@Table(name = "post_details")
public class PostDetails {

    @Id
    private Long id;

    @Column(name = "created_on")
    private Date createdOn;

    @Column(name = "created_by")
    private String createdBy;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private Post post;

    public PostDetails() {}

    public PostDetails(String createdBy) {
        createdOn = new Date();
        this.createdBy = createdBy;
    }

    //Getters and setters omitted for brevity
}

Notice that both the id attribute and the post association map the same database column, which is the post_details Primary Key column.

To exclude the id attribute, the @MapsId annotation will tell Hibernate that the post association takes care of the table Primary Key column value.

So, when the entity identifier and an association share the same column, you can use @MapsId to ignore the entity identifier attribute and use the association instead.

Using insertable = false, updatable = false

Another option is to use insertable = false, updatable = false for the association which you want to be ignored by Hibernate.

For instance, we can map the previous one-to-one association like this:

@Entity(name = "PostDetails")
@Table(name = "post_details")
public class PostDetails {

    @Id
    @Column(name = "post_id")
    private Long id;

    @Column(name = "created_on")
    private Date createdOn;

    @Column(name = "created_by")
    private String createdBy;

    @OneToOne
    @JoinColumn(name = "post_id", insertable = false, updatable = false)
    private Post post;

    //Getters and setters omitted for brevity

    public void setPost(Post post) {
        this.post = post;
        if (post != null) {
            this.id = post.getId();
        }
    }
}

The insertable and updatable attributes of the @JoinColumn annotation will instruct Hibernate to ignore the post association since the entity identifier takes care of the post_id Primary Key column.


问:
CNN Object detection: How to reduce high false positive rates
I am currently using Faster RCNN with inception v2 on Tensorflow object detection API on WIDER-FACE data, i have a lot of false positives with high scores (>0.98, so setting a higher score threshold won't help).
I have already assigned Hard Example Mining in my code but it doesn't help to much.
For image preprocessing, I randomly crop an area from the original image using tf.image.sample_distorted_bounding_box and resize it to 300*300. The resized image will be randomly flipped by a probability of 0.5

I set batch size to 32 and for each image the ratio of positive:negative in hard negative mining operation is 32:32. I set IoU > 0.5 as positive and IoU < 0.3 as negative. For samples that IoU between 0.5 and 0.3 are ignored

Can anyone help me with this? Many thanks!

答: You can also try increasing the NMS threshold for RPN.</p>


问:
Basic Select with Laravel Eloquent do not work
I have 2 table: User & Demands. Inside the table Demands, I have the user_id as a foreign key.
The User log in with a name (which I have throught the Session).
What I want to do is:
  - Have the name of the User (his log in)-> since I do not have the session implemented, I write the name directly inside the code.
  - Search his ID thanks to his name.
  - Search all of his demands with his id.

```<code>  $name = "Jason";
  $UserID = User::select('id')->where('name', '=', $name)->get();
  $User= User::find($UserID);
  $demands = Demand::where('user_id', '=', $UserID)->get();
  echo $demands;
</code>```

My array is then empty. But inside my database, I do have 3 demands of this user_id...

Do you guys have any clue please ?

Cordially.

答:
Please change

```<code>$UserID = User::select('id')->where('name', '=', $name)->get();
</code>```

to

```<code>$UserID = User::select('id')->where('name', '=', $name)->first()->id;
</code>```

Body:
I have 2 table: User & Demands. Inside the table Demands, I have the user_id as a foreign key.
The User log in with a name (which I have throught the Session).
What I want to do is:
  - Have the name of the User (his log in)-> since I do not have the session implemented, I write the name directly inside the code.
  - Search his ID thanks to his name.
  - Search all of his demands with his id.

  $name = "Jason";
  $UserID = User::select('id')->where('name', '=', $name)->get();
  $User= User::find($UserID);
  $demands = Demand::where('user_id', '=', $UserID)->get();
  echo $demands;

My array is then empty. But inside my database, I do have 3 demands of this user_id...

Do you guys have any clue please ?

Cordially.

Body:
Please change

$UserID = User::select('id')->where('name', '=', $name)->get();

to

$UserID = User::select('id')->where('name', '=', $name)->first()->id;


问:
Cannot insert row into table through create action
I'm sure there has to be a very simple solution to my problem but i don't know why i cant seem to put my finger on it, the problem is that I'm trying to submit a form but every time i submit the form the create action controller gives the following error

Mysql2::Error: Column 'preffered_players' cannot be null: INSERT INTO saved_sessions (preffered_players, session_id, preffered_opponents, game_id, game_type, opponents_list, banned_players, players_list) VALUES (NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)

how ever all these values that the error says are null are passed through parameters as soon as the form is submitted, can anyone tell me how to use the parameter values that i get from the form to fill in the little nulls in my query, create controller is as follow

```<code>def create
    opponents_list = params[:opponents_list]
    banned_players = params[:banned_players]
    game_type = params[:game_type]
    session_id = params[:session_id]
    preffered_opponents = params[:preffered_opponents]
    game_id = params[:game_id]
    players_list = params[:players_list]
    preffered_players = params[:preffered_players]

    @saved_sessions = SavedSession.new(params[:saved_sessions])

    respond_to do |format|
      if @saved_sessions.save
        format.html { redirect_to(@game, :notice => 'Game was successfully created.') }
        format.xml  { render :xml => @game, :status => :created, :location => @game }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @game.errors, :status => :unprocessable_entity }
      end
    end
  end
</code>```

thanks for any advice...

i'm including the form code however its very messy(its a huge form) plus its in haml :)

```<code>- form_tag('/saved_sessions',:method => :post, :id => "new_game") do
.select_option
  .list_col1
    .fl
      %img{:alt => "image", :border => "0", :src => "/images/happy_face.png"}/
    .blue_col
      = text_field_tag :preffered_opponents, "", :class => :blue_bar
    .clr
  .list_col2
    .list_col2_top_row
      .radio_row
        .fl
          %input{:type => "radio", :name => "battle_scale", :value => "3"}
        .fl 3 vs 3
        .fl
          %input{:type => "radio", :name => "battle_scale", :value => "5"}
        .fl 5 vs 5
        .clr
      %div
        .fl
          %img{:alt => "image", :border => "0", :src => "/images/sad_face.png"}/
        .fl
          /%input#banned_players.white_bar{:type => "text"}/
          = text_field_tag :banned_players, "", :class => :white_bar
        .clr
    .versus_row
      #inputs-vs.versus_col1
        .versus_col_row
          .blue_col
            /%input#input-1-vs.blue_bar{:type => "text"}/
            = text_field_tag 'input-1-vs', "", :class => :blue_bar
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .clr
        .versus_col_row
          .blue_col
            /%input#input-2-vs.blue_bar{:type => "text"}/
            = text_field_tag 'input-2-vs', "", :class => :blue_bar
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .clr
        .versus_col_row
          .blue_col
            /%input#input-3-vs.blue_bar{:type => "text"}/
            = text_field_tag 'input-3-vs', "", :class => :blue_bar
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .clr
        .versus_col_row
          .blue_col
            /%input#input-4-vs.blue_bar{:type => "text"}/
            = text_field_tag 'input-4-vs', "", :class => :blue_bar
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .clr
        .versus_col_row
          .blue_col
            /%input#input-5-vs.blue_bar{:type => "text"}/
            = text_field_tag 'input-5-vs', "", :class => :blue_bar
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .clr
      .versus_col2
        %img{:alt => "0", :border => "0", :src => "/images/vs.png"}/
      #inputs.versus_col1
        .versus_col_row
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .blue_col
            /%input#input-1.pink_bar{:name => "blah", :type => "text"}/
            = text_field_tag 'input-1', "", :class => :pink_bar
          .clr
        .versus_col_row
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .blue_col
            /%input#input-2.pink_bar{:name => "blah", :type => "text"}/
            = text_field_tag 'input-2', "", :class => :pink_bar
          .clr
        .versus_col_row
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .blue_col
            /%input#input-3.pink_bar{:name => "blah", :type => "text"}/
            = text_field_tag 'input-3', "", :class => :pink_bar
          .clr
        .versus_col_row
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .blue_col
            /%input#input-4.pink_bar{:name => "blah", :type => "text"}/
            = text_field_tag 'input-4', "", :class => :pink_bar
          .clr
        .versus_col_row
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .blue_col
            /%input#input-5.pink_bar{:name => "blah", :type => "text"}/
            = text_field_tag 'input-5', "", :class => :pink_bar
          .clr
      .clr
    .session_row
      %p
        %b You can save and share this session by entering your email. A unique code will be sent
      %p.small_text (Session are stored for 30 days)
    .seesion_send_row
      .fl
        /%input.big_white_bar{:type => "text"}/
        = text_field_tag 'email_bar', "", :class => :big_white_bar
      .fl
        %span 2+2=
        %span
        %span
          /%input.small_bar{:type => "text"}/
          = text_field_tag 'code_bar', "", :class => :small_bar
      .fl
        /%a{:href => "#."}
        /%img{:alt => "image", :border => "0", :src => "/images/send_button.png"}/
        = submit_tag("Send")
</code>```

hope this can help you guys better understand the problem..

答:
You seem to be pulling from 2 different places. The block of code at the top of the method is pulling the values from the top level of the incoming params, but then later you initialize a new SavedSession using the params[:saved_sessions] input. The two things don't seem to match...

if saved_sessions.opponents_list is found at opponents_list = params[:opponents_list] in the first line, then when you later try to save params[:saved_sessions], you're getting it from a different spot in the params...

EDIT: so you do not need both of the sets of values you have in the action. if you build your form like this (or at least something like this) you'll get the params correctly and can just blindly send them into SavedSession.new, and then call .save.

```<code>- form_for(@aved_session) do |f|
  -.blue_col
      = f.text_field :preffered_opponents, "", :class => :blue_bar
</code>```

If you allow f.text_field to build the id and name then rails magic will make sure that they are named/id'd correctly and then more rails magic interprets them and builds your input parameters correctly. This will build your params as:

```<code>params = {:saved_session => {:preferred_opponents => "text value" }...
</code>```

Then you can pull those params out:

```<code>saved_session_input = params[:saved_session]
</code>```

and pass them into new just like you are. the difference is that now those parameters are actually IN there.

The way you have it is like this:

```<code>params = {:preferred_opponents => "text value", :saved_session => {:preferred_opponents => nil }...
</code>```

this means you're passing nil in for the expected values for new. Note that you don't actually assign your local values to the new saved_session before calling save.

I hope this is clearer.

Body:
I'm sure there has to be a very simple solution to my problem but i don't know why i cant seem to put my finger on it, the problem is that I'm trying to submit a form but every time i submit the form the create action controller gives the following error

Mysql2::Error: Column 'preffered_players' cannot be null: INSERT INTO saved_sessions (preffered_players, session_id, preffered_opponents, game_id, game_type, opponents_list, banned_players, players_list) VALUES (NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)

how ever all these values that the error says are null are passed through parameters as soon as the form is submitted, can anyone tell me how to use the parameter values that i get from the form to fill in the little nulls in my query, create controller is as follow

def create
    opponents_list = params[:opponents_list]
    banned_players = params[:banned_players]
    game_type = params[:game_type]
    session_id = params[:session_id]
    preffered_opponents = params[:preffered_opponents]
    game_id = params[:game_id]
    players_list = params[:players_list]
    preffered_players = params[:preffered_players]

    @saved_sessions = SavedSession.new(params[:saved_sessions])

    respond_to do |format|
      if @saved_sessions.save
        format.html { redirect_to(@game, :notice => 'Game was successfully created.') }
        format.xml  { render :xml => @game, :status => :created, :location => @game }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @game.errors, :status => :unprocessable_entity }
      end
    end
  end

thanks for any advice...

i'm including the form code however its very messy(its a huge form) plus its in haml :)

- form_tag('/saved_sessions',:method => :post, :id => "new_game") do
.select_option
  .list_col1
    .fl
      %img{:alt => "image", :border => "0", :src => "/images/happy_face.png"}/
    .blue_col
      = text_field_tag :preffered_opponents, "", :class => :blue_bar
    .clr
  .list_col2
    .list_col2_top_row
      .radio_row
        .fl
          %input{:type => "radio", :name => "battle_scale", :value => "3"}
        .fl 3 vs 3
        .fl
          %input{:type => "radio", :name => "battle_scale", :value => "5"}
        .fl 5 vs 5
        .clr
      %div
        .fl
          %img{:alt => "image", :border => "0", :src => "/images/sad_face.png"}/
        .fl
          /%input#banned_players.white_bar{:type => "text"}/
          = text_field_tag :banned_players, "", :class => :white_bar
        .clr
    .versus_row
      #inputs-vs.versus_col1
        .versus_col_row
          .blue_col
            /%input#input-1-vs.blue_bar{:type => "text"}/
            = text_field_tag 'input-1-vs', "", :class => :blue_bar
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .clr
        .versus_col_row
          .blue_col
            /%input#input-2-vs.blue_bar{:type => "text"}/
            = text_field_tag 'input-2-vs', "", :class => :blue_bar
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .clr
        .versus_col_row
          .blue_col
            /%input#input-3-vs.blue_bar{:type => "text"}/
            = text_field_tag 'input-3-vs', "", :class => :blue_bar
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .clr
        .versus_col_row
          .blue_col
            /%input#input-4-vs.blue_bar{:type => "text"}/
            = text_field_tag 'input-4-vs', "", :class => :blue_bar
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .clr
        .versus_col_row
          .blue_col
            /%input#input-5-vs.blue_bar{:type => "text"}/
            = text_field_tag 'input-5-vs', "", :class => :blue_bar
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .clr
      .versus_col2
        %img{:alt => "0", :border => "0", :src => "/images/vs.png"}/
      #inputs.versus_col1
        .versus_col_row
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .blue_col
            /%input#input-1.pink_bar{:name => "blah", :type => "text"}/
            = text_field_tag 'input-1', "", :class => :pink_bar
          .clr
        .versus_col_row
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .blue_col
            /%input#input-2.pink_bar{:name => "blah", :type => "text"}/
            = text_field_tag 'input-2', "", :class => :pink_bar
          .clr
        .versus_col_row
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .blue_col
            /%input#input-3.pink_bar{:name => "blah", :type => "text"}/
            = text_field_tag 'input-3', "", :class => :pink_bar
          .clr
        .versus_col_row
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .blue_col
            /%input#input-4.pink_bar{:name => "blah", :type => "text"}/
            = text_field_tag 'input-4', "", :class => :pink_bar
          .clr
        .versus_col_row
          .fl
            %img{:alt => "image", :border => "0", :src => "/images/lock.png"}/
          .blue_col
            /%input#input-5.pink_bar{:name => "blah", :type => "text"}/
            = text_field_tag 'input-5', "", :class => :pink_bar
          .clr
      .clr
    .session_row
      %p
        %b You can save and share this session by entering your email. A unique code will be sent
      %p.small_text (Session are stored for 30 days)
    .seesion_send_row
      .fl
        /%input.big_white_bar{:type => "text"}/
        = text_field_tag 'email_bar', "", :class => :big_white_bar
      .fl
        %span 2+2=
        %span
        %span
          /%input.small_bar{:type => "text"}/
          = text_field_tag 'code_bar', "", :class => :small_bar
      .fl
        /%a{:href => "#."}
        /%img{:alt => "image", :border => "0", :src => "/images/send_button.png"}/
        = submit_tag("Send")

hope this can help you guys better understand the problem..

Body:
You seem to be pulling from 2 different places. The block of code at the top of the method is pulling the values from the top level of the incoming params, but then later you initialize a new SavedSession using the params[:saved_sessions] input. The two things don't seem to match...

if saved_sessions.opponents_list is found at opponents_list = params[:opponents_list] in the first line, then when you later try to save params[:saved_sessions], you're getting it from a different spot in the params...

EDIT: so you do not need both of the sets of values you have in the action. if you build your form like this (or at least something like this) you'll get the params correctly and can just blindly send them into SavedSession.new, and then call .save.

- form_for(@aved_session) do |f|
  -.blue_col
      = f.text_field :preffered_opponents, "", :class => :blue_bar

If you allow f.text_field to build the id and name then rails magic will make sure that they are named/id'd correctly and then more rails magic interprets them and builds your input parameters correctly. This will build your params as:

params = {:saved_session => {:preferred_opponents => "text value" }...

Then you can pull those params out:

saved_session_input = params[:saved_session]

and pass them into new just like you are. the difference is that now those parameters are actually IN there.

The way you have it is like this:

params = {:preferred_opponents => "text value", :saved_session => {:preferred_opponents => nil }...

this means you're passing nil in for the expected values for new. Note that you don't actually assign your local values to the new saved_session before calling save.

I hope this is clearer.


问:
How to convert strings of Year-Mon to the correct date format when exporting data in R?
I'm trying to ensure that the As_of_Dt converts to date correctly when I export the data from R as a csv. Currently, when I export the data to excel. It converts the As_of_Dt incorrectly. The month basically stays the same but the year becomes the day and the year becomes the current year (2020). If the as_of_dt is 18-Jan it becomes 1/18/20 in excel. I'm trying to prevent this from happening.

I would like this column to export like:
1/1/18 when the string is "18-Jan"

Currently, I tried

```<code>Data$As_of_Dt2<- zoo::as.Date(zoo::as.yearmon(Data$As_of_Dt, "%y-%b"))
</code>```

But there were some values that were NA in this new column I made.

Below you will find all the possible dates for the column As_of_Dt.

Update: I figured out that the date can sometimes be Jan-2018 or 2018-Jan. Is there a function that can convert these two situations into 1/1/18?

Body:
I'm trying to ensure that the As_of_Dt converts to date correctly when I export the data from R as a csv. Currently, when I export the data to excel. It converts the As_of_Dt incorrectly. The month basically stays the same but the year becomes the day and the year becomes the current year (2020). If the as_of_dt is 18-Jan it becomes 1/18/20 in excel. I'm trying to prevent this from happening.

I would like this column to export like:
1/1/18 when the string is "18-Jan"

Currently, I tried

Data$As_of_Dt2<- zoo::as.Date(zoo::as.yearmon(Data$As_of_Dt, "%y-%b"))

But there were some values that were NA in this new column I made.

Below you will find all the possible dates for the column As_of_Dt.

Update: I figured out that the date can sometimes be Jan-2018 or 2018-Jan. Is there a function that can convert these two situations into 1/1/18?

Body:
We can use as.yearmon

library(zoo)
as.Date( as.yearmon(dat, "%d-%b"))
#[1] "2020-11-01" "2020-11-01" "2020-01-01" "2020-06-01" "2020-02-01" "2020-04-01" "2020-12-01" "2020-08-01"
#[9] "2020-01-01" "2020-01-01" "2020-10-01" "2020-06-01" "2020-08-01" "2020-05-01" "2020-10-01" "2020-08-01"
#[17] "2020-11-01" "2020-01-01" "2020-12-01" "2020-11-01"

If we have some mixed formats i.e. %b-%d along with the one showed in  the post, an option is to rearrange the substring with sub to make it a single format and then apply the as.yearmon

as.Date(as.yearmon(sub("^([A-Za-z]+)-(\\d+)$", "\\2-\\1", dat), "%d-%b"))

data

 dat <- c("20-Nov", "15-Nov", "20-Jan", "20-Jun", "20-Feb", "19-Apr",
"16-Dec", "20-Aug", "17-Jan", "16-Jan", "17-Oct", "19-Jun", "17-Aug",
"16-May", "16-Oct", "18-Aug", "19-Nov", "15-Jan", "17-Dec", "18-Nov")


问:
Number at risk for cox regression plot
can I make "number at risk "table for cox plot if I have more than one independent variable?
if it possible where can I find the relevant code (I searched  but couldn't find)
 the code I used on my data:

```<code>fit <- coxph(Surv(time,event) ~chr1q21_status+CCND1+CRTM1+IRF4,data = myeloma)

ggsurvplot(fit, data = myeloma,
  risk.table=TRUE, break.time.by=365, xlim = c(0,4000),
  risk.table.y.text=FALSE, legend.labs =  c("2","3","4+"))
</code>```

got this message- object 'ggsurv' not found' although for only one variable and the function survfit it worked.

答:
"number at risk "table for cox plot

It's not a Cox plot, it's a Kaplan-Meier plot. You're trying to plot a Cox model, when what you want is to fit KM curves using survfit and then to plot the resulting fit:

library("survival")
library("survminer")
fit <- survfit(Surv(time,status) ~ ph.ecog + sex , data = lung)
ggsurvplot(fit, data = lung, risk.table = TRUE)
```

<p><img src="https://i.imgur.com/WapL2Ke.png" alt=""></p>

<p>Since you now mention that you have continuous predictors, perhaps you could think about what you expect an at-risk table or KM plot to show.
Here's an example of binning a continuous measure (age):</p>

<pre class="lang-r prettyprint-override"><code>library("survival")
library("survminer")
#> Loading required package: ggplot2
#> Loading required package: ggpubr
#> Loading required package: magrittr
lung$age_bin <- cut(lung$age, quantile(lung$age))
fit <- survfit(Surv(time,status) ~ age_bin + sex , data = lung)
ggsurvplot(fit, data = lung, risk.table = TRUE)
</code>```

Title: Number at risk for cox regression plot

Body:
can I make "number at risk "table for cox plot if I have more than one independent variable?
if it possible where can I find the relevant code (I searched  but couldn't find)
 the code I used on my data:

fit <- coxph(Surv(time,event) ~chr1q21_status+CCND1+CRTM1+IRF4,data = myeloma)

ggsurvplot(fit, data = myeloma,
  risk.table=TRUE, break.time.by=365, xlim = c(0,4000),
  risk.table.y.text=FALSE, legend.labs =  c("2","3","4+"))

got this message- object 'ggsurv' not found' although for only one variable and the function survfit it worked.

Body:
"number at risk "table for cox plot

It's not a Cox plot, it's a Kaplan-Meier plot. You're trying to plot a Cox model, when what you want is to fit KM curves using survfit and then to plot the resulting fit:

library("survival")
library("survminer")
fit <- survfit(Surv(time,status) ~ ph.ecog + sex , data = lung)
ggsurvplot(fit, data = lung, risk.table = TRUE)

Since you now mention that you have continuous predictors, perhaps you could think about what you expect an at-risk table or KM plot to show.
Here's an example of binning a continuous measure (age):

library("survival")
library("survminer")
#> Loading required package: ggplot2
#> Loading required package: ggpubr
#> Loading required package: magrittr
lung$age_bin <- cut(lung$age, quantile(lung$age))
fit <- survfit(Surv(time,status) ~ age_bin + sex , data = lung)
ggsurvplot(fit, data = lung, risk.table = TRUE)


问:
VBA Excel saving the file in the folder created by Excel macro
I would like to save my file in the folder created by...excel macro.

The process of vba excel folder creation has been presented here:

Create a folder and sub folder in Excel VBA

Following it, I have assigned it to my situation:

```<code> Sub Createfolder ()
     Dim fso As Object
     Dim fldrtitle As String
     Dim flrdrname As String
     Dim fldrpath As String

     Set fso = CreateObject("scripting.filesystemobject")
     fldrtitle = Worksheets("Sheet1").Range("A2").Value
     fldrname = "Pre-planning NBU " & fldrtitle
     fldrpath = "H:\ProfileV2\Desktop\Pre planning NBU\ Alex list new\" & fldrname
     If not fso.FolderExists(fldrpath) Then
         fso.Createfolder (fldrpath)
     End If
 End Sub
</code>```

Where the folder has been created.
My way to saving the file, according to the previous query looks as follows:

```<code>Sub Save()
    Dim name As String, Custom_Name As String

    name = Worksheets("Sheet1").Range("A2").Value
    Custom_Name = ThisWorkbook.Path & "\" & "NBU " & name & " - Opportunity list.xlsx"
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:=Custom_name, FileFormat:=51
End Sub
</code>```

Now, I tried to combine them together at some point, where the way 1 was:

```<code>Sub Save()
    Call Createfolder

    Dim name As String, Custom_Name As String

    name = Worksheets("Sheet1").Range("A2").Value
    Custom_Name = ThisWorkbook.Path & Createfolder & "NBU " & name & " - Opportunity list.xlsx"
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:=Custom_name, FileFormat:=51
End Sub
</code>```

Here I am getting error:
Expected Function or variable

what I understood, as I cannot fetch the external macro inside the code.

Afterwards I tried another way:

```<code> Sub Savetofolder ()
     Dim fso As Object
     Dim fldrtitle As String
     Dim flrdrname As String
     Dim fldrpath As String
     Dim name As String, Custom_Name As String

     Set fso = CreateObject("scripting.filesystemobject")
     fldrtitle = Worksheets("Sheet1").Range("A2").Value
     fldrname = "Pre-planning NBU " & fldrtitle
     fldrpath = "H:\ProfileV2\Desktop\Pre planning NBU\ Alex list new\" & fldrname
     If not fso.FolderExists(fldrpath) Then
         fso.Createfolder (fldrpath)
     End If

 'name = Worksheets("Sheet1").Range("A2").Value
     Custom_Name = ThisWorkbook.Path & Createfolder & "NBU " & fldrtitle & " - Opportunity list.xlsx"
     Application.DisplayAlerts = False
     ActiveWorkbook.SaveAs Filename:=Custom_name, FileFormat:=51
 End Sub
</code>```

I switched off the name variable, because it's the same as fldrtitle.

In the result my file is saved next to the created folder as per in the picture below:

Is there any chance to get it saved INSIDE this folder?

答:
Think you want this:

```<code>Function Createfolder() As String
  Dim fso As Object
  Dim fldrtitle As String
  Dim flrdrname As String
  Dim fldrpath As String

  Set fso = CreateObject("scripting.filesystemobject")
  fldrtitle = Worksheets("Sheet1").Range("A2").Value
  fldrname = "Pre-planning NBU " & fldrtitle
  fldrpath = "H:\ProfileV2\Desktop\Pre planning NBU\ Alex list new\" & fldrname
  If not fso.FolderExists(fldrpath) Then
      fso.Createfolder (fldrpath)
  End If

  Createfolder = fldrpath
End Function

Sub Save()

  Dim name As String, Custom_Name As String

  name = Worksheets("Sheet1").Range("A2").Value
  Custom_Name = Createfolder() & "\NBU " & name & " - Opportunity list.xlsx"
  Application.DisplayAlerts = False
  ActiveWorkbook.SaveAs Filename:=Custom_name, FileFormat:=51
End Sub
</code>```

EDIT

You aren't really gaining anything by separating the folder creation, this would probably be better:

```<code>Sub Save()

  Dim fso As Object
  Dim fldrtitle As String
  Dim flrdrname As String
  Dim fldrpath As String
  Dim filename As String
  Dim name As String

  'Construct folder name
  fldrtitle = Worksheets("Sheet1").Range("A2").Value
  name = Worksheets("Sheet1").Range("A2").Value 'looks like this is the same as fldrtitle, could just use same variable below
  fldrname = "Pre-planning NBU " & fldrtitle
  fldrpath = "H:\ProfileV2\Desktop\Pre planning NBU\ Alex list new\" & fldrname

  'Create folder if it doesn't exist
  Set fso = CreateObject("scripting.filesystemobject")
  If not fso.FolderExists(fldrpath) Then
      fso.Createfolder (fldrpath)
  End If

  'Construct filename and save
  filename = fldrpath & "\NBU " & name & " - Opportunity list.xlsx"
  Application.DisplayAlerts = False
  ActiveWorkbook.SaveAs Filename:=filename, FileFormat:=51
End Sub
</code>```

Body:
I would like to save my file in the folder created by...excel macro.

The process of vba excel folder creation has been presented here:

Create a folder and sub folder in Excel VBA

Following it, I have assigned it to my situation:

 Sub Createfolder ()
     Dim fso As Object
     Dim fldrtitle As String
     Dim flrdrname As String
     Dim fldrpath As String

     Set fso = CreateObject("scripting.filesystemobject")
     fldrtitle = Worksheets("Sheet1").Range("A2").Value
     fldrname = "Pre-planning NBU " & fldrtitle
     fldrpath = "H:\ProfileV2\Desktop\Pre planning NBU\ Alex list new\" & fldrname
     If not fso.FolderExists(fldrpath) Then
         fso.Createfolder (fldrpath)
     End If
 End Sub

Where the folder has been created.
My way to saving the file, according to the previous query looks as follows:

Sub Save()
    Dim name As String, Custom_Name As String

    name = Worksheets("Sheet1").Range("A2").Value
    Custom_Name = ThisWorkbook.Path & "\" & "NBU " & name & " - Opportunity list.xlsx"
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:=Custom_name, FileFormat:=51
End Sub

Now, I tried to combine them together at some point, where the way 1 was:

Sub Save()
    Call Createfolder

    Dim name As String, Custom_Name As String

    name = Worksheets("Sheet1").Range("A2").Value
    Custom_Name = ThisWorkbook.Path & Createfolder & "NBU " & name & " - Opportunity list.xlsx"
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:=Custom_name, FileFormat:=51
End Sub

Here I am getting error:
Expected Function or variable

what I understood, as I cannot fetch the external macro inside the code.

Afterwards I tried another way:

 Sub Savetofolder ()
     Dim fso As Object
     Dim fldrtitle As String
     Dim flrdrname As String
     Dim fldrpath As String
     Dim name As String, Custom_Name As String

     Set fso = CreateObject("scripting.filesystemobject")
     fldrtitle = Worksheets("Sheet1").Range("A2").Value
     fldrname = "Pre-planning NBU " & fldrtitle
     fldrpath = "H:\ProfileV2\Desktop\Pre planning NBU\ Alex list new\" & fldrname
     If not fso.FolderExists(fldrpath) Then
         fso.Createfolder (fldrpath)
     End If

 'name = Worksheets("Sheet1").Range("A2").Value
     Custom_Name = ThisWorkbook.Path & Createfolder & "NBU " & fldrtitle & " - Opportunity list.xlsx"
     Application.DisplayAlerts = False
     ActiveWorkbook.SaveAs Filename:=Custom_name, FileFormat:=51
 End Sub

I switched off the name variable, because it's the same as fldrtitle.

In the result my file is saved next to the created folder as per in the picture below:

Is there any chance to get it saved INSIDE this folder?

Body:
Think you want this:

Function Createfolder() As String
  Dim fso As Object
  Dim fldrtitle As String
  Dim flrdrname As String
  Dim fldrpath As String

  Set fso = CreateObject("scripting.filesystemobject")
  fldrtitle = Worksheets("Sheet1").Range("A2").Value
  fldrname = "Pre-planning NBU " & fldrtitle
  fldrpath = "H:\ProfileV2\Desktop\Pre planning NBU\ Alex list new\" & fldrname
  If not fso.FolderExists(fldrpath) Then
      fso.Createfolder (fldrpath)
  End If

  Createfolder = fldrpath
End Function

Sub Save()

  Dim name As String, Custom_Name As String

  name = Worksheets("Sheet1").Range("A2").Value
  Custom_Name = Createfolder() & "\NBU " & name & " - Opportunity list.xlsx"
  Application.DisplayAlerts = False
  ActiveWorkbook.SaveAs Filename:=Custom_name, FileFormat:=51
End Sub

EDIT

You aren't really gaining anything by separating the folder creation, this would probably be better:

Sub Save()

  Dim fso As Object
  Dim fldrtitle As String
  Dim flrdrname As String
  Dim fldrpath As String
  Dim filename As String
  Dim name As String

  'Construct folder name
  fldrtitle = Worksheets("Sheet1").Range("A2").Value
  name = Worksheets("Sheet1").Range("A2").Value 'looks like this is the same as fldrtitle, could just use same variable below
  fldrname = "Pre-planning NBU " & fldrtitle
  fldrpath = "H:\ProfileV2\Desktop\Pre planning NBU\ Alex list new\" & fldrname

  'Create folder if it doesn't exist
  Set fso = CreateObject("scripting.filesystemobject")
  If not fso.FolderExists(fldrpath) Then
      fso.Createfolder (fldrpath)
  End If

  'Construct filename and save
  filename = fldrpath & "\NBU " & name & " - Opportunity list.xlsx"
  Application.DisplayAlerts = False
  ActiveWorkbook.SaveAs Filename:=filename, FileFormat:=51
End Sub


问:
Change datatype of a whole column from string to integer in SQLite?
I'm pretty new to SQL. I'm practicing on a dataset I downloaded, unfortunately some int type columns became varchar when I imported them. I need to change them back into int. </p>

<p>I tried to create a temp table, create the correct schema for the table with appropriate datatype for all columns, then dump everything back. I got an int column with a mixture of int and empty strings. How do I convert empty strings to zeros? Thank you. </p>

答:
With an UPDATE statement like this:

```<code>UPDATE tablename
SET columnname = 0
WHERE columnname is null or trim(columnname) = ''
</code>```

Remove columnname is null if you don't have nulls but empty strings.

Body:
I'm pretty new to SQL. I'm practicing on a dataset I downloaded, unfortunately some int type columns became varchar when I imported them. I need to change them back into int.

I tried to create a temp table, create the correct schema for the table with appropriate datatype for all columns, then dump everything back. I got an int column with a mixture of int and empty strings. How do I convert empty strings to zeros? Thank you.

Body:
With an UPDATE statement like this:

UPDATE tablename
SET columnname = 0
WHERE columnname is null or trim(columnname) = ''

Remove columnname is null if you don't have nulls but empty strings.


答:
Since the user is logged in it means he's authenticated.
Try this</p>

```<code>$UserID = Auth::user()->id;

$demands = Demand::where('user_id', '=', $UserID);

echo $demands;
</code>```

Title: Basic Select with Laravel Eloquent do not work

Body:
Since the user is logged in it means he's authenticated.
Try this

$UserID = Auth::user()->id;

$demands = Demand::where('user_id', '=', $UserID);

echo $demands;


问:
Python multiprocessing: How to know to use Pool or Process?
So I have an algorithm I am writing, and the function multiprocess is supposed to call another function, CreateMatrixMp(), on as many processes as there are cpus, in parallel. I have never done multiprocessing before, and cannot be certain which one of the below methods is more efficient. The word "efficient" being used in the context of the function CreateMatrixMp() needing to potentially be called thousands of times.I have read all of the documentation on the python multiprocessing module, and have come to these two possibilities:

First is using the Pool class:

```<code>def MatrixHelper(self, args):
    return self.CreateMatrix(*args)

def Multiprocess(self, sigmaI, sigmaX):

    cpus = mp.cpu_count()
    print('Number of cpu\'s to process WM: %d' % cpus)
    poolCount = cpus*2
    args = [(sigmaI, sigmaX, i) for i in range(self.numPixels)]

    pool = mp.Pool(processes = poolCount, maxtasksperchild= 2)
    tempData = pool.map(self.MatrixHelper, args)
    pool.close()
    pool.join()
</code>```

And next is using the Process class:

```<code>def Multiprocess(self, sigmaI, sigmaX):

    cpus = mp.cpu_count()
    print('Number of cpu\'s to process WM: %d' % cpus)

    processes = [mp.Process(target = self.CreateMatrixMp, args = (sigmaI, sigmaX, i,)) for i in range(self.numPixels)]
    for p in processes:
        p.start()
    for p in processes:
        p.join()
</code>```

Pool seems to be the better choice. I have read that it causes less overhead. And Process does not consider the number of cpus on the machine. The only problem is that using Pool in this manner gives me error after error, and whenever I fix one, there is a new one underneath it. Process seems easier to implement, and for all I know it may be the better choice. What does your experience tell you?

If Pool should be used, then am I right in choosing map()? It would be preferred that order is maintained. I have tempData = pool.map(...) because the map function is supposed to return a list of the results of every process. I am not sure how Process handles its returned data.

答:
You can easily do this with pypeln:

import pypeln as pl

stage = pl.process.map(
    CreateMatrixMp,
    range(self.numPixels),
    workers=poolCount,
    maxsize=2,
)

# iterate over it in the main process
for x in stage:
   # code

# or convert it to a list
data = list(stage)
```

Body:
So I have an algorithm I am writing, and the function multiprocess is supposed to call another function, CreateMatrixMp(), on as many processes as there are cpus, in parallel. I have never done multiprocessing before, and cannot be certain which one of the below methods is more efficient. The word "efficient" being used in the context of the function CreateMatrixMp() needing to potentially be called thousands of times.I have read all of the documentation on the python multiprocessing module, and have come to these two possibilities:

First is using the Pool class:

def MatrixHelper(self, args):
    return self.CreateMatrix(*args)

def Multiprocess(self, sigmaI, sigmaX):

    cpus = mp.cpu_count()
    print('Number of cpu\'s to process WM: %d' % cpus)
    poolCount = cpus*2
    args = [(sigmaI, sigmaX, i) for i in range(self.numPixels)]

    pool = mp.Pool(processes = poolCount, maxtasksperchild= 2)
    tempData = pool.map(self.MatrixHelper, args)
    pool.close()
    pool.join()

And next is using the Process class:

def Multiprocess(self, sigmaI, sigmaX):

    cpus = mp.cpu_count()
    print('Number of cpu\'s to process WM: %d' % cpus)

    processes = [mp.Process(target = self.CreateMatrixMp, args = (sigmaI, sigmaX, i,)) for i in range(self.numPixels)]
    for p in processes:
        p.start()
    for p in processes:
        p.join()

Pool seems to be the better choice. I have read that it causes less overhead. And Process does not consider the number of cpus on the machine. The only problem is that using Pool in this manner gives me error after error, and whenever I fix one, there is a new one underneath it. Process seems easier to implement, and for all I know it may be the better choice. What does your experience tell you?

If Pool should be used, then am I right in choosing map()? It would be preferred that order is maintained. I have tempData = pool.map(...) because the map function is supposed to return a list of the results of every process. I am not sure how Process handles its returned data.


问:
DynamoDB find all items after date
I have a DynamoDB table in which I store link data (url, date, category, tags etc).

I need to be able to -

lookup items by url (check url doesn't already exist)

find all items stored after a given date

Based on the above I set up the schema with url as primary hash key and secondary index on date, as follows -

```<code>AWSTemplateFormatVersion: '2010-09-09'
Parameters:
  TableName:
    Type: String
    Default: "my_links"
  HashAttr:
    Type: String
    Default: url
  IndexAttr:
    Type: String
    Default: date
  ReadCapacity:
    Type: Number
    Default: 5
  WriteCapacity:
    Type: Number
    Default: 5
Resources:
  Table:
    Properties:
      KeySchema:
        - AttributeName: !Ref HashAttr
          KeyType: HASH
      AttributeDefinitions:
        - AttributeName: !Ref HashAttr
          AttributeType: S
        - AttributeName: !Ref IndexAttr
          AttributeType: S
      GlobalSecondaryIndexes:
        - IndexName: !Ref IndexAttr
          KeySchema:
            - AttributeName: !Ref IndexAttr
              KeyType: HASH
          Projection:
            ProjectionType: ALL
          ProvisionedThroughput:
            ReadCapacityUnits: !Ref ReadCapacity
            WriteCapacityUnits: !Ref WriteCapacity
      ProvisionedThroughput:
        ReadCapacityUnits: !Ref ReadCapacity
        WriteCapacityUnits: !Ref WriteCapacity
      TableName: !Ref TableName
    Type: AWS::DynamoDB::Table
</code>```

I can query the table by date as follows, but only using an eq condition -

```<code>ddb=boto3.resource("dynamodb")
table=ddb.Table("my_links")
from boto3.dynamodb.conditions import Key
queryexp=Key('date').eq("2020-02-19")
for item in table.query(IndexName="date",
                        KeyConditionExpression=queryexp)["Items"]:
    print (item)
</code>```

If I use a gte in place of eq condition I get the following -

```<code>botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the Query operation: Query key condition not supported
</code>```

I can however query the table using a scan and a gte condition -

```<code>filterexp=Key('date').gte("2020-02-19")
for item in table.scan(FilterExpression=filterexp)["Items"]:
    print (item)
</code>```

But then I'm guessing I don't need the secondary index any more and also that this will get very expensive as the table get large :-/

So I'd rather stick with a secondary index and query if possible (am I thinking about this right ?), but what do I need to do to the schema to be able to fetch all items after a date ?

答:
So this was useful -

https://stackoverflow.com/a/38790120/124179

and also this -

How to query DynamoDB by date (range key), with no obvious hash key?

In the end the answer was to denormalised the data, replacing the date field (and associated secondary index) with a week field, then searching for one or more specific weeks using eq query condition and joining the results (I only need a couple of weeks data)

Obviously could replace week with month for increased range but reduced granularity.

Title: DynamoDB find all items after date

Body:
I have a DynamoDB table in which I store link data (url, date, category, tags etc).

I need to be able to -

lookup items by url (check url doesn't already exist)

find all items stored after a given date

Based on the above I set up the schema with url as primary hash key and secondary index on date, as follows -

AWSTemplateFormatVersion: '2010-09-09'
Parameters:
  TableName:
    Type: String
    Default: "my_links"
  HashAttr:
    Type: String
    Default: url
  IndexAttr:
    Type: String
    Default: date
  ReadCapacity:
    Type: Number
    Default: 5
  WriteCapacity:
    Type: Number
    Default: 5
Resources:
  Table:
    Properties:
      KeySchema:
        - AttributeName: !Ref HashAttr
          KeyType: HASH
      AttributeDefinitions:
        - AttributeName: !Ref HashAttr
          AttributeType: S
        - AttributeName: !Ref IndexAttr
          AttributeType: S
      GlobalSecondaryIndexes:
        - IndexName: !Ref IndexAttr
          KeySchema:
            - AttributeName: !Ref IndexAttr
              KeyType: HASH
          Projection:
            ProjectionType: ALL
          ProvisionedThroughput:
            ReadCapacityUnits: !Ref ReadCapacity
            WriteCapacityUnits: !Ref WriteCapacity
      ProvisionedThroughput:
        ReadCapacityUnits: !Ref ReadCapacity
        WriteCapacityUnits: !Ref WriteCapacity
      TableName: !Ref TableName
    Type: AWS::DynamoDB::Table

I can query the table by date as follows, but only using an eq condition -

ddb=boto3.resource("dynamodb")
table=ddb.Table("my_links")
from boto3.dynamodb.conditions import Key
queryexp=Key('date').eq("2020-02-19")
for item in table.query(IndexName="date",
                        KeyConditionExpression=queryexp)["Items"]:
    print (item)

If I use a gte in place of eq condition I get the following -

botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the Query operation: Query key condition not supported

I can however query the table using a scan and a gte condition -

filterexp=Key('date').gte("2020-02-19")
for item in table.scan(FilterExpression=filterexp)["Items"]:
    print (item)

But then I'm guessing I don't need the secondary index any more and also that this will get very expensive as the table get large :-/

So I'd rather stick with a secondary index and query if possible (am I thinking about this right ?), but what do I need to do to the schema to be able to fetch all items after a date ?


问:
How to get the identity of an inserted row?
How am I supposed to get the IDENTITY of an inserted row?

I know about @@IDENTITY and IDENT_CURRENT and SCOPE_IDENTITY, but don't understand the implications or impacts attached to each.

Can someone please explain the differences and when I would be using each?

答:
Even though this is an older thread, there is a newer way to do this which avoids some of the pitfalls of the IDENTITY column in older versions of SQL Server, like gaps in the identity values after server reboots. Sequences are available in SQL Server 2016 and forward which is the newer way is to create a SEQUENCE object using TSQL.  This allows you create your own numeric sequence object in SQL Server and control how it increments.

Here is an example:

```<code>CREATE SEQUENCE CountBy1
    START WITH 1
    INCREMENT BY 1 ;
GO
</code>```

Then in TSQL you would do the following to get the next sequence ID:

```<code>SELECT NEXT VALUE FOR CountBy1 AS SequenceID
GO
</code>```

Here are the links to CREATE SEQUENCE and NEXT VALUE FOR

OwnerDisplayName: Oded

Body:
Even though this is an older thread, there is a newer way to do this which avoids some of the pitfalls of the IDENTITY column in older versions of SQL Server, like gaps in the identity values after server reboots. Sequences are available in SQL Server 2016 and forward which is the newer way is to create a SEQUENCE object using TSQL.  This allows you create your own numeric sequence object in SQL Server and control how it increments.

Here is an example:

CREATE SEQUENCE CountBy1
    START WITH 1
    INCREMENT BY 1 ;
GO

Then in TSQL you would do the following to get the next sequence ID:

SELECT NEXT VALUE FOR CountBy1 AS SequenceID
GO

Here are the links to CREATE SEQUENCE and NEXT VALUE FOR


问:
Async Infinite Loop
I'm programming a C# software and it has some functions which make like a check-in on my server 5 in 5 seconds (they send http request, but it doesn't matter for my problem). Here is the code:

```<code>    log();

    while (true)
    {

        alive(); // this sends an http request to my server
        Thread.Sleep(5000); // sleep for 5 seconds avoiding computer overcharge
    }

    MessageBox.Show("after infinite loop"); // this is never executed but i pretend to do so
</code>```

So, my problem is: I got an infinite loop and after that infinite loop I want to write ANOTHER infinite loop which runs asynchronously and does something each 100ms. Of course "that something" i cannot write it inside the existing loop because that loop is executed 5 in 5 seconds. I got to code a lot of infinite loops like those, each one being executed independently from another (or asynchronously) with different times.

I have searched a lot and my conclusion is to write every loop asynchronously.
My question is: how to do that? Every code I found was completely incomprehensible for me. I simply couldn't understand them. So, if you have a better option than async infinite loops (which i think is the best option indeed), you can speak about it, otherwise i need some help coding this async infinite loops...

Sorry for my bad english,
thanks in advance

答:
You can do it using async await as follows:

Create an async calling method that will call your multiple methods having infinite loop in non blocking way.

```<code>private async void Method1()
{

DoSomeInfiniteWork1(); //Don't use await here

MessageBox.Show("after First infinite loop"); //now it will executed instantly after calling DoSomeInfiniteWork1 method having infinite while loop.

DoSomeInfiniteWork2();

...some other task
}
</code>```

Create first method async having infinite loop as follows:

```<code>static bool cancelwork1=false;
private async Task DoSomeInfiniteWork1()
{
log();
    while (true)
    {
        //break logic to exit the loop if required
        if(cancelwork1)
        break;

        alive(); // this sends an http request to my server
        Task.Delay(5000); // Replace Thread.Sleep with Task.Delay
    }
}
</code>```

Create second method having another infinite loop:

```<code>static bool cancelwork2=false;
private async Task DoSomeInfiniteWork2()
{

while (true)
    {
        //break logic to exit the loop if required
        if(cancelwork2)
        break;

       DoSomeOtherWork();// Do your other work
       Task.Delay(5000); // Replace Thread.Sleep with Task.Delay
    }

}
</code>```

Thanks !!

Title: Async Infinite Loop

Body:
I'm programming a C# software and it has some functions which make like a check-in on my server 5 in 5 seconds (they send http request, but it doesn't matter for my problem). Here is the code:

    log();

    while (true)
    {

        alive(); // this sends an http request to my server
        Thread.Sleep(5000); // sleep for 5 seconds avoiding computer overcharge
    }

    MessageBox.Show("after infinite loop"); // this is never executed but i pretend to do so

So, my problem is: I got an infinite loop and after that infinite loop I want to write ANOTHER infinite loop which runs asynchronously and does something each 100ms. Of course "that something" i cannot write it inside the existing loop because that loop is executed 5 in 5 seconds. I got to code a lot of infinite loops like those, each one being executed independently from another (or asynchronously) with different times.

I have searched a lot and my conclusion is to write every loop asynchronously.
My question is: how to do that? Every code I found was completely incomprehensible for me. I simply couldn't understand them. So, if you have a better option than async infinite loops (which i think is the best option indeed), you can speak about it, otherwise i need some help coding this async infinite loops...

Sorry for my bad english,
thanks in advance

Body:
You can do it using async await as follows:

Create an async calling method that will call your multiple methods having infinite loop in non blocking way.

private async void Method1()
{

DoSomeInfiniteWork1(); //Don't use await here

MessageBox.Show("after First infinite loop"); //now it will executed instantly after calling DoSomeInfiniteWork1 method having infinite while loop.

DoSomeInfiniteWork2();

...some other task
}

Create first method async having infinite loop as follows:

static bool cancelwork1=false;
private async Task DoSomeInfiniteWork1()
{
log();
    while (true)
    {
        //break logic to exit the loop if required
        if(cancelwork1)
        break;

        alive(); // this sends an http request to my server
        Task.Delay(5000); // Replace Thread.Sleep with Task.Delay
    }
}

Create second method having another infinite loop:

static bool cancelwork2=false;
private async Task DoSomeInfiniteWork2()
{

while (true)
    {
        //break logic to exit the loop if required
        if(cancelwork2)
        break;

       DoSomeOtherWork();// Do your other work
       Task.Delay(5000); // Replace Thread.Sleep with Task.Delay
    }

}

Thanks !!


问:
Keras multi label image classification. Do I pass my data correctly? Did I preprocess correctly?
I am stuck in my keras multilabel problem. I got the hint to work with a custom data generator to create small batches and avoid memory issues.

I work with a csv file with IDs, Filenames and their corresponding labels (21 in total), which looks like this:

```<code>Filename  label1  label2  label3  label4  ...   ID
abc1.jpg    1       0       0       1     ...  id-1
def2.jpg    1       0       0       1     ...  id-2
ghi3.jpg    1       0       0       1     ...  id-3
...
</code>```

I put the the ids and the labels in dictionaries which has the following output:

```<code>partition: {'train': ['id-1','id-2','id-3',...], 'validation': ['id-7','id-14','id-21',...]}
labels:    {'id-0': [1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            'id-1': [1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            'id-2': [1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
             ...}
</code>```

As well i have a folder with every image saved as a single npy file, which will be taken by the custom data generator below:

```<code>import numpy as np
import keras
from keras.layers import *
from keras.models import Sequential

class DataGenerator(keras.utils.Sequence):
    'Generates data for Keras'
    def __init__(self, list_IDs, labels, batch_size=32, dim=(224,224), n_channels=3,
                 n_classes=21, shuffle=True):
        'Initialization'
        self.dim = dim
        self.batch_size = batch_size
        self.labels = labels
        self.list_IDs = list_IDs
        self.n_channels = n_channels
        self.n_classes = n_classes
        self.shuffle = shuffle
        self.on_epoch_end()

    def __len__(self):
        'Denotes the number of batches per epoch'
        return int(np.floor(len(self.list_IDs) / self.batch_size))

    def __getitem__(self, index):
        'Generate one batch of data'
        # Generate indexes of the batch
        indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]

        # Find list of IDs
        list_IDs_temp = [self.list_IDs[k] for k in indexes]

        # Generate data
        X, y = self.__data_generation(list_IDs_temp)

        return X, y

    def on_epoch_end(self):
        'Updates indexes after each epoch'
        self.indexes = np.arange(len(self.list_IDs))
        if self.shuffle == True:
            np.random.shuffle(self.indexes)

    def __data_generation(self, list_IDs_temp):
        'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)
        # Initialization
        X = np.empty((self.batch_size, *self.dim, self.n_channels))
        y = np.empty((self.batch_size), dtype=int)

        # Generate data
        for i, ID in enumerate(list_IDs_temp):
            # Store sample
            X[i,] = np.load('Folder with npy files/' + ID + '.npy')

            # Store class
            y[i] = self.labels[ID]

        return X, keras.utils.to_categorical(y, num_classes=self.n_classes)
</code>```

```<code>import numpy as np

from keras.models import Sequential

# Parameters
params = {'dim': (224, 224),
          'batch_size': 32,
          'n_classes': 21,
          'n_channels': 3,
          'shuffle': True}

# Datasets
partition = partition
labels = labels

# Generators
training_generator = DataGenerator(partition['train'], labels, **params)
validation_generator = DataGenerator(partition['validation'], labels, **params)

# Design model
model = Sequential()

model.add(Conv2D(32, (3,3), input_shape=(224, 224, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

...

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dense(21))
model.add(Activation('softmax'))

model.summary()
</code>```

so far my notebook doesnt give me any Errors, but when i do the following:

```<code>model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

# Train model on dataset
model.fit_generator(generator=training_generator,
                    validation_data=validation_generator,
                    epochs=5,
                    use_multiprocessing=True,
                    workers=2)
</code>```

i get an Error message like this:

Exception in thread Thread-7:
Traceback (most recent call last):
  File "c:\users\sebas\appdata\local\programs\python\python36\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
...

File "c:\users\sebas\appdata\local\programs\python\python36\lib\multiprocessing\reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)
BrokenPipeError: [Errno 32] Broken pipe

It feels that I pass or use the data somehow incorrect!?
If someone has an idea or a hint how to pass the data in a better manner or tackle this issue, i will appreciate. Even a different approach would be awesome. Thanks for your help in advance.

答: use_multiprocessing=True is not supported on windows (github issue). remove that and the workers parameter.

Body:
I am stuck in my keras multilabel problem. I got the hint to work with a custom data generator to create small batches and avoid memory issues.

I work with a csv file with IDs, Filenames and their corresponding labels (21 in total), which looks like this:

Filename  label1  label2  label3  label4  ...   ID
abc1.jpg    1       0       0       1     ...  id-1
def2.jpg    1       0       0       1     ...  id-2
ghi3.jpg    1       0       0       1     ...  id-3
...

I put the the ids and the labels in dictionaries which has the following output:

partition: {'train': ['id-1','id-2','id-3',...], 'validation': ['id-7','id-14','id-21',...]}
labels:    {'id-0': [1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            'id-1': [1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            'id-2': [1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
             ...}

As well i have a folder with every image saved as a single npy file, which will be taken by the custom data generator below:

import numpy as np
import keras
from keras.layers import *
from keras.models import Sequential

class DataGenerator(keras.utils.Sequence):
    'Generates data for Keras'
    def __init__(self, list_IDs, labels, batch_size=32, dim=(224,224), n_channels=3,
                 n_classes=21, shuffle=True):
        'Initialization'
        self.dim = dim
        self.batch_size = batch_size
        self.labels = labels
        self.list_IDs = list_IDs
        self.n_channels = n_channels
        self.n_classes = n_classes
        self.shuffle = shuffle
        self.on_epoch_end()

    def __len__(self):
        'Denotes the number of batches per epoch'
        return int(np.floor(len(self.list_IDs) / self.batch_size))

    def __getitem__(self, index):
        'Generate one batch of data'
        # Generate indexes of the batch
        indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]

        # Find list of IDs
        list_IDs_temp = [self.list_IDs[k] for k in indexes]

        # Generate data
        X, y = self.__data_generation(list_IDs_temp)

        return X, y

    def on_epoch_end(self):
        'Updates indexes after each epoch'
        self.indexes = np.arange(len(self.list_IDs))
        if self.shuffle == True:
            np.random.shuffle(self.indexes)

    def __data_generation(self, list_IDs_temp):
        'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)
        # Initialization
        X = np.empty((self.batch_size, *self.dim, self.n_channels))
        y = np.empty((self.batch_size), dtype=int)

        # Generate data
        for i, ID in enumerate(list_IDs_temp):
            # Store sample
            X[i,] = np.load('Folder with npy files/' + ID + '.npy')

            # Store class
            y[i] = self.labels[ID]

        return X, keras.utils.to_categorical(y, num_classes=self.n_classes)

import numpy as np

from keras.models import Sequential

# Parameters
params = {'dim': (224, 224),
          'batch_size': 32,
          'n_classes': 21,
          'n_channels': 3,
          'shuffle': True}

# Datasets
partition = partition
labels = labels

# Generators
training_generator = DataGenerator(partition['train'], labels, **params)
validation_generator = DataGenerator(partition['validation'], labels, **params)

# Design model
model = Sequential()

model.add(Conv2D(32, (3,3), input_shape=(224, 224, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

...

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dense(21))
model.add(Activation('softmax'))

model.summary()

so far my notebook doesnt give me any Errors, but when i do the following:

model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

# Train model on dataset
model.fit_generator(generator=training_generator,
                    validation_data=validation_generator,
                    epochs=5,
                    use_multiprocessing=True,
                    workers=2)

i get an Error message like this:

Exception in thread Thread-7:
Traceback (most recent call last):
  File "c:\users\sebas\appdata\local\programs\python\python36\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
...

File "c:\users\sebas\appdata\local\programs\python\python36\lib\multiprocessing\reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)
BrokenPipeError: [Errno 32] Broken pipe

It feels that I pass or use the data somehow incorrect!?
If someone has an idea or a hint how to pass the data in a better manner or tackle this issue, i will appreciate. Even a different approach would be awesome. Thanks for your help in advance.