问:
@ApiResponse with empty response body (Spring Boot)
I'm looking for a way to tell swagger that a certain API response code doesn't have a response body. A get response, for example, that can either return a 200 code with the actual object as a response or a 404 if the object associated with the passed ID doesn't exist:

```<code>@ApiResponses(value = {
    @ApiResponse(responseCode = "200", description = "Object found"),
    @ApiResponse(responseCode = "404", description = "Invalid object ID", content = @Content)
})
</code>```

This is the closest thing I could figure out but it's not perfect, I still get an annoying "Media type" under the description of the 404 response.
Thanks!

答:
If you are not specifying the content attribute of @ApiResponse annotation the return type of the controller method will be your response content. To prevent this define content explicitly:

```<code>@ApiResponse(responseCode = "200", description = "OK",
             content = @Content(schema = @Schema(implementation = Void.class)))
</code>```

Or you can simply return ResponseEntity<Void>.

Body:
I'm looking for a way to tell swagger that a certain API response code doesn't have a response body. A get response, for example, that can either return a 200 code with the actual object as a response or a 404 if the object associated with the passed ID doesn't exist:

@ApiResponses(value = {
    @ApiResponse(responseCode = "200", description = "Object found"),
    @ApiResponse(responseCode = "404", description = "Invalid object ID", content = @Content)
})

This is the closest thing I could figure out but it's not perfect, I still get an annoying "Media type" under the description of the 404 response.
Thanks!

Body:
If you are not specifying the content attribute of @ApiResponse annotation the return type of the controller method will be your response content. To prevent this define content explicitly:

@ApiResponse(responseCode = "200", description = "OK",
             content = @Content(schema = @Schema(implementation = Void.class)))

Or you can simply return ResponseEntity<Void>.


来源: stackexchange

问:
What is the equivalent of ActionBar in earlier sdk versions?
Since the ActionBar is available only in Android 3.0 and later, what is a good way to implement ActionBar-like widget in earlier sdk versions? I am looking to do this programmatically, if that helps. </p>

答:
The Google IO 2011 app is a good example

It runs on versions of Android less than 3.0 as explained during the Google I/O 2011 session, Designing and Implementing Android UIs for Phones and Tablets.

ContentLicense: CC BY-SA 3.0


问:
JavaScript: How do you use Array.prototype.filter() on arrays that contain objects
I was arranging a file tree and I only wanted to show file/folder name that don't have "." at the start of their names. But I always get the same array after I filter it. What do I do?

So here what have I tried:

```<code>const arr = [
  {
    name: ".hidden",
    size: "14"
  },
  {
    name: "View",
    size: "12"
  },
  {
    name: ".secret",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
];
arr.filter(obj => {
  // charCode of "." is 46
  if(obj.name.charCodeOf(0) !== 46) {
    return true
  }
  else {
    return false
  }
});
console.log(arr);
</code>```

Expexted Console:

```<code>[
  {
    name: "View",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
]
</code>```

Reality:

```<code>[
  {
    name: ".hidden",
    size: "14"
  },
  {
    name: "View",
    size: "12"
  },
  {
    name: ".secret",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
]
</code>```

答:
Try chartCodeAt(0) instead

```<code>let arr = [
  {
    name: ".hidden",
    size: "14"
  },
  {
    name: "View",
    size: "12"
  },
  {
    name: ".secret",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
];
arr = arr.filter(obj => {
  // charCode of "." is 46
  if(obj.name.charCodeAt(0) !== 46) {
    return true
  }
  else {
    return false
  }
});
console.log(arr);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I was arranging a file tree and I only wanted to show file/folder name that don't have "." at the start of their names. But I always get the same array after I filter it. What do I do?

So here what have I tried:

const arr = [
  {
    name: ".hidden",
    size: "14"
  },
  {
    name: "View",
    size: "12"
  },
  {
    name: ".secret",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
];
arr.filter(obj => {
  // charCode of "." is 46
  if(obj.name.charCodeOf(0) !== 46) {
    return true
  }
  else {
    return false
  }
});
console.log(arr);

Expexted Console:

[
  {
    name: "View",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
]

Reality:

[
  {
    name: ".hidden",
    size: "14"
  },
  {
    name: "View",
    size: "12"
  },
  {
    name: ".secret",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
]

Body:
Try chartCodeAt(0) instead

let arr = [
  {
    name: ".hidden",
    size: "14"
  },
  {
    name: "View",
    size: "12"
  },
  {
    name: ".secret",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
];
arr = arr.filter(obj => {
  // charCode of "." is 46
  if(obj.name.charCodeAt(0) !== 46) {
    return true
  }
  else {
    return false
  }
});
console.log(arr);


问:
How to select column content based on max value within groups of another column. Select marker name based of maximun value for each gene
I have the following df:

```<code>Gene pval  Marker
A      0.12     M1
A      0.11     M2
B      0.33     M3
B      0.55     M4
B      0.06     M5
D      0.03     M7
D      0.04     M8
</code>```

I want to get the marker name based on the maximum pvalue for each gene.
What I have tried:

```<code>peak_marker <-df[which.max(df[,2]),3]
</code>```

But the result is the marker name with the highest pvalue in the entire data frame not the marker name with the highest pval for each gene.

I also tried this with no success:

```<code>aggregate(df$pval, by = list(df$Gene), which.max)
</code>```

答:
Solution using dplyr:

```<code>library(dplyr)
df %>%
  group_by(Gene) %>%
  filter(val == max(val))
</code>```

Returns:

```<code>  # A tibble: 3 x 3
  # Groups:   Gene [3]
    Gene    val Marker
    <chr> <dbl> <chr>
  1 A      0.12 M1
  2 B      0.55 M4
  3 D      0.04 M8
</code>```

Or, if we want to get rid of the grouping:

```<code>  df %>%
    group_by(Gene) %>%
    filter(val == max(val)) %>%
    ungroup()
</code>```

Body:
I have the following df:

Gene pval  Marker
A      0.12     M1
A      0.11     M2
B      0.33     M3
B      0.55     M4
B      0.06     M5
D      0.03     M7
D      0.04     M8

I want to get the marker name based on the maximum pvalue for each gene.
What I have tried:

peak_marker <-df[which.max(df[,2]),3]

But the result is the marker name with the highest pvalue in the entire data frame not the marker name with the highest pval for each gene.

I also tried this with no success:

aggregate(df$pval, by = list(df$Gene), which.max)

Body:
Solution using dplyr:

library(dplyr)
df %>%
  group_by(Gene) %>%
  filter(val == max(val))

Returns:

  # A tibble: 3 x 3
  # Groups:   Gene [3]
    Gene    val Marker
    <chr> <dbl> <chr>
  1 A      0.12 M1
  2 B      0.55 M4
  3 D      0.04 M8

Or, if we want to get rid of the grouping:

  df %>%
    group_by(Gene) %>%
    filter(val == max(val)) %>%
    ungroup()


答:
You can simply use startsWith() for this scenario. Also, you are returning the original arr in the console log, but filter() does not modify the original array. It returns a new modified array which actually you need to put in the console log.

const arr = [{name:".hidden",size:"14"},{name:"View",size:"12"},{name:".secret",size:"12"},{name:"Public",size:"11"}];

var newArr = arr.filter(({name}) => name.startsWith("."));
console.log(newArr);```

Title: JavaScript: How do you use Array.prototype.filter() on arrays that contain objects


答:
Try this:</p>

```<code>const arr = [
  {
    name: ".hidden",
    size: "14"
  },
  {
    name: "View",
    size: "12"
  },
  {
    name: ".secret",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
];

const filteredArray = arr.filter(obj => !obj.name.startsWith("."));
console.log(filteredArray);
</code>```

Body:
Try this:

const arr = [
  {
    name: ".hidden",
    size: "14"
  },
  {
    name: "View",
    size: "12"
  },
  {
    name: ".secret",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
];

const filteredArray = arr.filter(obj => !obj.name.startsWith("."));
console.log(filteredArray);


问:
drop down country selection for phone country code in rails
Rails noob here posing a question.

I'm trying to get users to input their phone number. Form contains separate fields for countrycode, areacode and phonenumber at the moment.

```<code><% form_tag phones_path, :method => 'get' do %>
<th><%= text_field_tag :countrycode %></th>
<th><%= text_field_tag :areacode %></th>
<th><%= text_field_tag :search, params[:search] %></th>
<th><%= submit_tag "Search", :name => nil %></th>
<% end %>
</code>```

I want to convert the countrycode field into a dropdown selection of country names, and automatically display the actual country code upon selection. Eg user selections USA, and +1 is displayed. I am going to store both the country name and the numerical code.

I think I need to use a combination of collection_select for the dropdown and javascript to refresh the display. But I'm kinda lost as to how to proceed. Will any kind soul give some hints please?

答:
first you should create a hash in your controller that looks like:

```<code>@countries  = { "United States" => "+1", "Switzerland" => "+41" }
</code>```

Then create a select list for the countries and add an onchange javascript event handler for the select list:

```<code><% form_tag phones_path, :method => 'get' do %>
<th>
  <%= select_tag  :country,
                  options_for_select(@countries),
                  :onchange => "document.getElementById('countrycode').value = this.options[selectedIndex].value;"
  %>
</th>
<th><%= text_field_tag :countrycode %></th>
<th><%= text_field_tag :areacode %></th>
<th><%= text_field_tag :search, params[:search] %></th>
<th><%= submit_tag "Search", :name => nil %></th>
<% end %>
</code>```

Note: I've used standard Javascript for the onchange event, if you use jQuery or prototypeJS this could be written much shorter and cleaner :)

Body:
Rails noob here posing a question.

I'm trying to get users to input their phone number. Form contains separate fields for countrycode, areacode and phonenumber at the moment.

<% form_tag phones_path, :method => 'get' do %>
<%= text_field_tag :countrycode %>
<%= text_field_tag :areacode %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
<% end %>

I want to convert the countrycode field into a dropdown selection of country names, and automatically display the actual country code upon selection. Eg user selections USA, and +1 is displayed. I am going to store both the country name and the numerical code.

I think I need to use a combination of collection_select for the dropdown and javascript to refresh the display. But I'm kinda lost as to how to proceed. Will any kind soul give some hints please?

Body:
first you should create a hash in your controller that looks like:

@countries  = { "United States" => "+1", "Switzerland" => "+41" }

Then create a select list for the countries and add an onchange javascript event handler for the select list:

<% form_tag phones_path, :method => 'get' do %>
<th>
  <%= select_tag  :country,
                  options_for_select(@countries),
                  :onchange => "document.getElementById('countrycode').value = this.options[selectedIndex].value;"
  %>
</th>
<th><%= text_field_tag :countrycode %></th>
<th><%= text_field_tag :areacode %></th>
<th><%= text_field_tag :search, params[:search] %></th>
<th><%= submit_tag "Search", :name => nil %></th>
<% end %>

Note: I've used standard Javascript for the onchange event, if you use jQuery or prototypeJS this could be written much shorter and cleaner :)


问:
TextField either phone number or Email format validation swift?
I having one text field for forgot password ,here user enter either mobile number or email then we send OTP to that.

I am trying to validations for that text field with my code but it is not working, any one give some idea on that please find my code with following.

It needs to valid for either mailid or Phone number format.

```<code>if emaiTF.text == "" {
            print("Enter either valid phone or email")
        }else if let validphone = emaiTF.text, validphone.isValidPhone() || validphone.isValidEmail() {
            print("Enter either valid phone or email")
        }else{
            forGotPasswordApi()
        }
</code>```

my validation methods like following.

```<code>extension String {
    func isValidEmail() -> Bool {
        // here, `try!` will always succeed because the pattern is valid
        let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .caseInsensitive)
        return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
    }

    // vrify Valid PhoneNumber or Not
    func isValidPhone() -> Bool {

        let phoneRegex = "^[0-9]{10}$";
        let valid = NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: phoneRegex)
        return valid
    }
}
</code>```

答:
It seems to be the problem in your output validation. Modified your code in following way to work, please validate.</p>

```<code>  extension ViewController {

    func checkValidation() {
      if txtUserName.text == "" {
          print("Enter either valid phone or email 1")
      } else if let validphone = txtUserName.text, validphone.isValidPhone() || validphone.isValidEmail() {
          print("Success")
          forGotPasswordApi()
      }else{
        print("Enter either valid phone or email 2")
      }
    }
  }

  extension String {
      func isValidEmail() -> Bool {
          // here, `try!` will always succeed because the pattern is valid
          let regex = try! NSRegularExpression(pattern: "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,3})$", options: .caseInsensitive)
        let valid = regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
        print("Email validation \(valid)")
          return valid
      }

      // vrify Valid PhoneNumber or Not
      func isValidPhone() -> Bool {

        let regex = try! NSRegularExpression(pattern: "^[0-9]\\d{9}$", options: .caseInsensitive)
        let valid = regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
        print("Mobile validation \(valid)")
          return valid
      }
  }
</code>```

Body:
I having one text field for forgot password ,here user enter either mobile number or email then we send OTP to that.

I am trying to validations for that text field with my code but it is not working, any one give some idea on that please find my code with following.

It needs to valid for either mailid or Phone number format.

if emaiTF.text == "" {
            print("Enter either valid phone or email")
        }else if let validphone = emaiTF.text, validphone.isValidPhone() || validphone.isValidEmail() {
            print("Enter either valid phone or email")
        }else{
            forGotPasswordApi()
        }

my validation methods like following.

extension String {
    func isValidEmail() -> Bool {
        // here, `try!` will always succeed because the pattern is valid
        let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .caseInsensitive)
        return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
    }

    // vrify Valid PhoneNumber or Not
    func isValidPhone() -> Bool {

        let phoneRegex = "^[0-9]{10}$";
        let valid = NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: phoneRegex)
        return valid
    }
}

Body:
It seems to be the problem in your output validation. Modified your code in following way to work, please validate.

  extension ViewController {

    func checkValidation() {
      if txtUserName.text == "" {
          print("Enter either valid phone or email 1")
      } else if let validphone = txtUserName.text, validphone.isValidPhone() || validphone.isValidEmail() {
          print("Success")
          forGotPasswordApi()
      }else{
        print("Enter either valid phone or email 2")
      }
    }
  }

  extension String {
      func isValidEmail() -> Bool {
          // here, `try!` will always succeed because the pattern is valid
          let regex = try! NSRegularExpression(pattern: "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,3})$", options: .caseInsensitive)
        let valid = regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
        print("Email validation \(valid)")
          return valid
      }

      // vrify Valid PhoneNumber or Not
      func isValidPhone() -> Bool {

        let regex = try! NSRegularExpression(pattern: "^[0-9]\\d{9}$", options: .caseInsensitive)
        let valid = regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
        print("Mobile validation \(valid)")
          return valid
      }
  }


问:
i installed 5.1.6-1 dse cassandra after sometime 6.7 version getting installed by it's own

 Package                                             Arch                                 Version                                  Repository                               Size

Removing:
 datastax-agent                                      noarch                               6.7.6-1                                  @DataStax                                74 M
 dse                                                 noarch                               5.1.6-1                                  @DataStax                               170 M
 dse                                                 noarch                               6.7.7-1                                  installed                               288 M
 dse-full                                            noarch                               5.1.6-1                                  @DataStax                               489 k
 dse-full                                            noarch                               6.7.7-1                                  installed                               561 k
 dse-libcassandra                                    noarch                               5.1.6-1                                  @DataStax                                58 M
 dse-libcassandra                                    noarch                               6.7.7-1                                  installed                                63 M
 dse-libgraph                                        noarch                               5.1.6-1                                  @DataStax                                27 M
 dse-libgraph                                        noarch                               6.7.7-1                                  installed                               129 M
 dse-libhadoop2-client                               noarch                               5.1.6-1                                  @DataStax                                63 M
 dse-libhadoop2-client                               noarch                               6.7.7-1                                  installed                                72 M
 dse-liblog4j                                        noarch                               5.1.6-1                                  @DataStax                                13 k
 dse-liblog4j                                        noarch                               6.7.7-1                                  installed                                13 k
 dse-libsolr                                         noarch                               5.1.6-1                                  @DataStax                                83 M
 dse-libsolr                                         noarch                               6.7.7-1                                  installed                                78 M
 dse-libspark                                        noarch                               5.1.6-1                                  @DataStax                               432 M
 dse-libspark                                        noarch                               6.7.7-1                                  installed                               432 M
 dse-libtomcat                                       noarch                               5.1.6-1                                  @DataStax                               8.0 M
 dse-libtomcat                                       noarch                               6.7.7-1                                  installed                               5.8 M

答: Are you trying to figure out why 6.7 was installed, and as you mentioned, "on its own"? If so, that's a pretty hard question to answer, but you could go look at the yum history to see who did it and when. One guess is that you have the Datastax repo as part of your system repo lists, and it's possible that someone tried to patch the system with something similar to "yum update" (without specifying what to update), and the Datastax RPMs were updated with that command. I say that because it accidentally happened where I work. Since then we don't have the Datastax Repo as part of our system repositories any more (we could simply disable it, but we didn't want to leave it to chance that someone may re-enable it by accident). Otherwise, if that's not your question, you'll have to be a bit more specific.</p>


问:
SQL column default value with Entity Framework
I am trying to use Code-First EF6 with default SQL values.

For example, I have a "CreatedDate" column/property not null with a default in SQL of "getdate()"

How do I represent this in my code Model? Currently I have:

```<code><DatabaseGenerated(DatabaseGeneratedOption.Computed)>
Public Property CreatedDate As DateTime
</code>```

Will this work, or will I need to use a nullable even though the actual column should be not null, so EF doesn't send a value when it hasn't been set:

```<code><DatabaseGenerated(DatabaseGeneratedOption.Computed)>
Public Property CreatedDate As DateTime?
</code>```

Or is there a better solution out there?

I don't want EF to handle my defaults - I know this is available to me but not possible in my current situation.

答:
[mysql]

For those, who don't want to use computed and rewrite it after every db update, I wrote extension method for database partial class. Sure, there are thing that has to be improved or added, but for now it is enough for our using, enjoy.

Take into account, that due to database_schema access it is not the fastest and also you need to have same entity name as table name (or rewrite it somehow).

```<code>    public static bool GetDBDefaults(object entity)
    {
        try
        {
            string table_name = entity.GetType().Name;

            string q = $"select column_name, column_default from information_schema.columns where column_default is not null and table_schema not in ('information_schema', 'sys', 'performance_schema', 'mysql') and table_name = '{table_name}' order by table_schema, table_name, ordinal_position;";

            List<DBDefaults> dbDefaults = new List<DBDefaults>();
            using (DatabaseModelFull db = new DatabaseModelFull())
            {
                dbDefaults = db.Database.SqlQuery<DBDefaults>(q).ToList();
            }

            Type myType = entity.GetType();
            IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
            IList<FieldInfo> fields = new List<FieldInfo>(myType.GetFields());

            foreach (var dbDefault in dbDefaults)
            {
                var prop = props.SingleOrDefault(x => x.Name == dbDefault.column_name);

                if (prop != null)
                {
                    if (dbDefault.column_default.Equals("CURRENT_TIMESTAMP"))
                        prop.SetValue(entity, System.Convert.ChangeType(DateTime.Now, prop.PropertyType));
                    else
                        prop.SetValue(entity, System.Convert.ChangeType(dbDefault.column_default, prop.PropertyType));
                    continue;
                }

                var field = fields.SingleOrDefault(x => x.Name == dbDefault.column_name);

                if (field != null)
                {
                    if (dbDefault.column_default.Equals("CURRENT_TIMESTAMP"))
                        field.SetValue(entity, System.Convert.ChangeType(DateTime.Now, field.FieldType));
                    else
                        field.SetValue(entity, System.Convert.ChangeType(dbDefault.column_default, field.FieldType));
                }
            }
            return true;
        }
        catch
        {
            return false;
        }
    }

    public class DBDefaults
    {
        public string column_name { get; set; }
        public string column_default { get; set; }
    }
</code>```

Body:
I am trying to use Code-First EF6 with default SQL values.

For example, I have a "CreatedDate" column/property not null with a default in SQL of "getdate()"

How do I represent this in my code Model? Currently I have:

<DatabaseGenerated(DatabaseGeneratedOption.Computed)>
Public Property CreatedDate As DateTime

Will this work, or will I need to use a nullable even though the actual column should be not null, so EF doesn't send a value when it hasn't been set:

<DatabaseGenerated(DatabaseGeneratedOption.Computed)>
Public Property CreatedDate As DateTime?

Or is there a better solution out there?

I don't want EF to handle my defaults - I know this is available to me but not possible in my current situation.

Body:
[mysql]

For those, who don't want to use computed and rewrite it after every db update, I wrote extension method for database partial class. Sure, there are thing that has to be improved or added, but for now it is enough for our using, enjoy.

Take into account, that due to database_schema access it is not the fastest and also you need to have same entity name as table name (or rewrite it somehow).

    public static bool GetDBDefaults(object entity)
    {
        try
        {
            string table_name = entity.GetType().Name;

            string q = $"select column_name, column_default from information_schema.columns where column_default is not null and table_schema not in ('information_schema', 'sys', 'performance_schema', 'mysql') and table_name = '{table_name}' order by table_schema, table_name, ordinal_position;";

            List<DBDefaults> dbDefaults = new List<DBDefaults>();
            using (DatabaseModelFull db = new DatabaseModelFull())
            {
                dbDefaults = db.Database.SqlQuery<DBDefaults>(q).ToList();
            }

            Type myType = entity.GetType();
            IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
            IList<FieldInfo> fields = new List<FieldInfo>(myType.GetFields());

            foreach (var dbDefault in dbDefaults)
            {
                var prop = props.SingleOrDefault(x => x.Name == dbDefault.column_name);

                if (prop != null)
                {
                    if (dbDefault.column_default.Equals("CURRENT_TIMESTAMP"))
                        prop.SetValue(entity, System.Convert.ChangeType(DateTime.Now, prop.PropertyType));
                    else
                        prop.SetValue(entity, System.Convert.ChangeType(dbDefault.column_default, prop.PropertyType));
                    continue;
                }

                var field = fields.SingleOrDefault(x => x.Name == dbDefault.column_name);

                if (field != null)
                {
                    if (dbDefault.column_default.Equals("CURRENT_TIMESTAMP"))
                        field.SetValue(entity, System.Convert.ChangeType(DateTime.Now, field.FieldType));
                    else
                        field.SetValue(entity, System.Convert.ChangeType(dbDefault.column_default, field.FieldType));
                }
            }
            return true;
        }
        catch
        {
            return false;
        }
    }

    public class DBDefaults
    {
        public string column_name { get; set; }
        public string column_default { get; set; }
    }


问:
Passing JSON File to PM2 as a node argument
I have a NodeJS app which needs to start the server with the following parameter: start server.js --config=config.json. Then in the server.js I use NodeUtils.getArgs() and
JSON.parse() to get all the parameters of the config.json file. This works well.

Now, I want to start the server with PM2, but I am not being able.

If I try with pm2 start server.js --node-args"--config=config.json" I get a node: bad option: --config=config.json. I tried with a lot of options but none of them works.

How can I do it? Thanks

EDIT: After starting pm2, if it gets an error, you must pm2 delete all.

答:
You can pass your own arguments after --, so you can do this:

pm2 start server.js -- -config=config.json
```


问:
How to get the value of the last assert statement?
Is there an easy way to get the value of the last assert as boolean so I can avoid asking for it twice?

Example:

```<code>assert 1 == 2
status = ???? # how can i get the boolean value of the previous assert
</code>```

I do not want just as i want the nice reporting feature of assert in pytest

```<code>test = 1 == 2
assert test
</code>```

答:
In Python 3.8, you can use the new assignment expression (walrus operator):

```<code>>>> assert (test := 1 == 1)
>>> print(test)

True
</code>```

However, note that if the assertion fails, you will not get to the print statement because assert raises an AssertionError exception. If you want to use the value in the error message, you can do following:

```<code>>>> assert (test := 1 == 2), f"Value was '{test}'."

AssertionError: Value was 'False'.
</code>```

Body:
Is there an easy way to get the value of the last assert as boolean so I can avoid asking for it twice?

Example:

assert 1 == 2
status = ???? # how can i get the boolean value of the previous assert

I do not want just as i want the nice reporting feature of assert in pytest

test = 1 == 2
assert test

Body:
In Python 3.8, you can use the new assignment expression (walrus operator):

>>> assert (test := 1 == 1)
>>> print(test)

True

However, note that if the assertion fails, you will not get to the print statement because assert raises an AssertionError exception. If you want to use the value in the error message, you can do following:

>>> assert (test := 1 == 2), f"Value was '{test}'."

AssertionError: Value was 'False'.


问:
multiple histograms on top of eachother without bins
Let's say I've got this dataframe with 2 levels. LC and HC.
Now i want to get 2 plots like below on top of eachother.

```<code>data <- data.frame(
    welltype=c("LC","LC","LC","LC","LC","HC","HC","HC","HC","HC"),
    value=c(1,2,1,2,1,5,4,5,4,5))
</code>```

The code to get following plot =

```<code>x <- rnorm(1000)
y <- hist(x)
plot(y$breaks,
   c(y$counts,0),
   type="s",col="blue")
</code>```

(with thanks to Joris Meys)

So, how do I even start on this. Since I'm used to java I was thinking of a for loop, but I've been told not to do it this way.

答:
You can use the same code except with points instead of plot for adding additional lines to the plot.

Making up some data

```<code>set.seed(5)
d <- data.frame(x=c(rnorm(1000)+3, rnorm(1000)),
                g=rep(1:2, each=1000) )
</code>```

And doing it in a fairly straightforward way:

```<code>x1 <- d$x[d$g==1]
x2 <- d$x[d$g==2]
y1 <- hist(x1, plot=FALSE)
y2 <- hist(x2, plot=FALSE)
plot(y1$breaks, c(y1$counts,0), type="s",col="blue",
     xlim=range(c(y1$breaks, y2$breaks)), ylim=range(c(0,y1$counts, y2$counts)))
points(y2$breaks, c(y2$counts,0), type="s", col="red")
</code>```

Or in a more R-ish way:

```<code>col <- c("blue", "red")
ds <- split(d$x, d$g)
hs <- lapply(ds, hist, plot=FALSE)
plot(0,0,type="n",
     ylim=range(c(0,unlist(lapply(hs, function(x) x$counts)))),
     xlim=range(unlist(lapply(hs, function(x) x$breaks))) )
for(i in seq_along(hs)) {
  points(hs[[i]]$breaks, c(hs[[i]]$counts,0), type="s", col=col[i])
}
</code>```

EDIT: Inspired by Joris's answer, I'll note that lattice can also easily do overlapping density plots.

```<code>library(lattice)
densityplot(~x, group=g, data=d)
</code>```

Body:
Let's say I've got this dataframe with 2 levels. LC and HC.
Now i want to get 2 plots like below on top of eachother.

data <- data.frame(
    welltype=c("LC","LC","LC","LC","LC","HC","HC","HC","HC","HC"),
    value=c(1,2,1,2,1,5,4,5,4,5))

The code to get following plot =

x <- rnorm(1000)
y <- hist(x)
plot(y$breaks,
   c(y$counts,0),
   type="s",col="blue")

(with thanks to Joris Meys)

So, how do I even start on this. Since I'm used to java I was thinking of a for loop, but I've been told not to do it this way.

Body:
You can use the same code except with points instead of plot for adding additional lines to the plot.

Making up some data

set.seed(5)
d <- data.frame(x=c(rnorm(1000)+3, rnorm(1000)),
                g=rep(1:2, each=1000) )

And doing it in a fairly straightforward way:

x1 <- d$x[d$g==1]
x2 <- d$x[d$g==2]
y1 <- hist(x1, plot=FALSE)
y2 <- hist(x2, plot=FALSE)
plot(y1$breaks, c(y1$counts,0), type="s",col="blue",
     xlim=range(c(y1$breaks, y2$breaks)), ylim=range(c(0,y1$counts, y2$counts)))
points(y2$breaks, c(y2$counts,0), type="s", col="red")

Or in a more R-ish way:

col <- c("blue", "red")
ds <- split(d$x, d$g)
hs <- lapply(ds, hist, plot=FALSE)
plot(0,0,type="n",
     ylim=range(c(0,unlist(lapply(hs, function(x) x$counts)))),
     xlim=range(unlist(lapply(hs, function(x) x$breaks))) )
for(i in seq_along(hs)) {
  points(hs[[i]]$breaks, c(hs[[i]]$counts,0), type="s", col=col[i])
}

EDIT: Inspired by Joris's answer, I'll note that lattice can also easily do overlapping density plots.

library(lattice)
densityplot(~x, group=g, data=d)


问:
Neo4j WHERE IN queries
I'm a graph DB relative n00b, have been playing with Neo4j (via Ruby ActiveRecord, but I don't think that's relevant), very much enjoying it but have found some counter-intuitive behaviour.

My problem involves getting some data from the DB, pulling it back to my Ruby code, doing some processing, then making a second query with the set of ids identified by this external processing (it is too complicated to do in the DB).  The result is an ActiveRecord query like

```<code>Foo.where(foo_id: foo_ids)...
</code>```

which translates to a Cypher query like

```<code>MATCH (foo:Foo) WHERE foo.foo_id IN [1, 5, ...] ...
</code>```

The set of ids is largish, a few tens of thousands, and I'm finding this query really rather slow.  The foo_id has a unique constraint, and my experience in RDBMSs shouts that it shouldn't be.  Is this just a the way things are or am I ignorant of the proper "graphy" way of doing things?

答:
you need to create index on foo_id .
After that , instead of checking in array
you can unwind that array and match like following </p>

```<code>UNWIND [1,4,5,.....] as id
MATCH (foo : Foo{foo_id:id})
RETURN foo
</code>```

Title: Neo4j WHERE IN queries

Body:
I'm a graph DB relative n00b, have been playing with Neo4j (via Ruby ActiveRecord, but I don't think that's relevant), very much enjoying it but have found some counter-intuitive behaviour.

My problem involves getting some data from the DB, pulling it back to my Ruby code, doing some processing, then making a second query with the set of ids identified by this external processing (it is too complicated to do in the DB).  The result is an ActiveRecord query like

Foo.where(foo_id: foo_ids)...

which translates to a Cypher query like

MATCH (foo:Foo) WHERE foo.foo_id IN [1, 5, ...] ...

The set of ids is largish, a few tens of thousands, and I'm finding this query really rather slow.  The foo_id has a unique constraint, and my experience in RDBMSs shouts that it shouldn't be.  Is this just a the way things are or am I ignorant of the proper "graphy" way of doing things?

Body:
you need to create index on foo_id .
After that , instead of checking in array
you can unwind that array and match like following

UNWIND [1,4,5,.....] as id
MATCH (foo : Foo{foo_id:id})
RETURN foo


问:
Gitlab runner fail to use cache with minio
I installed a self-hosted Gitlab using the Helm chart on a Kubernetes cluster.
Everything is working fine except one thing: the cache.

In my .gitlab-ci.yml file I have

```<code>cache:
  paths:
    - .m2/repository/
    - target/
</code>```

But when running the job I have this warning when trying to download the cache:

```<code>WARNING: Retrying...
error=Get https://minio.mydomain.com/runner-cache/gitlab-runner/project/6/default?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=xxx: x509: certificate signed by unknown authority
</code>```

And when uploading I have:

```<code>WARNING: Retrying...                                error=received: 501 Not Implemented
Uploading cache.zip to https://minio.mydomain.com/runner-cache/gitlab-runner/project/6/default
FATAL: received: 501 Not Implemented
</code>```

But the certificate is provided by LetsEncrypt so it's not an unknown authority. When I go on minio.mydomain.com I can see that the connection is secure

I've also check that the runner is using the right credentials and yes it is.

I'm kind of lost here. Any hints is welcome.

Thanks.

答:
You need to add the CA to the image that is hosting the cache.

You can follow these instructions from this gitlab issue for a workaround:

Update the helper image to have the ca chain for the self-signed certificate trusted.

```<code>FROM gitlab/gitlab-runner-helper:x86_64-latest

RUN apk add --no-cache ca-certificates

COPY ca.crt /usr/local/share/ca-certificates/ca.crt

RUN update-ca-certificates

RUN rm /usr/local/share/ca-certificates/ca.crt
</code>```

docker build -t registry.gitlab.com/namespace/project/tools/gitlab-runner-helper:$SOME_TAG

Override the helper image used by GitLab by updating the config.toml to use the image you just build with the correct CA trusted.

If you are using the helm chart you can define KUBERNETES_HELPER_CPU_LIMIT environment variable and define it in envVars

Hope this helps.

Body:
I installed a self-hosted Gitlab using the Helm chart on a Kubernetes cluster.
Everything is working fine except one thing: the cache.

In my .gitlab-ci.yml file I have

cache:
  paths:
    - .m2/repository/
    - target/

But when running the job I have this warning when trying to download the cache:

WARNING: Retrying...
error=Get https://minio.mydomain.com/runner-cache/gitlab-runner/project/6/default?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=xxx: x509: certificate signed by unknown authority

And when uploading I have:

WARNING: Retrying...                                error=received: 501 Not Implemented
Uploading cache.zip to https://minio.mydomain.com/runner-cache/gitlab-runner/project/6/default
FATAL: received: 501 Not Implemented

But the certificate is provided by LetsEncrypt so it's not an unknown authority. When I go on minio.mydomain.com I can see that the connection is secure

I've also check that the runner is using the right credentials and yes it is.

I'm kind of lost here. Any hints is welcome.

Thanks.

Body:
You need to add the CA to the image that is hosting the cache.

You can follow these instructions from this gitlab issue for a workaround:

Update the helper image to have the ca chain for the self-signed certificate trusted.

FROM gitlab/gitlab-runner-helper:x86_64-latest

RUN apk add --no-cache ca-certificates

COPY ca.crt /usr/local/share/ca-certificates/ca.crt

RUN update-ca-certificates

RUN rm /usr/local/share/ca-certificates/ca.crt

docker build -t registry.gitlab.com/namespace/project/tools/gitlab-runner-helper:$SOME_TAG

Override the helper image used by GitLab by updating the config.toml to use the image you just build with the correct CA trusted.

If you are using the helm chart you can define KUBERNETES_HELPER_CPU_LIMIT environment variable and define it in envVars

Hope this helps.


问:
Howto generate Java Enum from XML Schema with JAXB?
I am using the maven plugin maven-jaxb2-plugin to generate POJOs from a XSD Schema file.
This works fine. The only thing, thats really bothering me is, that the xml schema enumerations are not mapped in a Java Enum Type.

My maven plugin is generating the java pojos from a file I called schemachooser.xsd

schemachooser.xsd:

```<code><?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:sch="http://www.ascc.net/xml/schematron"
targetNamespace="http://schema.something" elementFormDefault="qualified"
version="1.0" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
jaxb:extensionBindingPrefixes="xjc" jaxb:version="1.0">

<xs:annotation>
    <xs:appinfo>
        <jaxb:globalBindings generateIsSetMethod="true" fixedAttributeAsConstantProperty="true">
            <xjc:serializable />
        </jaxb:globalBindings>
        <jaxb:schemaBindings>
           <jaxb:bindings node="//xsd:element[@name='ElementName']/xsd:simpleType">
               <jaxb:typesafeEnumClass name="MyEnumType" />
           </jaxb:bindings>
        </jaxb:schemaBindings>
    </xs:appinfo>
</xs:annotation>

<xs:include schemaLocation="myNormalSchema.xsd" />

</schema>
</code>```

It does generate the files, but not the "new" Enum Class "MyEnumType". Am I using the bindings wrong?

答:
If you want to keep the JAXB annotations separate from the XML schema then you need to use an JAXB bindings file:

bindings.xml

```<code><jaxb:bindings
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
    xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
    jaxb:extensionBindingPrefixes="xjc"
    version="2.1">
    <jaxb:globalBindings generateIsSetMethod="true" fixedAttributeAsConstantProperty="true">
        <xjc:serializable />
    </jaxb:globalBindings>
    <jaxb:bindings schemaLocation="myNormalSchema.xsd">
        <jaxb:bindings node="//xs:element[@name='ElementName']/xs:simpleType">
               <jaxb:typesafeEnumClass name="MyEnumType" />
        </jaxb:bindings>
   </jaxb:bindings>
</jaxb:bindings>
</code>```

myNormalSchema.xsd

Below is a sample XML schema that a reverse engineered from your question:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema
    targetNamespace="http://www.example.com"
     xmlns="http://www.example.com"
     xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xs:element name="ElementName">
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:enumeration value="MY_ENUM_1"/>
                <xs:enumeration value="MY_ENUM_2"/>
            </xs:restriction>
        </xs:simpleType>
   </xs:element>

    <xs:element name="Root">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="ElementName"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

</xs:schema>
</code>```

XJC Call

```<code>xjc -extension -d out -b bindings.xml myNormalSchema.xsd
</code>```

MyEnumType

One of the generated classes is an enum called MyEnumType.

```<code>package com.example;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

@XmlType(name = "")
@XmlEnum
public enum MyEnumType {

    MY_ENUM_1,
    MY_ENUM_2;

    public String value() {
        return name();
    }

    public static MyEnumType fromValue(String v) {
        return valueOf(v);
    }

}
</code>```

Root

Also the Root class is generated with the isSet method:

```<code>package com.example;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "elementName"
})
@XmlRootElement(name = "Root")
public class Root
    implements Serializable
{

    @XmlElement(name = "ElementName", required = true)
    protected MyEnumType elementName;

    public MyEnumType getElementName() {
        return elementName;
    }

    public void setElementName(MyEnumType value) {
        this.elementName = value;
    }

    public boolean isSetElementName() {
        return (this.elementName!= null);
    }

}
</code>```

Examples

http://bdoughan.blogspot.com/2011/05/schema-to-java-xmlmimetype.html

http://bdoughan.blogspot.com/2011/04/xml-schema-to-java-xsd-choice.html

Body:
I am using the maven plugin maven-jaxb2-plugin to generate POJOs from a XSD Schema file.
This works fine. The only thing, thats really bothering me is, that the xml schema enumerations are not mapped in a Java Enum Type.

My maven plugin is generating the java pojos from a file I called schemachooser.xsd

schemachooser.xsd:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:sch="http://www.ascc.net/xml/schematron"
targetNamespace="http://schema.something" elementFormDefault="qualified"
version="1.0" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
jaxb:extensionBindingPrefixes="xjc" jaxb:version="1.0">

<xs:annotation>
    <xs:appinfo>
        <jaxb:globalBindings generateIsSetMethod="true" fixedAttributeAsConstantProperty="true">
            <xjc:serializable />
        </jaxb:globalBindings>
        <jaxb:schemaBindings>
           <jaxb:bindings node="//xsd:element[@name='ElementName']/xsd:simpleType">
               <jaxb:typesafeEnumClass name="MyEnumType" />
           </jaxb:bindings>
        </jaxb:schemaBindings>
    </xs:appinfo>
</xs:annotation>

<xs:include schemaLocation="myNormalSchema.xsd" />

</schema>

It does generate the files, but not the "new" Enum Class "MyEnumType". Am I using the bindings wrong?

Body:
If you want to keep the JAXB annotations separate from the XML schema then you need to use an JAXB bindings file:

bindings.xml

<jaxb:bindings
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
    xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
    jaxb:extensionBindingPrefixes="xjc"
    version="2.1">
    <jaxb:globalBindings generateIsSetMethod="true" fixedAttributeAsConstantProperty="true">
        <xjc:serializable />
    </jaxb:globalBindings>
    <jaxb:bindings schemaLocation="myNormalSchema.xsd">
        <jaxb:bindings node="//xs:element[@name='ElementName']/xs:simpleType">
               <jaxb:typesafeEnumClass name="MyEnumType" />
        </jaxb:bindings>
   </jaxb:bindings>
</jaxb:bindings>

myNormalSchema.xsd

Below is a sample XML schema that a reverse engineered from your question:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
    targetNamespace="http://www.example.com"
     xmlns="http://www.example.com"
     xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xs:element name="ElementName">
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:enumeration value="MY_ENUM_1"/>
                <xs:enumeration value="MY_ENUM_2"/>
            </xs:restriction>
        </xs:simpleType>
   </xs:element>

    <xs:element name="Root">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="ElementName"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

</xs:schema>

XJC Call

xjc -extension -d out -b bindings.xml myNormalSchema.xsd

MyEnumType

One of the generated classes is an enum called MyEnumType.

package com.example;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

@XmlType(name = "")
@XmlEnum
public enum MyEnumType {

    MY_ENUM_1,
    MY_ENUM_2;

    public String value() {
        return name();
    }

    public static MyEnumType fromValue(String v) {
        return valueOf(v);
    }

}

Root

Also the Root class is generated with the isSet method:

package com.example;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "elementName"
})
@XmlRootElement(name = "Root")
public class Root
    implements Serializable
{

    @XmlElement(name = "ElementName", required = true)
    protected MyEnumType elementName;

    public MyEnumType getElementName() {
        return elementName;
    }

    public void setElementName(MyEnumType value) {
        this.elementName = value;
    }

    public boolean isSetElementName() {
        return (this.elementName!= null);
    }

}

Examples

http://bdoughan.blogspot.com/2011/05/schema-to-java-xmlmimetype.html

http://bdoughan.blogspot.com/2011/04/xml-schema-to-java-xsd-choice.html


问:
Data-augmentation generators not working with TensorFlow 2.0
I am trying to train model with image data-augmentation generators on TensorFlow 2.0, after downloading Kaggle's cats_vs_dogs dataset using below code.

train_datagen = ImageDataGenerator(rescale=1. / 255,
                                   rotation_range=40,
                                   width_shift_range=0.2,
                                   height_shift_range=0.2,
                                   shear_range=0.2,
                                   zoom_range=0.2,
                                   horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(train_dir,
                                                    target_size=(150, 150),
                                                    batch_size=32,
                                                    class_mode='binary')

validation_generator = test_datagen.flow_from_directory(validation_dir,
                                                    target_size=(150, 150),
                                                    batch_size=32,
                                                    class_mode='binary')

history = model.fit_generator(train_generator,
                              steps_per_epoch=100,
                              epochs=100,
                              validation_data=validation_generator,
                              validation_steps=50)
```

<p>But on first epoch, getting this error: </p>

<pre class="lang-py prettyprint-override"><code>Found 2000 images belonging to 2 classes.
Found 1000 images belonging to 2 classes.
WARNING:tensorflow:From <ipython-input-18-e571f2719e1b>:27: Model.fit_generator (from tensorflow.python.keras.engine.training) is deprecated and will be removed in a future version.
Instructions for updating:
Please use Model.fit, which supports generators.
WARNING:tensorflow:sample_weight modes were coerced from
  ...
    to
  ['...']
WARNING:tensorflow:sample_weight modes were coerced from
  ...
    to
  ['...']
Train for 100 steps, validate for 50 steps
Epoch 1/100
 63/100 [=================>............] - ETA: 59s - loss: 0.7000 - accuracy: 0.5000 WARNING:tensorflow:Your input ran out of data; interrupting training. Make sure that your dataset or generator can generate at least `steps_per_epoch * epochs` batches (in this case, 10000 batches). You may need to use the repeat() function when building your dataset.
</code>```

How should I modify the above code base for TensorFlow 2?

答:
The kaggle dataset contain 25000 training examples. The error message states that:

Blockquote tensorflow:Your input ran out of data; interrupting training. Make sure that your dataset or generator can generate at least steps_per_epoch * epochs batches (in this case, 10000 batches). You may need to use the repeat() function when building your dataset.

Which means the data generator needs to generate at least 10000 batches. But with the current batch size of 32 the generator would produce only 25000 / 32 is approximately equal to 781 batches. My suggestion is try to reduce the steps_per_epoch or epochs and try.

You can get rid of the deprecation message by passing the generator object to model.fit(...) instead of model.fit_generator

Body:
I am trying to train model with image data-augmentation generators on TensorFlow 2.0, after downloading Kaggle's cats_vs_dogs dataset using below code.

train_datagen = ImageDataGenerator(rescale=1. / 255,
                                   rotation_range=40,
                                   width_shift_range=0.2,
                                   height_shift_range=0.2,
                                   shear_range=0.2,
                                   zoom_range=0.2,
                                   horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(train_dir,
                                                    target_size=(150, 150),
                                                    batch_size=32,
                                                    class_mode='binary')

validation_generator = test_datagen.flow_from_directory(validation_dir,
                                                    target_size=(150, 150),
                                                    batch_size=32,
                                                    class_mode='binary')

history = model.fit_generator(train_generator,
                              steps_per_epoch=100,
                              epochs=100,
                              validation_data=validation_generator,
                              validation_steps=50)

But on first epoch, getting this error:

Found 2000 images belonging to 2 classes.
Found 1000 images belonging to 2 classes.
WARNING:tensorflow:From <ipython-input-18-e571f2719e1b>:27: Model.fit_generator (from tensorflow.python.keras.engine.training) is deprecated and will be removed in a future version.
Instructions for updating:
Please use Model.fit, which supports generators.
WARNING:tensorflow:sample_weight modes were coerced from
  ...
    to
  ['...']
WARNING:tensorflow:sample_weight modes were coerced from
  ...
    to
  ['...']
Train for 100 steps, validate for 50 steps
Epoch 1/100
 63/100 [=================>............] - ETA: 59s - loss: 0.7000 - accuracy: 0.5000 WARNING:tensorflow:Your input ran out of data; interrupting training. Make sure that your dataset or generator can generate at least `steps_per_epoch * epochs` batches (in this case, 10000 batches). You may need to use the repeat() function when building your dataset.

How should I modify the above code base for TensorFlow 2?


问:
The code will count the number of times a name appears in a column and will analyze the date when the data was stored in different Sheets
I updated the code with the suggestions and worl, thank you all

But, I have another problem. I need to do this for every month of the year and for all the names on the worksheet (about 20 names).

This way the code will be very long, do you have any suggestions to make it more automated?

'''

```<code>Sub CountHSEcards()

Sub CountHSEcards()

Dim Sh As Worksheet
Dim Br As Worksheet
Set Sh = Sheets("Planilha1")
Set Br = Sheets("Brasil")

NultimaCelula = Sh.Cells(Sh.Rows.Count, "A").End(xlUp).Row

For i = 1 To NultimaCelula

    If InStr(Sh.Range(CStr("AD" & i + 1)).Value, "Lucas") > 0 Then

        If Month(Sh.Range("AC" & i + 1).Value) = 1 Then
            Br.Range("C4") = Br.Range("C4").Value + 1
        End If

    End If

Next i

End Sub
</code>```

'''

答:
Thanks guys, with the help of the comments, the code worked well</p>

```<code>Sub CountHSEcards()

Dim Sh As Worksheet
Dim Br As Worksheet
Set Sh = Sheets("Banco De Dados")
Set Br = Sheets("Brasil")
Dim z As Integer
Dim h As Integer

NultimaCelula = Sh.Cells(Sh.Rows.Count, "A").End(xlUp).Row

Br.Range("C4" & ":C1000") = Empty
z = 17
h = 16
For i = 1 To NultimaCelula

    For x = 1 To 12

        If InStr(Sh.Range(CStr("AD" & i + 1)).Value, "Andrea Ramos") > 0 Then

            If Month(Sh.Range("C" & i + 1).Value) = x Then
                Br.Range("C" & x + 3) = Br.Range("C" & x + 3).Value + 1
                Br.Range("C16").FormulaLocal = WorksheetFunction.Sum(Range("C4:C15"))
            End If

        End If

    Next x
Next i

End Sub
</code>```

Body:
I updated the code with the suggestions and worl, thank you all

But, I have another problem. I need to do this for every month of the year and for all the names on the worksheet (about 20 names).

This way the code will be very long, do you have any suggestions to make it more automated?

'''

Sub CountHSEcards()

Sub CountHSEcards()

Dim Sh As Worksheet
Dim Br As Worksheet
Set Sh = Sheets("Planilha1")
Set Br = Sheets("Brasil")

NultimaCelula = Sh.Cells(Sh.Rows.Count, "A").End(xlUp).Row

For i = 1 To NultimaCelula

    If InStr(Sh.Range(CStr("AD" & i + 1)).Value, "Lucas") > 0 Then

        If Month(Sh.Range("AC" & i + 1).Value) = 1 Then
            Br.Range("C4") = Br.Range("C4").Value + 1
        End If

    End If

Next i

End Sub

'''

Body:
Thanks guys, with the help of the comments, the code worked well

Sub CountHSEcards()

Dim Sh As Worksheet
Dim Br As Worksheet
Set Sh = Sheets("Banco De Dados")
Set Br = Sheets("Brasil")
Dim z As Integer
Dim h As Integer

NultimaCelula = Sh.Cells(Sh.Rows.Count, "A").End(xlUp).Row

Br.Range("C4" & ":C1000") = Empty
z = 17
h = 16
For i = 1 To NultimaCelula

    For x = 1 To 12

        If InStr(Sh.Range(CStr("AD" & i + 1)).Value, "Andrea Ramos") > 0 Then

            If Month(Sh.Range("C" & i + 1).Value) = x Then
                Br.Range("C" & x + 3) = Br.Range("C" & x + 3).Value + 1
                Br.Range("C16").FormulaLocal = WorksheetFunction.Sum(Range("C4:C15"))
            End If

        End If

    Next x
Next i

End Sub


问:
Export all files name in all disks powershell
I have to export the names of all the files on all the disks on some machines.
At the moment I have this command line.

```<code>$date = (Get-Date).tostring("dd-MM-yyyy")
gci . *.* -rec | where { ! $_.PSIsContainer} | Select-Object FullName | Export-Csv -Delimiter ";" C:\$env:COMPUTERNAME'_'FilesAudit'_'$date.csv -NoTypeInformation
</code>```

The problem is that if I execute this code, it only extracts the information from the disk I am running and not from the other disks.

I don't know how I can get the information from the other disks, and as an extra problem, each machine has different disks, for example, C: + D: or C: + E: or C: + F: + Q: etc..

Someone has some idea how to help me.

Thank you so much.

答:
Seeing your latest comment, you are using a foreach loop without capturing anything, and after that the Export-Csv would want to know what it is you are exporting.

If you use a ForEach-Object instead of foreach ($drive in $drives), you can use the $_ automatic variable, PLUS you can pipe the result to the Export-Csv cmdlet.

```<code># create the CSV filename to output
$outFile = 'C:\{0}_FilesAudit_{1:dd-MM-yyyy}.csv' -f $env:COMPUTERNAME, (Get-Date)
Get-PSDrive -PSProvider FileSystem | ForEach-Object {
    # if your PowerShell version is less than 3.0 you'll need
    # Get-ChildItem $_.Root -Recurse | Where-Object {!$_.PSIsContainer} |
    Get-ChildItem $_.Root -Recurse -File -ErrorAction SilentlyContinue |
        Select-Object @{Name = 'FileName'; Expression = {$_.FullName}}   # maybe also select the Length property?
} | Export-Csv -Path $outFile -Delimiter ';' -NoTypeInformation
</code>```

The -ErrorAction SilentlyContinue lets you continue iterating, even if you do not have permissions on any of the drives/folders, which is often the case on the C: drive.

This means you probably won't get a complete listing of all files.

Having said that, are you sure you have permission to write the output CSV file on C: ?

Body:
I have to export the names of all the files on all the disks on some machines.
At the moment I have this command line.

$date = (Get-Date).tostring("dd-MM-yyyy")
gci . *.* -rec | where { ! $_.PSIsContainer} | Select-Object FullName | Export-Csv -Delimiter ";" C:\$env:COMPUTERNAME'_'FilesAudit'_'$date.csv -NoTypeInformation

The problem is that if I execute this code, it only extracts the information from the disk I am running and not from the other disks.

I don't know how I can get the information from the other disks, and as an extra problem, each machine has different disks, for example, C: + D: or C: + E: or C: + F: + Q: etc..

Someone has some idea how to help me.

Thank you so much.

Body:
Seeing your latest comment, you are using a foreach loop without capturing anything, and after that the Export-Csv would want to know what it is you are exporting.

If you use a ForEach-Object instead of foreach ($drive in $drives), you can use the $_ automatic variable, PLUS you can pipe the result to the Export-Csv cmdlet.

# create the CSV filename to output
$outFile = 'C:\{0}_FilesAudit_{1:dd-MM-yyyy}.csv' -f $env:COMPUTERNAME, (Get-Date)
Get-PSDrive -PSProvider FileSystem | ForEach-Object {
    # if your PowerShell version is less than 3.0 you'll need
    # Get-ChildItem $_.Root -Recurse | Where-Object {!$_.PSIsContainer} |
    Get-ChildItem $_.Root -Recurse -File -ErrorAction SilentlyContinue |
        Select-Object @{Name = 'FileName'; Expression = {$_.FullName}}   # maybe also select the Length property?
} | Export-Csv -Path $outFile -Delimiter ';' -NoTypeInformation

The -ErrorAction SilentlyContinue lets you continue iterating, even if you do not have permissions on any of the drives/folders, which is often the case on the C: drive.

This means you probably won't get a complete listing of all files.

Having said that, are you sure you have permission to write the output CSV file on C: ?


答:
Email Validation

Pass your string in the below method

The Below Method will return Bool Value YES or NO

Method :

```<code> func isValidEmail(testStr:String) -> Bool {
    // print("validate calendar: \(testStr)")
    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"

    let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
    return emailTest.evaluate(with: testStr)
}
</code>```

Usage :

```<code>if isValidEmail(testStr: emailTxtFld.text!) == True {

       print("Valid");
 }
else {

    print("In Valid");
 }
</code>```

Title: TextField either phone number or Email format validation swift?

Body:
I having one text field for forgot password ,here user enter either mobile number or email then we send OTP to that.

I am trying to validations for that text field with my code but it is not working, any one give some idea on that please find my code with following.

It needs to valid for either mailid or Phone number format.

if emaiTF.text == "" {
            print("Enter either valid phone or email")
        }else if let validphone = emaiTF.text, validphone.isValidPhone() || validphone.isValidEmail() {
            print("Enter either valid phone or email")
        }else{
            forGotPasswordApi()
        }

my validation methods like following.

extension String {
    func isValidEmail() -> Bool {
        // here, `try!` will always succeed because the pattern is valid
        let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .caseInsensitive)
        return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
    }

    // vrify Valid PhoneNumber or Not
    func isValidPhone() -> Bool {

        let phoneRegex = "^[0-9]{10}$";
        let valid = NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: phoneRegex)
        return valid
    }
}

Body:
Email Validation

Pass your string in the below method

The Below Method will return Bool Value YES or NO

Method :

 func isValidEmail(testStr:String) -> Bool {
    // print("validate calendar: \(testStr)")
    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"

    let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
    return emailTest.evaluate(with: testStr)
}

Usage :

if isValidEmail(testStr: emailTxtFld.text!) == True {

       print("Valid");
 }
else {

    print("In Valid");
 }


答:
I've updated the code you've provided a little bit by changing the validation checks. I think validInput.isValidPhone() || validInput.isValidEmail() is not handled right on your code.

```<code>// Check if any input is entered and not empty string
guard let validInput = emaiTF.text, validInput != "" else {
  print("Enter either valid phone or email")
  return
}

// Check if entered value is valid or not
if validInput.isValidPhone() || validInput.isValidEmail() {
  forGotPasswordApi()
} else {
  print("Enter either valid phone or email")
}
</code>```

Body:
I've updated the code you've provided a little bit by changing the validation checks. I think validInput.isValidPhone() || validInput.isValidEmail() is not handled right on your code.

// Check if any input is entered and not empty string
guard let validInput = emaiTF.text, validInput != "" else {
  print("Enter either valid phone or email")
  return
}

// Check if entered value is valid or not
if validInput.isValidPhone() || validInput.isValidEmail() {
  forGotPasswordApi()
} else {
  print("Enter either valid phone or email")
}


问:
please wait while jenkins is restarting- waiting long
I updated some plugins and restarted the jenkins but now it says:

Please wait while Jenkins is restarting

Your browser will reload automatically when Jenkins is ready.

It is taking too much time (waiting from last 40 minutes). I have only 1 project with around 20 builds. I have restarted jenkins many times and worked fine but now it stucks.
Is there any way out to kill/suspend jenkins to avoid this wait?

答:
I try to fix a file named hudson.model.UpdateCenter.xml located /var/lib/jenkins

I change the URL to https://mirrors.tuna.tsinghua.edu.cn/jenkins/updates/update-center.json

Finally, restart Jenkins. it solves my problem


问:
Custom markers icons not displayed on android
I have this code :

```<code>this.service.getListe(data).forEach((data: any) => {
    const marker: Marker = this.map.addMarkerSync(data);
    marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe((params) => {
        this.click(params);
    });
});
</code>```

Now the getListe() looks like :

```<code>getListe(merchants: any) {
    const Liste: BaseArrayClass<any> = new BaseArrayClass<any>();
    merchants.map(item => {
        Liste.push({
            title: item.name,
            animation: 'DROP',
            position: {
                lat: item.lat,
                lng: item.long
            },
            icon: 'http://icons.iconarchive.com/icons/iconarchive/red-orb-alphabet/24/Number-1-icon.png',
            disableAutoPan: true
        });
    });

    return Markers;
}
</code>```

I tried and like this :

```<code>icon: {
    url: 'http://icons.iconarchive.com/icons/iconarchive/red-orb-alphabet/24/Number-1-icon.png'
}
</code>```

But the same behaviour, the problem is that on emulator and on real device the icon is not changing. On browser mode I have for markers the correct icon that I indicate in BaseArrayClass, but on emulator I have default icon. Have you an idea about that ?

答:
Try to find some icon with https protocol.

Google may not allow insecure URLs.

Body:
I have this code :

this.service.getListe(data).forEach((data: any) => {
    const marker: Marker = this.map.addMarkerSync(data);
    marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe((params) => {
        this.click(params);
    });
});

Now the getListe() looks like :

getListe(merchants: any) {
    const Liste: BaseArrayClass<any> = new BaseArrayClass<any>();
    merchants.map(item => {
        Liste.push({
            title: item.name,
            animation: 'DROP',
            position: {
                lat: item.lat,
                lng: item.long
            },
            icon: 'http://icons.iconarchive.com/icons/iconarchive/red-orb-alphabet/24/Number-1-icon.png',
            disableAutoPan: true
        });
    });

    return Markers;
}

I tried and like this :

icon: {
    url: 'http://icons.iconarchive.com/icons/iconarchive/red-orb-alphabet/24/Number-1-icon.png'
}

But the same behaviour, the problem is that on emulator and on real device the icon is not changing. On browser mode I have for markers the correct icon that I indicate in BaseArrayClass, but on emulator I have default icon. Have you an idea about that ?


问:
get table name from query using a regex
I'm looking into finding a Pattern in order to get the table name for this type of SQL query;

```<code>INSERT INTO table(uuid,type) VALUES (?,?)
</code>```

Here I want to get "table"

I have a pattern but it's working only if there is no brackets like
    INSERT INTO table VALUES (?,?)

[from|into|update]\s+(?:\w+.)(\w+)(\s$|\s+(WHERE))

Thanks

NB : it's not the same pattern than in get table name from query

答:
For me, the table name between quotes (?is)\b(?:from|into|update)\s+(\w+) didn't work, I changed to work for all queries where between quotes like `table_name` or 'table_name' or "table_name"

```<code>(?is)\b(?:from|into|update)\s+[|'|"]([^|'|"]+)[`|'|"]
</code>```

Title: get table name from query using a regex

Body:
I'm looking into finding a Pattern in order to get the table name for this type of SQL query;

INSERT INTO table(uuid,type) VALUES (?,?)

Here I want to get "table"

I have a pattern but it's working only if there is no brackets like
    INSERT INTO table VALUES (?,?)

[from|into|update]\s+(?:\w+.)(\w+)(\s$|\s+(WHERE))

Thanks

NB : it's not the same pattern than in get table name from query

Body:
For me, the table name between quotes (?is)\b(?:from|into|update)\s+(\w+) didn't work, I changed to work for all queries where between quotes like `table_name` or 'table_name' or "table_name"

(?is)\b(?:from|into|update)\s+[|'|"]([^|'|"]+)[`|'|"]


问:
XDocument adds carriage (\r\n, ecaspe characters) return when generating final xml string
I need to return IHttpActionResult, Ok(xml).

Variable xml is a string data type. The problem is next...

When the program returns string xml, it adds \r\n for a NewLine, string escape characters ().

I want to return a clean xml string.

For example, this string i want to return:

```<code><?xml version="1.0" encoding="utf-8" standalone="yes"?>
 <ProxyGlave>
    <Glava ID="530064">
       <DatumIsporuke>1900-01-01T00:00:00</DatumIsporuke>
    </Glava>
    <Glava ID="530065">
       <DatumIsporuke>1900-01-01T00:00:00</DatumIsporuke>
    </Glava>
 </ProxyGlave>
</code>```

But my program returns this:

```<code>     "
     <?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n
     <ProxyGlave>\r\n
        <Glava ID=\"530064\">\r\n
           <DatumIsporuke>1900-01-01T00:00:00</DatumIsporuke>\r\n
        </Glava>\r\n
        <Glava ID=\"530065\">\r\n
           <DatumIsporuke>1900-01-01T00:00:00</DatumIsporuke>\r\n
        </Glava>\r\n
     </ProxyGlave>"
</code>```

Screenshot from Postman tool:

Code which generates string XML:

```<code>XDocument xdoc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
        new XElement("ProxyGlave",
        from gl in glave
        select
            new XElement("Glava", new XAttribute("ID", gl.DokumentiGlaId),
            new XElement("DatumIsporuke", gl.datum_isporuke)))
);
return Ok(xdoc.ToString());

</code>```

答:
In a Header of the GET request, you need to add Accept key which has value application/xml.
With that information in a header, the app knows what type of value it needs to return.

Body:
I need to return IHttpActionResult, Ok(xml).

Variable xml is a string data type. The problem is next...

When the program returns string xml, it adds \r\n for a NewLine, string escape characters ().

I want to return a clean xml string.

For example, this string i want to return:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
 <ProxyGlave>
    <Glava ID="530064">
       <DatumIsporuke>1900-01-01T00:00:00</DatumIsporuke>
    </Glava>
    <Glava ID="530065">
       <DatumIsporuke>1900-01-01T00:00:00</DatumIsporuke>
    </Glava>
 </ProxyGlave>

But my program returns this:

     "
     <?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n
     <ProxyGlave>\r\n
        <Glava ID=\"530064\">\r\n
           <DatumIsporuke>1900-01-01T00:00:00</DatumIsporuke>\r\n
        </Glava>\r\n
        <Glava ID=\"530065\">\r\n
           <DatumIsporuke>1900-01-01T00:00:00</DatumIsporuke>\r\n
        </Glava>\r\n
     </ProxyGlave>"

Screenshot from Postman tool:

Code which generates string XML:

XDocument xdoc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
        new XElement("ProxyGlave",
        from gl in glave
        select
            new XElement("Glava", new XAttribute("ID", gl.DokumentiGlaId),
            new XElement("DatumIsporuke", gl.datum_isporuke)))
);
return Ok(xdoc.ToString());


问:
Is there any missing functions in this code to pop-up the materialize data?
The materialize pop-up does not appear.

$(document).ready(function() {
  $('#cdn_customer_id').on('click', function() {
    //alert("hi00");
    var countCust = '<?php count($customers) ?>';
    if (countCust < 1) {
      Materialize.toast('Add a Sales/Client Master', 3000, 'red rounded')
    }
  });
```

<pre class="lang-html prettyprint-override"><code><select class="js-example-basic-single" name="cust_id" id="cdn_customer_id">
  <option value="">SELECT CLIENT</option>
  <?php foreach ($customers as $cus) { ?>
    <option value="<?php echo $cus->cust_id; ?>" <?php if(!empty($inv)){if($inv[0]->cust_id!=0){ echo ($inv[0]->cust_id==$cus->cust_id)?'selected':''; }} ?> >
    <?php echo strtoupper($cus->cust_name); ?>
  </option>
  <?php } ?>
</select>
</code>```

答:
It looks like this is a materializecss specific question.

Your markup looks wrong for one. The docs use this structure:

```<code>M.toast({html:'Add a Sales/Client Master'})
</code>```

Codepen here.

So an object inside the toast. Not sure why you are passing other style data in.

Another way is to declare the html first, then pass it in. From the docs:

```<code> var toastHTML = '<span>I am toast content</span><button class="btn-flat toast-action">Undo</button>';
  M.toast({html: toastHTML});
</code>```

https://materializecss.com/toasts.html

Body:
The materialize pop-up does not appear.

$(document).ready(function() {
  $('#cdn_customer_id').on('click', function() {
    //alert("hi00");
    var countCust = '<?php count($customers) ?>';
    if (countCust < 1) {
      Materialize.toast('Add a Sales/Client Master', 3000, 'red rounded')
    }
  });

<select class="js-example-basic-single" name="cust_id" id="cdn_customer_id">
  <option value="">SELECT CLIENT</option>
  <?php foreach ($customers as $cus) { ?>
    <option value="<?php echo $cus->cust_id; ?>" <?php if(!empty($inv)){if($inv[0]->cust_id!=0){ echo ($inv[0]->cust_id==$cus->cust_id)?'selected':''; }} ?> >
    <?php echo strtoupper($cus->cust_name); ?>
  </option>
  <?php } ?>
</select>

Body:
It looks like this is a materializecss specific question.

Your markup looks wrong for one. The docs use this structure:

M.toast({html:'Add a Sales/Client Master'})

Codepen here.

So an object inside the toast. Not sure why you are passing other style data in.

Another way is to declare the html first, then pass it in. From the docs:

 var toastHTML = '<span>I am toast content</span><button class="btn-flat toast-action">Undo</button>';
  M.toast({html: toastHTML});

https://materializecss.com/toasts.html


问:
Is there any way to accept all the parameters as a single string?
For example,

Input:

```<code>echo( hello world
</code>```

Program:

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

int main(int n,char** args){
// Replace all the '\0' with ' '
system(args[1]);
return printf("\n");
}
</code>```

Output:

```<code>hello world

</code>```

Now I need hello world in a pointer.

I know that **char doesn't work the way I want it to..

But is there any efficient way out, instead of calculating the length of each argument, malloc-ing those many bytes and then concatenating it to the allocated memory?

Some access specifier for char** maybe?

I am trying to add echo( a command to DOSBox, so basically echo params and then print a newline. That's it.

Also, is there any way to exclude to recognize an exe without any spaces or is it console specific?

答:
Make it one line.

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

int main(int argc, char **argv)
{
    char oneline[256] = "";
    for(int index = 1; index < argc; index++)
    {
        strcat(oneline, argv[index]);
        strcat(oneline, " ");
    }

    printf("parameters: "%s"\n", oneline);
}
</code>```

https://godbolt.org/z/B4ULLB

This is only the idea and it can be done much more efficiently - for example by not using strcat or more efficiently allocate the memory. But the idea will be the same. You can also do not add the last space (it is for nitpickers)

Body:
For example,

Input:

echo( hello world

Program:

#include<stdio.h>

int main(int n,char** args){
// Replace all the '\0' with ' '
system(args[1]);
return printf("\n");
}

Output:

hello world

Now I need hello world in a pointer.

I know that **char doesn't work the way I want it to..

But is there any efficient way out, instead of calculating the length of each argument, malloc-ing those many bytes and then concatenating it to the allocated memory?

Some access specifier for char** maybe?

I am trying to add echo( a command to DOSBox, so basically echo params and then print a newline. That's it.

Also, is there any way to exclude to recognize an exe without any spaces or is it console specific?

Body:
Make it one line.

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    char oneline[256] = "";
    for(int index = 1; index < argc; index++)
    {
        strcat(oneline, argv[index]);
        strcat(oneline, " ");
    }

    printf("parameters: "%s"\n", oneline);
}

https://godbolt.org/z/B4ULLB

This is only the idea and it can be done much more efficiently - for example by not using strcat or more efficiently allocate the memory. But the idea will be the same. You can also do not add the last space (it is for nitpickers)


问:
JavaScript: How do you use Array.prototype.filter() on arrays that contain objects
I was arranging a file tree and I only wanted to show file/folder name that don't have "." at the start of their names. But I always get the same array after I filter it. What do I do?

So here what have I tried:

```<code>const arr = [
  {
    name: ".hidden",
    size: "14"
  },
  {
    name: "View",
    size: "12"
  },
  {
    name: ".secret",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
];
arr.filter(obj => {
  // charCode of "." is 46
  if(obj.name.charCodeOf(0) !== 46) {
    return true
  }
  else {
    return false
  }
});
console.log(arr);
</code>```

Expexted Console:

```<code>[
  {
    name: "View",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
]
</code>```

Reality:

```<code>[
  {
    name: ".hidden",
    size: "14"
  },
  {
    name: "View",
    size: "12"
  },
  {
    name: ".secret",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
]
</code>```

答:
Couple issues:

You should use indexOf to check for the dot in the first position of the string. (Better browser support: https://caniuse.com/#search=indexOf)

The array filter returns a new array with your filtered results.

const arr = [
  {
    name: ".hidden",
    size: "14"
  },
  {
    name: "View",
    size: "12"
  },
  {
    name: ".secret",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
];
const newArray = arr.filter(obj => obj.name.indexOf(".") === 0);
console.log(newArray);```

Body:
I was arranging a file tree and I only wanted to show file/folder name that don't have "." at the start of their names. But I always get the same array after I filter it. What do I do?

So here what have I tried:

const arr = [
  {
    name: ".hidden",
    size: "14"
  },
  {
    name: "View",
    size: "12"
  },
  {
    name: ".secret",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
];
arr.filter(obj => {
  // charCode of "." is 46
  if(obj.name.charCodeOf(0) !== 46) {
    return true
  }
  else {
    return false
  }
});
console.log(arr);

Expexted Console:

[
  {
    name: "View",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
]

Reality:

[
  {
    name: ".hidden",
    size: "14"
  },
  {
    name: "View",
    size: "12"
  },
  {
    name: ".secret",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
]


问:
Algorithm to cluster 2D points into bounding-box decomposition

I'm looking for an algorithm that takes the unstructured 2D point set as illustrated above and gives me a decomposition into bounding boxes as shown below. The bounding boxes may overlap, but the algorithm should nevertheless try to find a tight fit (it does not need to be the best one possible, but a good one).

I already tried to work with K-Means but that doesn't give me useful results as I'd need to know already how many clusters I need.

答:
There are several approaches to achieve this. The one I'd use is to apply the RANSAC algorithm in order to sequentially fit Oriented Bounding Boxes (OBB) to the data. By adopting this approach you can even improve the sample selection by computing a constrained Delaunay triangulation on your data, thus discarding bigger edges when fitting the OBB.

Alternatively, you can apply the Alpha-shape algorithm on the entire set of points and start decomposing in smaller shapes, but this requires the definition of an optimal alpha value which is not trivial.


问:
C# lambda expression unable to manage a certain string compare
I have a specific lambda what doesn't seem to want to work properly although the logic seems sound.

```<code>index = llCodeList.FindIndex(f => string.Compare(f.Threshold.ToString(), searchText, true ) >= 0);
</code>```

f.Threshold is an integer value, it seems that the conversion doesn't happen and it breaks my search function.  Can anyone shed some light on this?

答:
Why not ditch the string compare and explicitly check?

```<code>index = llCodeList.FindIndex(
            f => f.Threshold.ToString()
                            .Contains(searchText));
</code>```

Are you sure that the search text is a subset of the threshold number?

Also it may be that you're not understanding how string.Compare works, it won't check numerical value but string value. For the above if searchText is 4 and the threshold is -40 would match your predicate. My example more explicitly demonstrates the behavior of string.Compare(...,...,...) >= 0

If you're trying to find results based on having a greater than or equal to match on threshold and searchText you could do this

```<code>int search = 0;
int32.TryParse(searchText, out search);
index = llCodeList.FindIndex(f => f.Threshold >= search);
</code>```

Body:
I have a specific lambda what doesn't seem to want to work properly although the logic seems sound.

index = llCodeList.FindIndex(f => string.Compare(f.Threshold.ToString(), searchText, true ) >= 0);

f.Threshold is an integer value, it seems that the conversion doesn't happen and it breaks my search function.  Can anyone shed some light on this?

Body:
Why not ditch the string compare and explicitly check?

index = llCodeList.FindIndex(
            f => f.Threshold.ToString()
                            .Contains(searchText));

Are you sure that the search text is a subset of the threshold number?

Also it may be that you're not understanding how string.Compare works, it won't check numerical value but string value. For the above if searchText is 4 and the threshold is -40 would match your predicate. My example more explicitly demonstrates the behavior of string.Compare(...,...,...) >= 0

If you're trying to find results based on having a greater than or equal to match on threshold and searchText you could do this

int search = 0;
int32.TryParse(searchText, out search);
index = llCodeList.FindIndex(f => f.Threshold >= search);


问:
COUNTIFS for Last 10 Matching Entries
Spreadsheet

Tab Ladder - Col J has a COUNTIFS formula that calculates % of matching criteria within the last 24hrs.  I would like to limit the calculation to the last 10 matching entries within the 24hr window.

I have a stub formula in J35 outlining how I would like it structured.  I have done a lot of searching, and while I have found a few examples of "Last x rows" - I haven't been able to translate those concepts to my specific needs.

Thank you in advance for your help!

答:
I have also discovered that the following nested QUERY would work - though I would have to restructure the sheet a little bit so that the formula was outside of the bounds of the QUERY so not to trigger a circular dependency.

=QUERY(QUERY($A$18:$Y, "Select T Where H = '"&$H35&"' and D = '"&$D35&"' and E = '"&$E35&"' Order by C desc limit 10", 0), "select avg(Col1) label avg(Col1)''", 0)

Title: COUNTIFS for Last 10 Matching Entries


问:
Cannot examine breakpoints in PhpStorm with Xdebug
I have a simple Apache + PHP 7.1 web server running locally.

I've got Xdebug helper installed in Chrome, and I click "Debug" in that.

I've got Xdebug 2.9.2 extension running successfully in PHP, with correct output from phpinfo();

When I run "validate" in PhpStorm I get green ticks for all but the last item, "Debug protocol '' is not supported", which has a yellow triangle.

I set a debug point in my code, and hit the green bug in the toolbar to begin a debugging session, and the only thing that's output in the Debugger "Variables" pane in PhpStorm is "Waiting for incoming connection with ide key '13508'" (this number changes every time).

Within php.ini I have set xdebug.idekey="PHPSTORM", and I've mirrored this in my Chrome Xdebug Helper.

I am not running Zend Debug.

I would really like to be able to debug properly. Any help is greatly appreciated.

答:
Accordingly to your Xdebug log, you already have some service running on TCP 9000 port and that does not seem to be PhpStorm. Most likely it's php-fpm (it also uses the same port by default).

You can check that with netstat or alike (e.g. sudo lsof -nP -iTCP -sTCP:LISTEN if you are on Mac) -- it can show associated process ID (or even process name straight away).

Solution: change Xdebug port in both php.ini and PhpStorm to be some another number -- e.g. 9001 or so; restart web server once done.


问:
Extracting value from an object
I'm working on a discord bot, using discord.js.

I've been working on this command for too long without finding a solution, so I come here to ask for help.
Here is my problem, maybe it's really simple to solve to you, and that would be great :D
I want to create a command that sends a random gif, based on a keyword.
I'm using a node module called giphy-random.

```<code>        (async () => {
            const API_KEY = "hidden";

            const gif = await giphyRandom(API_KEY, {
                tag: "kawaii"
            });
            console.log(gif)
          }
</code>```

I would like to be able to get only the value 'url' of the const which is defined by the function (i'm maybe wrong in my words, I'm a beginner) in order to send it in a channel.

答:
You simply want gif.data.url In fact if you change your console.log like this:

```<code>console.log(gif.data.url);
</code>```

You'll see the url printed to the console.

Title: Extracting value from an object

Body:
I'm working on a discord bot, using discord.js.

I've been working on this command for too long without finding a solution, so I come here to ask for help.
Here is my problem, maybe it's really simple to solve to you, and that would be great :D
I want to create a command that sends a random gif, based on a keyword.
I'm using a node module called giphy-random.

        (async () => {
            const API_KEY = "hidden";

            const gif = await giphyRandom(API_KEY, {
                tag: "kawaii"
            });
            console.log(gif)
          }

I would like to be able to get only the value 'url' of the const which is defined by the function (i'm maybe wrong in my words, I'm a beginner) in order to send it in a channel.

Body:
You simply want gif.data.url In fact if you change your console.log like this:

console.log(gif.data.url);

You'll see the url printed to the console.


答:
According to the docs, the link is returned in data.url property of the resulting object. So your code should look like:

```<code>      (async () => {
        const API_KEY = "hidden";

        const gif = await giphyRandom(API_KEY, {
            tag: "kawaii"
        });
        console.log(gif.data.url)
      }
</code>```

Title: Extracting value from an object

Body:
According to the docs, the link is returned in data.url property of the resulting object. So your code should look like:

      (async () => {
        const API_KEY = "hidden";

        const gif = await giphyRandom(API_KEY, {
            tag: "kawaii"
        });
        console.log(gif.data.url)
      }


问:
how do I find differences between similar strings?
I have a vector of strings (file names to be exact).

```<code>pav <- c("Sn_4Khz_3W_45_130_02_30cm_101mm_",
         "Sn_4Khz_4W_45_130_02_30cm_101mm_",
         "Sn_4Khz_4W_50_130_02_30cm_101mm_")
</code>```

I'm looking for a simple way to find difference between these strings.

```<code>`> char_position_fun(pav) # gives unique character position
[1] 9 12 13 `

`> char_diff_fun(pav) # removes matching components (position and value)
[1] 3_4_5  4_4_5  4_5_0`
</code>```

答:
Here is a base R solution.

At first, we can invert strings from UTF8 to Int, i.e.,

```<code>z <- Map(utf8ToInt,v)
</code>```

the positions of differences

```<code>pos <- unique(unlist(outer(z,z,FUN = Vectorize(function(x,y) which(x!=y)))))

> pos
[1]  9 12 13
</code>```

the chars that are different:

```<code>word <- Map(function(x) paste(intToUtf8(x[p],multiple = T),collapse = "_"),z)

> word
$Sn_4Khz_3W_45_130_02_30cm_101mm_
[1] "3_4_5"

$Sn_4Khz_4W_45_130_02_30cm_101mm_
[1] "4_4_5"

$Sn_4Khz_4W_50_130_02_30cm_101mm_
[1] "4_5_0"
</code>```

DATA

```<code>v <- c("Sn_4Khz_3W_45_130_02_30cm_101mm_", "Sn_4Khz_4W_45_130_02_30cm_101mm_",
            "Sn_4Khz_4W_50_130_02_30cm_101mm_")
</code>```

Body:
I have a vector of strings (file names to be exact).

pav <- c("Sn_4Khz_3W_45_130_02_30cm_101mm_",
         "Sn_4Khz_4W_45_130_02_30cm_101mm_",
         "Sn_4Khz_4W_50_130_02_30cm_101mm_")

I'm looking for a simple way to find difference between these strings.

`> char_position_fun(pav) # gives unique character position
[1] 9 12 13 `

`> char_diff_fun(pav) # removes matching components (position and value)
[1] 3_4_5  4_4_5  4_5_0`

Body:
Here is a base R solution.

At first, we can invert strings from UTF8 to Int, i.e.,

z <- Map(utf8ToInt,v)

the positions of differences

pos <- unique(unlist(outer(z,z,FUN = Vectorize(function(x,y) which(x!=y)))))

> pos
[1]  9 12 13

the chars that are different:

word <- Map(function(x) paste(intToUtf8(x[p],multiple = T),collapse = "_"),z)

> word
$Sn_4Khz_3W_45_130_02_30cm_101mm_
[1] "3_4_5"

$Sn_4Khz_4W_45_130_02_30cm_101mm_
[1] "4_4_5"

$Sn_4Khz_4W_50_130_02_30cm_101mm_
[1] "4_5_0"

DATA

v <- c("Sn_4Khz_3W_45_130_02_30cm_101mm_", "Sn_4Khz_4W_45_130_02_30cm_101mm_",
            "Sn_4Khz_4W_50_130_02_30cm_101mm_")


问:
How do I sort an NSMutableArray with custom objects in it?
What I want to do seems pretty simple, but I can't find any answers on the web. I have an NSMutableArray of objects, and let's say they are 'Person' objects. I want to sort the NSMutableArray by Person.birthDate which is an NSDate.

I think it has something to do with this method:

```<code>NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(???)];
</code>```

In Java I would make my object implement Comparable, or use Collections.sort with an inline custom comparator...how on earth do you do this in Objective-C?

答:
Swift version: 5.1

If you have a custom struct or class and want to sort them arbitrarily, you should call sort() using a trailing closure that sorts on a field you specify. Here's an example using an array of custom structs that sorts on a particular property:

```<code>    struct User {
        var firstName: String
    }

    var users = [
        User(firstName: "Jemima"),
        User(firstName: "Peter"),
        User(firstName: "David"),
        User(firstName: "Kelly"),
        User(firstName: "Isabella")
    ]

    users.sort {
        $0.firstName < $1.firstName
    }
</code>```

If you want to return a sorted array rather than sort it in place, use sorted() like this:

```<code>    let sortedUsers = users.sorted {
        $0.firstName < $1.firstName
    }
</code>```

Body:
What I want to do seems pretty simple, but I can't find any answers on the web. I have an NSMutableArray of objects, and let's say they are 'Person' objects. I want to sort the NSMutableArray by Person.birthDate which is an NSDate.

I think it has something to do with this method:

NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(???)];

In Java I would make my object implement Comparable, or use Collections.sort with an inline custom comparator...how on earth do you do this in Objective-C?

Body:
Swift version: 5.1

If you have a custom struct or class and want to sort them arbitrarily, you should call sort() using a trailing closure that sorts on a field you specify. Here's an example using an array of custom structs that sorts on a particular property:

    struct User {
        var firstName: String
    }

    var users = [
        User(firstName: "Jemima"),
        User(firstName: "Peter"),
        User(firstName: "David"),
        User(firstName: "Kelly"),
        User(firstName: "Isabella")
    ]

    users.sort {
        $0.firstName < $1.firstName
    }

If you want to return a sorted array rather than sort it in place, use sorted() like this:

    let sortedUsers = users.sorted {
        $0.firstName < $1.firstName
    }


问:
How do I get two dockerized applications to talk on a given port?
I'm trying to get two dockerized applications to speak to eachother on a given port according to my docker-compose.yml file.

They are able to speak to eachother on port app1:61001 and app2:61002, but my friend tells me that they should be able to communicate on port 80. example.. app2:80, and that port 61001 and 61002 should only be the accessible ports exposed out of the swarm.

The applications themselves are set to server.port=80

Any idea how I can get it working as my friend suggests?

Here is the docker-compose file I'm using:

docker compose

```<code>version: "3.5"

services:
  app1:
    image: docker.artifactory.gr.gr.com/app1:latest
    ports:
      - "61001:80"
    deploy:
      replicas: 2
    networks:
      - custom-network

  app2:
    image: docker.artifactory.gr.gr.com/app2:latest
    ports:
      - "61002:80"
    deploy:
      replicas: 2
    networks:
      - custom-network

networks:
  custom-network:
</code>```

My

答:
App1 and App2 are part of the same network that you named custom-network.
This means that the internal port used by the containers ( the one on the right, 80 ) is  visible from both applications!
If you have to call a service from APP 1 to APP 2 you simply have to name the container with

```<code>hostname: app2 // do the same for the other container
container_name: app2
</code>```

Then, from app1, you can call the application simply using "app1:80/yourpath".
The port exposed are visible OUTSIDE the network.

In addition:
You can check the connectivity, connecting into app1 application with an iterative shell:https://gist.github.com/mitchwongho/11266726 and then executing

```<code>ping app1
</code>```

you will see that app1 has an internal IP and that is reachable.

Body:
I'm trying to get two dockerized applications to speak to eachother on a given port according to my docker-compose.yml file.

They are able to speak to eachother on port app1:61001 and app2:61002, but my friend tells me that they should be able to communicate on port 80. example.. app2:80, and that port 61001 and 61002 should only be the accessible ports exposed out of the swarm.

The applications themselves are set to server.port=80

Any idea how I can get it working as my friend suggests?

Here is the docker-compose file I'm using:

docker compose

version: "3.5"

services:
  app1:
    image: docker.artifactory.gr.gr.com/app1:latest
    ports:
      - "61001:80"
    deploy:
      replicas: 2
    networks:
      - custom-network

  app2:
    image: docker.artifactory.gr.gr.com/app2:latest
    ports:
      - "61002:80"
    deploy:
      replicas: 2
    networks:
      - custom-network

networks:
  custom-network:

My

Body:
App1 and App2 are part of the same network that you named custom-network.
This means that the internal port used by the containers ( the one on the right, 80 ) is  visible from both applications!
If you have to call a service from APP 1 to APP 2 you simply have to name the container with

hostname: app2 // do the same for the other container
container_name: app2

Then, from app1, you can call the application simply using "app1:80/yourpath".
The port exposed are visible OUTSIDE the network.

In addition:
You can check the connectivity, connecting into app1 application with an iterative shell:https://gist.github.com/mitchwongho/11266726 and then executing

ping app1

you will see that app1 has an internal IP and that is reachable.


答:
In the simplest way</p>

```<code>const result = arr.filter(obj => !obj.name.startsWith('.'));

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

Body:
In the simplest way

const result = arr.filter(obj => !obj.name.startsWith('.'));

console.log(result);