问:
Responsive html: place side column between elements in main column when wrapped
I have simple columns layout:

On smaller screen I want Component 2 to be the last component, placed after Component 3:

Is it possible to modify following html to meet the resposive layout criteria?

```<code><div class="row">
  <div class="col-lg-8">
    <div id="component1"></div>
    <div id="component2"></div>
  </div>
  <div class="col-lg-4">
      <div id="component3"></div>
  </div>
</div>
</code>```

答:
You will be able to use the flexbox order property in order to change the ordering of elements. As you are using Bootstrap 4, you can read Bootstraps documentation on order classes.

As shown in Bootstrap example, it can work like this:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

First flex item

Second flex item

Third flex item

```
</div>
</div>
</p>

<p>Bootstrap also has responsive variations also exist for order. For example, the class names would look like this:</p>

<pre class="lang-html prettyprint-override"><code>.order-sm-0
.order-md-4
.order-lg-2
</code>```

Body:
You will be able to use the flexbox order property in order to change the ordering of elements. As you are using Bootstrap 4, you can read Bootstraps documentation on order classes.

As shown in Bootstrap example, it can work like this:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div class="d-flex flex-nowrap bd-highlight">
  <div class="order-3 p-2 bd-highlight">First flex item</div>
  <div class="order-2 p-2 bd-highlight">Second flex item</div>
  <div class="order-1 p-2 bd-highlight">Third flex item</div>
</div>

Bootstrap also has responsive variations also exist for order. For example, the class names would look like this:

.order-sm-0
.order-md-4
.order-lg-2


来源: stackexchange

问:
Is there an easier way to do this in python?
I want to try to find an easier way to do this and I haven't found any way to do it.

This is meant to be a menu that can be written in. I am trying to add personalized messages to the text to further make it human-like, however it seems very long and longer than it should be. sandwich_t is a question asking the user if they want a sandwich, beverage is asking the user if they want a beverage, etc.

if sandwich_t=="Yes" and beverage== "Yes" and fries== "Yes" and Ketchup== "Yes":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, and a ", beverage_selection, "drink, with ", fries_selection, "fries, with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "Yes" and fries== "Yes" and Ketchup== "No":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, and a ", beverage_selection, "drink, with ", fries_selection, "fries, with no ketchup"
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "Yes" and fries== "No" and Ketchup== "Yes":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, and a ", beverage_selection, "drink, with no fries, and ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "No" and fries== "Yes" and Ketchup== "Yes":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, with no drink, with ", fries_selection, "fries, with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "Yes" and fries== "No" and Ketchup== "No":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, and a ", beverage_selection, "drink, with no fries, with no ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "No" and fries== "No" and Ketchup== "No":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, with no drink, with no fries, with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "No" and fries== "Yes" and Ketchup== "No":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, with no drink, with ", fries_selection, "fries, with no ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "No" and fries== "No" and Ketchup== "Yes":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, with no drink, with no fries, with", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "Yes" and fries== "Yes" and Ketchup== "Yes":
    print "Cashier: In total so far you have no sandwich with a", beverage_selection, "drink with ", fries_selection, "fries and ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "Yes" and fries== "Yes" and Ketchup== "No":
    print "Cashier: In total so far you have no sandwich with a", beverage_selection, "drink with ", fries_selection, "fries with no ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "Yes" and fries== "No" and Ketchup== "Yes":
    print "Cashier: In total so far you have no sandwich with a", beverage_selection, "drink no fries and ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "Yes" and fries== "No" and Ketchup== "No":
    print "Cashier: In total so far you have no sandwich with a", beverage_selection, "drink, no fries with no ketchup."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "No" and fries== "Yes" and Ketchup== "Yes":
    print "Cashier: In total so far you have no sandwich with no drink, ", fries_selection, "fries with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "No" and fries== "Yes" and Ketchup== "No":
    print "Cashier: In total so far you have no sandwich with no drink, ", fries_selection, "fries with no ketchup."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "No" and fries== "No" and Ketchup== "Yes":
    print "Cashier: In total so far you have no sandwich, no drink, no fries, with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "No" and fries== "No" and Ketchup== "No":
    print "Chasier: You ordered nothing. Why did you come here?"
```

答:
Loops, have you heard of them? Also, non-empty things evaluate to true.

Assuming ketchup, and fries are just booleans (not strings with "Yes" or "No") and sandwich is either None or a string with name (no "string_t"), similarly beverage:

```<code>cashier_text = "Cashier: In total you have so far ordered "
total = 0
if sandwich: # evaluates to true if string, skips if
    cashier_text += sandwich
    cashier_text += " sandwich, and "
    total += #cost here, you don't have this in your code?
if beverage: # same as sandwich
    cashier_text += beverage
    total += #cost here, omitted in your code
if fries: # boolean
    cashier_text += " with fries"
    total += #cost here
if ketchup: #boolean
    cashier_text += " with additional ketchup"
#print cashier text here
#total and customer was always common so they should've been always here, not in if's
</code>```

This is more of a pythonic pseudocode than working example - it should work but it will be ugly, I wrote it directly in answer editor.

Add else wherever you want, make the sentence so it makes sense if something is not there (as I said, I didn't care about it - e.g. if you order a sandwich only with my code it will be "[name] sandwitch, and").

ContentLicense: CC BY-SA 4.0

Body:
Loops, have you heard of them? Also, non-empty things evaluate to true.

Assuming ketchup, and fries are just booleans (not strings with "Yes" or "No") and sandwich is either None or a string with name (no "string_t"), similarly beverage:

cashier_text = "Cashier: In total you have so far ordered "
total = 0
if sandwich: # evaluates to true if string, skips if
    cashier_text += sandwich
    cashier_text += " sandwich, and "
    total += #cost here, you don't have this in your code?
if beverage: # same as sandwich
    cashier_text += beverage
    total += #cost here, omitted in your code
if fries: # boolean
    cashier_text += " with fries"
    total += #cost here
if ketchup: #boolean
    cashier_text += " with additional ketchup"
#print cashier text here
#total and customer was always common so they should've been always here, not in if's

This is more of a pythonic pseudocode than working example - it should work but it will be ugly, I wrote it directly in answer editor.

Add else wherever you want, make the sentence so it makes sense if something is not there (as I said, I didn't care about it - e.g. if you order a sandwich only with my code it will be "[name] sandwitch, and").


问:
How to write/append the json object from a POST request to a JSON file?
I want to add a JSON element to a JSON file using the data given by a POST request. This already kind of works, I just can't figure out how to add the id to the data, how do I do that?

I tried a lot, I have created a completely new JSON object and tried to add it to my file which didn't work and I tried adding data to the data given from the POST request like this: body += { "id": 10 }; which produces an undefined error.

Here is how I handle the POST request:

```<code>} else if (req.method === 'POST' && pathname === 'Kunden') {

        res.writeHead(200, {
            'Content-Type' : 'application/json'
        });

        var body = '';
        req.on('data', function(data) {
            body += data;
        });

        req.on('end', function() {

            fs.readFile('Kunden.json', function(err, kundenJSON) {
                if (err) {
                    console.log(err);
                }

                var kunden = JSON.parse([kundenJSON]);
                kunden.kunde.push(JSON.parse(body));
                kundenJSON = JSON.stringify(kunden);

                fs.writeFile('Kunden.json', kundenJSON, function(err) {
                    if(err) {console.log(err);
                    }});
            });

            });
    }

}).listen(8081);
</code>```

and here is my already existing JSON file:

```<code>{"kunde":[{"id":1,"name":"Customer1"},{"id":2,"name":"Customer2"},{"id":3,"name":"Customer3"}]}
</code>```

Basically I get the "name" from the POST req and I have to add the following id (in the first request this would be 4, then 5 and so on) to it and then append it to my file.

In the end my file should look like this:

```<code>{"kunde":[{"id":1,"name":"Customer1"},{"id":2,"name":"Customer2"},{"id":3,"name":"Customer3"},{"id":4,"name":PostData"}]}
</code>```

But I can only manage this right now:

```<code>{"kunde":[{"id":1,"name":"Customer1"},{"id":2,"name":"Customer2"},{"id":3,"name":"Customer3"},{"name":PostData"}]}
</code>```

答:
If I understand you correctly, you want to add and id to the new object when you save it to the file. This is basically easy, but you should also know how to keep track of the ids properly.

```<code>var kunden = JSON.parse([kundenJSON]);
var newKunde = JSON.parse(body);
newKunde.id = 4;
kunden.kunde.push(newKunde);
kundenJSON = JSON.stringify(kunden);
</code>```

The problems I'm talking about is, how to you get to know the new id? You could just say newId = kunden.kunde.length + 1 - but if you delete one later on, you will have duplicate ids. You also need to think about how to handle unique ids for the future.

Body:
I want to add a JSON element to a JSON file using the data given by a POST request. This already kind of works, I just can't figure out how to add the id to the data, how do I do that?

I tried a lot, I have created a completely new JSON object and tried to add it to my file which didn't work and I tried adding data to the data given from the POST request like this: body += { "id": 10 }; which produces an undefined error.

Here is how I handle the POST request:

} else if (req.method === 'POST' && pathname === 'Kunden') {

        res.writeHead(200, {
            'Content-Type' : 'application/json'
        });

        var body = '';
        req.on('data', function(data) {
            body += data;
        });

        req.on('end', function() {

            fs.readFile('Kunden.json', function(err, kundenJSON) {
                if (err) {
                    console.log(err);
                }

                var kunden = JSON.parse([kundenJSON]);
                kunden.kunde.push(JSON.parse(body));
                kundenJSON = JSON.stringify(kunden);

                fs.writeFile('Kunden.json', kundenJSON, function(err) {
                    if(err) {console.log(err);
                    }});
            });

            });
    }

}).listen(8081);

and here is my already existing JSON file:

{"kunde":[{"id":1,"name":"Customer1"},{"id":2,"name":"Customer2"},{"id":3,"name":"Customer3"}]}

Basically I get the "name" from the POST req and I have to add the following id (in the first request this would be 4, then 5 and so on) to it and then append it to my file.

In the end my file should look like this:

{"kunde":[{"id":1,"name":"Customer1"},{"id":2,"name":"Customer2"},{"id":3,"name":"Customer3"},{"id":4,"name":PostData"}]}

But I can only manage this right now:

{"kunde":[{"id":1,"name":"Customer1"},{"id":2,"name":"Customer2"},{"id":3,"name":"Customer3"},{"name":PostData"}]}

Body:
If I understand you correctly, you want to add and id to the new object when you save it to the file. This is basically easy, but you should also know how to keep track of the ids properly.

var kunden = JSON.parse([kundenJSON]);
var newKunde = JSON.parse(body);
newKunde.id = 4;
kunden.kunde.push(newKunde);
kundenJSON = JSON.stringify(kunden);

The problems I'm talking about is, how to you get to know the new id? You could just say newId = kunden.kunde.length + 1 - but if you delete one later on, you will have duplicate ids. You also need to think about how to handle unique ids for the future.


问:
Explain some code about dynamic connection string
So, I'm doing a website that does a lot of things and one of them is, doing a dynamic connection string... I already did it, but because I took the code from the internet, I'm kinda lost, so I was hoping that somebody could help and explain how it works and what each thing does...

Here's the code:

```<code>protected void Page_Load(object sender, EventArgs e)
        {
            AddUpdateConnectionString("ConString");
        }

            void AddUpdateConnectionString(string name)
            {

                bool isNew = false;
                string path = Server.MapPath("~/Web.Config");
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNodeList list = doc.DocumentElement.SelectNodes(string.Format("connectionStrings/add[@name='{0}']", name));
                XmlNode node;
                isNew = list.Count == 0;
                if (isNew)
                {
                    node = doc.CreateNode(XmlNodeType.Element, "add", null);
                    XmlAttribute attribute = doc.CreateAttribute("name");
                    attribute.Value = name;
                    node.Attributes.Append(attribute);

                    attribute = doc.CreateAttribute("connectionString");
                    attribute.Value = "";
                    node.Attributes.Append(attribute);

                    attribute = doc.CreateAttribute("providerName");
                    attribute.Value = "System.Data.SqlClient";
                    node.Attributes.Append(attribute);
                }
                else
                {
                    node = list[0];
                }
                string conString = node.Attributes["connectionString"].Value;
                SqlConnectionStringBuilder conStringBuilder = new SqlConnectionStringBuilder(conString);
                conStringBuilder.InitialCatalog = TxtBaseDeDados.Text;
                conStringBuilder.DataSource = TxtHost.Text;
                conStringBuilder.IntegratedSecurity = false;
                conStringBuilder.UserID = TxtUtilizador.Text;
                conStringBuilder.Password = TxtPalavraPasse.Text;
                node.Attributes["connectionString"].Value = conStringBuilder.ConnectionString;
                if (isNew)
                {
                    doc.DocumentElement.SelectNodes("connectionStrings")[0].AppendChild(node);
                }

                doc.Save(path);

            }

        protected void Button1_Click(object sender, EventArgs e)
        {
            AddUpdateConnectionString("ConString");
        }
</code>```

答: It creates or updates the setting in your web.config file used to store the details of how to connect to your back-end database. Config files are XML documents (which are laid out in hierarchical format), so the code finds the config, finds the right section inside of the config (creating it if it's not there), constructs a new connection string, stores it in the XML and saves the changes.</p>

Body:
So, I'm doing a website that does a lot of things and one of them is, doing a dynamic connection string... I already did it, but because I took the code from the internet, I'm kinda lost, so I was hoping that somebody could help and explain how it works and what each thing does...

Here's the code:

protected void Page_Load(object sender, EventArgs e)
        {
            AddUpdateConnectionString("ConString");
        }

            void AddUpdateConnectionString(string name)
            {

                bool isNew = false;
                string path = Server.MapPath("~/Web.Config");
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNodeList list = doc.DocumentElement.SelectNodes(string.Format("connectionStrings/add[@name='{0}']", name));
                XmlNode node;
                isNew = list.Count == 0;
                if (isNew)
                {
                    node = doc.CreateNode(XmlNodeType.Element, "add", null);
                    XmlAttribute attribute = doc.CreateAttribute("name");
                    attribute.Value = name;
                    node.Attributes.Append(attribute);

                    attribute = doc.CreateAttribute("connectionString");
                    attribute.Value = "";
                    node.Attributes.Append(attribute);

                    attribute = doc.CreateAttribute("providerName");
                    attribute.Value = "System.Data.SqlClient";
                    node.Attributes.Append(attribute);
                }
                else
                {
                    node = list[0];
                }
                string conString = node.Attributes["connectionString"].Value;
                SqlConnectionStringBuilder conStringBuilder = new SqlConnectionStringBuilder(conString);
                conStringBuilder.InitialCatalog = TxtBaseDeDados.Text;
                conStringBuilder.DataSource = TxtHost.Text;
                conStringBuilder.IntegratedSecurity = false;
                conStringBuilder.UserID = TxtUtilizador.Text;
                conStringBuilder.Password = TxtPalavraPasse.Text;
                node.Attributes["connectionString"].Value = conStringBuilder.ConnectionString;
                if (isNew)
                {
                    doc.DocumentElement.SelectNodes("connectionStrings")[0].AppendChild(node);
                }

                doc.Save(path);

            }

        protected void Button1_Click(object sender, EventArgs e)
        {
            AddUpdateConnectionString("ConString");
        }


问:
How do I stop this loop after 5 seconds?
I made this box of code and the loop goes on forever, I want the loop to go for 5 seconds then stop completely. (also import time and random are put in above in the code)

I haven't tried much, quite lost on how to do this.

def case1():
    start = 1
    while True:
        int = randint(0,3)
        if int < 1:
            print('Blue')
            sleep(0.05)

        elif int < 2:
            print('Purple')
            sleep(0.05)

        elif int <= 3:
            print('Pink')
            sleep(0.05)
```

I need the loop to stop, after 5 seconds

答:
To stop the loop after 5 seconds you can use time() from time:

```<code>from time import time

def case1():
    start = time() + 5
    while time() < start:
        num = randint(0,3)
        if num < 1:
            print("Blue")
            sleep(0.05)
        elif num < 2:
            print("Purple")
            sleep(0.05)
        elif num <= 3:
            print("Pink")
            sleep(0.05)
</code>```

Body:
I made this box of code and the loop goes on forever, I want the loop to go for 5 seconds then stop completely. (also import time and random are put in above in the code)

I haven't tried much, quite lost on how to do this.

def case1():
    start = 1
    while True:
        int = randint(0,3)
        if int < 1:
            print('Blue')
            sleep(0.05)

        elif int < 2:
            print('Purple')
            sleep(0.05)

        elif int <= 3:
            print('Pink')
            sleep(0.05)

I need the loop to stop, after 5 seconds

Body:
To stop the loop after 5 seconds you can use time() from time:

from time import time

def case1():
    start = time() + 5
    while time() < start:
        num = randint(0,3)
        if num < 1:
            print("Blue")
            sleep(0.05)
        elif num < 2:
            print("Purple")
            sleep(0.05)
        elif num <= 3:
            print("Pink")
            sleep(0.05)


问:
Cannot convert value of type 'subSequence' (aka 'String.CharacterView') to type 'String' in collection
I build a webservis that requesting image url from the database. And I want to show it on the swift. But I'm gettig this error on the var photo line:

Cannot convert value of type 'subSequence' (aka 'String.CharacterView') to type 'String' in collection

```<code>let requestResponse = self.sendToServer(postUrl: "localhost",data:"abc")

let Seperated = requestResponse.characters.split(separator: " ")

var photo = Seperated[0] as String

let imageURL = URL(string: photo)
if let imageData = try? Data(contentsOf: imageURL!) {
    ...
}
</code>```

答:
The easiest solution.

let separated = requestResponse.characters.split(separator: " ").map { String($0) }
```

ContentLicense: CC BY-SA 3.0

Body:
I build a webservis that requesting image url from the database. And I want to show it on the swift. But I'm gettig this error on the var photo line:

Cannot convert value of type 'subSequence' (aka 'String.CharacterView') to type 'String' in collection

let requestResponse = self.sendToServer(postUrl: "localhost",data:"abc")

let Seperated = requestResponse.characters.split(separator: " ")

var photo = Seperated[0] as String

let imageURL = URL(string: photo)
if let imageData = try? Data(contentsOf: imageURL!) {
    ...
}


问:
Exclude a property from unobstrusive client Validation with MVC 3
I have a class User, that have an Email property, like that :

```<code>public class User : Entity
{
...
    [Display(Name = "Email"), Required(ErrorMessage = "Required."), Remote("EmailExists", "User", ErrorMessage = "Email already in Use.")]
    public virtual string Email { get; set; }
...
}
</code>```

My View Create works fine with all the validation ...
But in my view Edit, my Email texbox is Readonly, so The user cant change the email...

The problem is my Remote validation EmailExists keeps firing...

Is there a way to exclude the Email client validation just in that case? Or maybe another solution?

Thanks

答: You could use different ViewModels for the edit and create views and only apply the Remote attribute to view model associated with the create view or call some other remote validation logic for the view model associated with the edit view.</p>

Body:
I have a class User, that have an Email property, like that :

public class User : Entity
{
...
    [Display(Name = "Email"), Required(ErrorMessage = "Required."), Remote("EmailExists", "User", ErrorMessage = "Email already in Use.")]
    public virtual string Email { get; set; }
...
}

My View Create works fine with all the validation ...
But in my view Edit, my Email texbox is Readonly, so The user cant change the email...

The problem is my Remote validation EmailExists keeps firing...

Is there a way to exclude the Email client validation just in that case? Or maybe another solution?

Thanks


问:
Screen Editor Error after upgrade to 19.101 - Customization Project Must Be Published
I'm getting a "The customization project must be published before the screen can be edited" error when I try to open a screen in the Screen Editor.  I have 20 screen mods under the Screens node in the customization project.  Only about 6 of them are getting this error.  Some of the screens that are getting the error are completely custom and some are not.

I have upgraded from 18.209 to 19.101.  That is when this started happening.  I am able to open all screens with no problem in 18.209.

I have verified that the page files are in the CstPublished folder of the site.  I also checked the same folder in the validation folder.

The customization project is showing the "published" checkbox as checked.

Has anybody ran into this?  How can I debug?  It looks like there is something that 19.101 doesn't like about these pages.

TIA!

答: We've seen this error before and it turned out to be a dependency/setup issue with a feature that was turned off on the published target company (see Enable/Disable Features).  For example, if you are using a shell company to publish customization projects and your customization references a screen such as Sales Order Entry but the Inventory and Order Management feature is turned off or is not setup this could throw an error upon publish.  We've not necessarily experienced the same problem with previous versions.</p>


问:
What is the difference between |+ and |- when creating a configmap from a file in kubernetes yaml definitions?
i've came across 2 types of syntax for creating configmaps from files in kubernetes.

first one ;

```<code>apiVersion: v1
data:
  file1.yaml: |+
    parameter1=value1
kind: ConfigMap
metadata:
  name: my-configmap
</code>```

second one ;

```<code>apiVersion: v1
data:
  file1.yaml: | -
    parameter1=value1
kind: ConfigMap
metadata:
  name: my-configmap
</code>```

what is the difference between |+ and |- ?

答:
This is the block chomping indicator.

Directly  quoting from the link:

The chomping indicator controls what should happen with newlines at
  the end of the string. The default, clip, puts a single newline at the
  end of the string. To remove all newlines, strip them by putting a
  minus sign (-) after the style indicator. Both clip and strip ignore
  how many newlines are actually at the end of the block; to keep them
  all put a plus sign (+) after the style indicator.

This means that for:

```<code>apiVersion: v1
data:
  file1.yaml: |-
    parameter1=value1

kind: ConfigMap
metadata:
  name: my-configmap
</code>```

file1.yaml will have the value:

```<code>parameter1=value1
</code>```

For:

```<code>apiVersion: v1
data:
  file1.yaml: |+
    parameter1=value1

kind: ConfigMap
metadata:
  name: my-configmap
</code>```

file1.yaml will have the value:

```<code>parameter1=value1 # line break
# line break
# line break
</code>```

Body:
i've came across 2 types of syntax for creating configmaps from files in kubernetes.

first one ;

apiVersion: v1
data:
  file1.yaml: |+
    parameter1=value1
kind: ConfigMap
metadata:
  name: my-configmap

second one ;

apiVersion: v1
data:
  file1.yaml: | -
    parameter1=value1
kind: ConfigMap
metadata:
  name: my-configmap

what is the difference between |+ and |- ?

Body:
This is the block chomping indicator.

Directly  quoting from the link:

The chomping indicator controls what should happen with newlines at
  the end of the string. The default, clip, puts a single newline at the
  end of the string. To remove all newlines, strip them by putting a
  minus sign (-) after the style indicator. Both clip and strip ignore
  how many newlines are actually at the end of the block; to keep them
  all put a plus sign (+) after the style indicator.

This means that for:

apiVersion: v1
data:
  file1.yaml: |-
    parameter1=value1

kind: ConfigMap
metadata:
  name: my-configmap

file1.yaml will have the value:

parameter1=value1

For:

apiVersion: v1
data:
  file1.yaml: |+
    parameter1=value1

kind: ConfigMap
metadata:
  name: my-configmap

file1.yaml will have the value:

parameter1=value1 # line break
# line break
# line break


问:
Is there a way to disable a legend item by default?
Hi Highcharts community,

I'm curious to know if there is a way to disable a single legend item by default. For example, if there were 3 legend items- "Accepted" "Ideal" "Prediction", is it possible to have ONLY the "Prediction" legend item disabled after the chart loads without having to click on the legend item first? (Note: I don't want to eliminate the legend item altogether, I just want it to be greyed out initially, and still retain the functionality to enable the legend item again after clicking it).

Any help would be greatly appreciated.

Thanks!

答:
Below code works for me,(i am binding dynamic series)</p>

```<code> $(Chart.series).each(function (i, val) {
        if (val.name == "All Entity") {
             val.setVisible(true);
        }
   });
</code>```

Body:
Below code works for me,(i am binding dynamic series)

 $(Chart.series).each(function (i, val) {
        if (val.name == "All Entity") {
             val.setVisible(true);
        }
   });


问:
AngularJS application continuously redirects within BPM and thus crashing browser
I included a standalone AngularJS project in IBM BPM by keeping all the project assets (html, css & js files) in resources (teamworks.war) and keeping the index.html and AngularJS's main controller in customHTML in BPM's coach view.

Routing file for AngularJS (app.js):

```<code>angular.module('demoApp', ['ui.tree', 'ngRoute', 'ui.bootstrap'])
    .config(['$routeProvider', function($routeProvider) {
        $routeProvider
            .when("/tree", {
                controller: "treeCtrl",
                templateUrl: "template.html"
            })
            .otherwise({
                redirectTo: '/tree'
            });
    }]);
</code>```

BPM loads the AngularJS app again and again (using '/tree ' instead of '/tree' as the template name) as seen from elements in developer tools in ng-view and ultimately the browser gets crashed.

Although the same AngularJS app works perfectly fine on browser independently (without being included in BPM).

How can this behaviour be avoided in BPM?

答:
Sometimes third party libraries have limitations which you would not have locally.

When it is not possible to change the source code of that particular project, you might be better off by incurring a small stylistic penalty in your own code, so that you can integrate with the other software.

In this case, if you cannot change the configuration to omit the space, you could change your own template name to '/tree ', which will have an unnecessary space after your template name, but should be called on properly through BPM.

Body:
I included a standalone AngularJS project in IBM BPM by keeping all the project assets (html, css & js files) in resources (teamworks.war) and keeping the index.html and AngularJS's main controller in customHTML in BPM's coach view.

Routing file for AngularJS (app.js):

angular.module('demoApp', ['ui.tree', 'ngRoute', 'ui.bootstrap'])
    .config(['$routeProvider', function($routeProvider) {
        $routeProvider
            .when("/tree", {
                controller: "treeCtrl",
                templateUrl: "template.html"
            })
            .otherwise({
                redirectTo: '/tree'
            });
    }]);

BPM loads the AngularJS app again and again (using '/tree ' instead of '/tree' as the template name) as seen from elements in developer tools in ng-view and ultimately the browser gets crashed.

Although the same AngularJS app works perfectly fine on browser independently (without being included in BPM).

How can this behaviour be avoided in BPM?


问:
Prevent malicious input to execute when script called
I need to call a Unix script in my Java code, wait for it to execute, and get the output. The script will do a 'find', and user will  provide the directory he wants the 'find' to look in

```<code>String[] cmd = new String[] { "/bin/sh", "-c",
                              runnerScript.getAbsolutePath() + " " + Param1 };
Process p = Runtime.getRuntime().exec(cmd);
</code>```

Problem is : How can I prevent one to type ' && rm -rf *' or ' / -exec rm..' ?

I have an idea like check if the directory exist on the server, or use a method like isLetterOrDigit(), but I want to know if a safer way exists.
I know for Sql Query I can use PreparedStatement to work around this problem. Is there something similar when calling a script?

答:
Refer to ProcessBuilder for a similar purpose.

Refer to : How to sanitize user input used in Runtime.exec()?

```<code>ProcessBuilder pb = new ProcessBuilder("ls", "-l");
try {
    Process p = pb.start();
    System.out.println("Executed");
    while (p.isAlive())
    {}
    InputStream s = p.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(s));
    StringBuilder builder = new StringBuilder();
    String line = null;
    while ( (line = reader.readLine()) != null) {
       builder.append(line);
       builder.append(System.getProperty("line.separator"));
    }
    String result = builder.toString();
    System.out.println(result);
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

Body:
I need to call a Unix script in my Java code, wait for it to execute, and get the output. The script will do a 'find', and user will  provide the directory he wants the 'find' to look in

String[] cmd = new String[] { "/bin/sh", "-c",
                              runnerScript.getAbsolutePath() + " " + Param1 };
Process p = Runtime.getRuntime().exec(cmd);

Problem is : How can I prevent one to type ' && rm -rf *' or ' / -exec rm..' ?

I have an idea like check if the directory exist on the server, or use a method like isLetterOrDigit(), but I want to know if a safer way exists.
I know for Sql Query I can use PreparedStatement to work around this problem. Is there something similar when calling a script?

Body:
Refer to ProcessBuilder for a similar purpose.

Refer to : How to sanitize user input used in Runtime.exec()?

ProcessBuilder pb = new ProcessBuilder("ls", "-l");
try {
    Process p = pb.start();
    System.out.println("Executed");
    while (p.isAlive())
    {}
    InputStream s = p.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(s));
    StringBuilder builder = new StringBuilder();
    String line = null;
    while ( (line = reader.readLine()) != null) {
       builder.append(line);
       builder.append(System.getProperty("line.separator"));
    }
    String result = builder.toString();
    System.out.println(result);
} catch (IOException e) {
    e.printStackTrace();
}


问:
Why is the Java 11 runtime ignoring my jar containing sun.misc classes?
I am trying to upgrade my code base to Java 11. Unfortunately, my code has a dependency on a third-party library that internally uses sun.misc.BASE64Encoder and Decoder. Since the sun.misc package has been removed from the Java 11 JRE it is failing. The owner of that library has not replaced that dependency as yet, so I am stuck with it for a while.

If I had control of the code I would use java.util.BASE64 classes, but as I said these are coming in as a transitive dependency from another library, and I cannot change that.

I thought I would be clever and create a new jar with just those classes, but for some reason, that jar is being ignored.

```<code><dependency>
    <groupId>sun.misc</groupId>
    <artifactId>BASE64</artifactId>
    <version>1.8</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/lib/sun.jar</systemPath>
</dependency>
</code>```

I also tried adding it to the classpath explicitly but still no luck

Is this one of those packages that the JRE prevents you from playing with, or am I missing some module specification, or is this a show stopper?

Here is the output

```<code>java.lang.NoClassDefFoundError: sun/misc/BASE64Encoder
at com.propsco.util.support.PropsLoader.save(PropsLoader.java:478) ~[props-client-2.2.1.jar:na]
</code>```

答:
In past versions, Sun went to great lengths to ensure that there was no way to tamper with the runtime the way you are trying now (had it been as easy as this, everyone could have created their own private variant of the runtime - and surely you'll understand that wouldn't have been a good thing).  I don't know the details but they probably boiled down to "if package name is this or that or such or so, then loading will only happen from rt.jar" - hardcoded in the classloaders stuff.  It seems very likely those enforcement measures (or similar) are still in effect.

Scrapped the rest of my answer because I think you understand very well what your options are and that wasn't the question.

Body:
I am trying to upgrade my code base to Java 11. Unfortunately, my code has a dependency on a third-party library that internally uses sun.misc.BASE64Encoder and Decoder. Since the sun.misc package has been removed from the Java 11 JRE it is failing. The owner of that library has not replaced that dependency as yet, so I am stuck with it for a while.

If I had control of the code I would use java.util.BASE64 classes, but as I said these are coming in as a transitive dependency from another library, and I cannot change that.

I thought I would be clever and create a new jar with just those classes, but for some reason, that jar is being ignored.

<dependency>
    <groupId>sun.misc</groupId>
    <artifactId>BASE64</artifactId>
    <version>1.8</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/lib/sun.jar</systemPath>
</dependency>

I also tried adding it to the classpath explicitly but still no luck

Is this one of those packages that the JRE prevents you from playing with, or am I missing some module specification, or is this a show stopper?

Here is the output

java.lang.NoClassDefFoundError: sun/misc/BASE64Encoder
at com.propsco.util.support.PropsLoader.save(PropsLoader.java:478) ~[props-client-2.2.1.jar:na]


问:
Difference in graph plotted from excel and python?
Loaded the text file using pandas, and plotted the graph for selected two columns (mentioned in pd.read_csv command line)

Text files are here.

```<code>import matplotlib
import pandas as pd
import matplotlib.pyplot as plt
import glob

files=sorted(glob.glob(r"adress of folder containing text files\*.txt"))
T_raise= pd.read_csv(files[1],delimiter=',',skiprows=1,index_col=False,usecols=
["COLUMN A","COLUMN B"])
t=T_raise.iloc[1:6900,0]
T=T_raise.iloc[1:6900,1]
plt.plot(t.values,T.values)
</code>```

Plot obtained from python and excel are different, Python showing linear one which is not correct (Please find png of graph plotted from excel in link )

答:
Above problem of slowing down is sorted out, by using
a  buffer csv file

```<code>zip(t,T)
    with open('text.csv', 'w') as f:
        writer = csv.writer(f, delimiter='\t')
        writer.writerows(zip(t,T))
</code>```

to fetch the values for graph,

```<code># lines can be used for reading the different text files with similar number of columns, and getting graphs for selected columns and plotting them together in one figure
import matplotlib
import pandas as pd
import matplotlib.pyplot as plt
import csv
import glob
i=0;
files= sorted (glob.glob('<address of the text files there in link shared in question above\*.txt'))
nof = len(files)
for i in range(0,nof):
    T_raise= pd.read_csv(files[i],delimiter=',',skiprows=1,index_col=False,usecols=["column A","Column B"], header=0)

    t=T_raise.iloc[1:len(T_raise)-1,0]
    T=T_raise.iloc[1:len(T_raise)-1,1]
    zip(t,T)
    with open('text.csv', 'w') as f:
        writer = csv.writer(f, delimiter='\t')
        writer.writerows(zip(t,T))
        T2_raise=pd.read_csv('text.csv',delimiter='\t',header=0)
        t2=T2_raise.iloc[1:len(T2_raise)-1,0]
        T2=T2_raise.iloc[1:len(T2_raise)-1,1]
        plt.plot(t2,T2)
</code>```

Suggest if any better ways to do it, thanks

Body:
Loaded the text file using pandas, and plotted the graph for selected two columns (mentioned in pd.read_csv command line)

Text files are here.

import matplotlib
import pandas as pd
import matplotlib.pyplot as plt
import glob

files=sorted(glob.glob(r"adress of folder containing text files\*.txt"))
T_raise= pd.read_csv(files[1],delimiter=',',skiprows=1,index_col=False,usecols=
["COLUMN A","COLUMN B"])
t=T_raise.iloc[1:6900,0]
T=T_raise.iloc[1:6900,1]
plt.plot(t.values,T.values)

Plot obtained from python and excel are different, Python showing linear one which is not correct (Please find png of graph plotted from excel in link )

Body:
Above problem of slowing down is sorted out, by using
a  buffer csv file

zip(t,T)
    with open('text.csv', 'w') as f:
        writer = csv.writer(f, delimiter='\t')
        writer.writerows(zip(t,T))

to fetch the values for graph,

# lines can be used for reading the different text files with similar number of columns, and getting graphs for selected columns and plotting them together in one figure
import matplotlib
import pandas as pd
import matplotlib.pyplot as plt
import csv
import glob
i=0;
files= sorted (glob.glob('<address of the text files there in link shared in question above\*.txt'))
nof = len(files)
for i in range(0,nof):
    T_raise= pd.read_csv(files[i],delimiter=',',skiprows=1,index_col=False,usecols=["column A","Column B"], header=0)

    t=T_raise.iloc[1:len(T_raise)-1,0]
    T=T_raise.iloc[1:len(T_raise)-1,1]
    zip(t,T)
    with open('text.csv', 'w') as f:
        writer = csv.writer(f, delimiter='\t')
        writer.writerows(zip(t,T))
        T2_raise=pd.read_csv('text.csv',delimiter='\t',header=0)
        t2=T2_raise.iloc[1:len(T2_raise)-1,0]
        T2=T2_raise.iloc[1:len(T2_raise)-1,1]
        plt.plot(t2,T2)

Suggest if any better ways to do it, thanks


问:
VSTS/Azure Devops - Check if record exists in SQL Server as part of the CI/CD tasks
Using TFS 2018. I have setup a build pipeline that builds my solution and executes all unit tests. I want to add a step on the end that queries a table in SQL Server and returns back a boolean value, if false, I would like to fail the pipeline and return an error.

I have seen many extensions that allow me to execute a script, but none that return data I can use to perform an action.

Is this possible?

答:
You can use sqlcmd.exe from a Commandline/PowerShell Task to execute a query, then process the output in whatever way you want.

Similarly you can use the standard .NET SqlConnection/SqlCommand classes in PowerShell to execute a query and interpret the result. As well as the Invoke-Sqlcmd function.

To pass or fail the build you can use the Azure Pipeline Log commands to pass status back to the agent.

In Batch:

```<code>echo ##vso[task.complete result=Failed;]Your Message Here
</code>```

Or in PowerShell:

```<code>Write-Output "##vso[task.complete result=Failed;]Your Message Here"
</code>```

Body:
You can use sqlcmd.exe from a Commandline/PowerShell Task to execute a query, then process the output in whatever way you want.

Similarly you can use the standard .NET SqlConnection/SqlCommand classes in PowerShell to execute a query and interpret the result. As well as the Invoke-Sqlcmd function.

To pass or fail the build you can use the Azure Pipeline Log commands to pass status back to the agent.

In Batch:

echo ##vso[task.complete result=Failed;]Your Message Here

Or in PowerShell:

Write-Output "##vso[task.complete result=Failed;]Your Message Here"


问:
retrieving variable from intermed table
I need to retrieve institution name by going through an intermediate table.  My view gets all the values except this one or at least it is not displaying in the template.  Can someone please help with either revising my view or template statement?

http://dpaste.com/122204/

Thank you,

May

答:
To debug these kinds of problems do the following.

Run the view function's processing separate from any template or any other parts of Django.

Either interactively or with a VERY simple script run your query.  For example, use a simple script like this to explore your model and make sure your model really works.

```<code>from app.models import Contact, Institution, Whatever
results= Researchproject.objects.filter(restitlestrip__icontains='something').distinct()
for project in results:
    print project.contact
    print contact.institutionname
</code>```

Note several things about your simple script and your template.

Case matters.  Project != project.

Navigation matters. In the script shown above, contact is undefined.  project.contact, however, is defined.  Perhaps that's what you meant.

Your model appears incomplete.  The Contactintermed table doesn't seem to be used anywhere in your query or view.  It may have FK's to other tables, but you don't seem to have a sensible navigation from Project through Contact to Contactinterma to Institution.

Get your model to be correct in a stand-alone script.  Add the template processing later.

Also, please post all the code here on StackOverflow.  Chasing your code down all over the internet is a huge pain.  It's far easier to simply ignore your question than it is to chase down your code.

OwnerDisplayName: Ana

LastEditorDisplayName: Mark Brady

ContentLicense: CC BY-SA 2.5

Title: retrieving variable from intermed table

Body:
To debug these kinds of problems do the following.

Run the view function's processing separate from any template or any other parts of Django.

Either interactively or with a VERY simple script run your query.  For example, use a simple script like this to explore your model and make sure your model really works.

from app.models import Contact, Institution, Whatever
results= Researchproject.objects.filter(restitlestrip__icontains='something').distinct()
for project in results:
    print project.contact
    print contact.institutionname

Note several things about your simple script and your template.

Case matters.  Project != project.

Navigation matters. In the script shown above, contact is undefined.  project.contact, however, is defined.  Perhaps that's what you meant.

Your model appears incomplete.  The Contactintermed table doesn't seem to be used anywhere in your query or view.  It may have FK's to other tables, but you don't seem to have a sensible navigation from Project through Contact to Contactinterma to Institution.

Get your model to be correct in a stand-alone script.  Add the template processing later.

Also, please post all the code here on StackOverflow.  Chasing your code down all over the internet is a huge pain.  It's far easier to simply ignore your question than it is to chase down your code.


问:
How can I filter an Iterable based upon a Predicate?
I want to do a string list filter function using an Iterable<String> and a predicate to select the strings to keep, the other ones must be removed from the list, but I'm not understating how I do the remove.

```<code>static <T> Iterable<T> select(Iterable<T> it, Predicate<T> pred) {
    for (T s: it) {
        if (pred.test(s)==false) {
            // what to do here?
        }
    }
    return ...;
}
</code>```

For this input:

```<code>{"a","","b",""}
</code>```

I expect

```<code>{"a","b"}
</code>```

答:
First wrap your Iterable<T> into Stream<T>:

Plain Java:

```<code>StreamSupport.stream(it.spliterator(), false)
</code>```

Guava

```<code>Streams.stream(it)
</code>```

StreamEx

```<code>StreamEx.of(it.iterator())
</code>```

Then filter it by your Predicate<T> :

```<code>...
stream.filter(pred.negate())
...
</code>```

And finally return Iterable<T>:

as lambda :

```<code>return () -> stream.iterator();
</code>```

as method reference

```<code>return stream::iterator;
</code>```

Complete example:

```<code>static <T> Iterable<T> select(Iterable<T> it, Predicate<T> pred) {
    return StreamSupport.stream(it.spliterator(), false).filter(pred.negate())::iterator;
}
</code>```

or:

```<code>static <T> Iterable<T> select(Iterable<T> it, Predicate<T> pred) {
    Stream<T> stream = stream(it.spliterator(), false);
    Predicate<T> negatedPred = pred.negate();
    Stream<T> filteredStream = stream.filter(negatedPred);
    return filteredStream::iterator;
}
</code>```

Body:
I want to do a string list filter function using an Iterable<String> and a predicate to select the strings to keep, the other ones must be removed from the list, but I'm not understating how I do the remove.

static <T> Iterable<T> select(Iterable<T> it, Predicate<T> pred) {
    for (T s: it) {
        if (pred.test(s)==false) {
            // what to do here?
        }
    }
    return ...;
}

For this input:

{"a","","b",""}

I expect

{"a","b"}

Body:
First wrap your Iterable<T> into Stream<T>:

Plain Java:

StreamSupport.stream(it.spliterator(), false)

Guava

Streams.stream(it)

StreamEx

StreamEx.of(it.iterator())

Then filter it by your Predicate<T> :

...
stream.filter(pred.negate())
...

And finally return Iterable<T>:

as lambda :

return () -> stream.iterator();

as method reference

return stream::iterator;

Complete example:

static <T> Iterable<T> select(Iterable<T> it, Predicate<T> pred) {
    return StreamSupport.stream(it.spliterator(), false).filter(pred.negate())::iterator;
}

or:

static <T> Iterable<T> select(Iterable<T> it, Predicate<T> pred) {
    Stream<T> stream = stream(it.spliterator(), false);
    Predicate<T> negatedPred = pred.negate();
    Stream<T> filteredStream = stream.filter(negatedPred);
    return filteredStream::iterator;
}


问:
Why isn't my DiffUtil with RecyclerView working?
I'm trying to create a simple DiffUtil Adapter to work with a RecyclerView and nothing shows up (I only get a blank activity). Here is the code:

MainActivity.java:

```<code>public class MainActivity extends AppCompatActivity {

    private MyAdapter mAdapter;
    private ArrayList<User> myDataset;
    private RecyclerView mRecyclerView;

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

        mAdapter = new MyAdapter();
        myDataset = new ArrayList<User>();

        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        myDataset.add(new User("User1"));
        myDataset.add(new User("User2"));
        myDataset.add(new User("User3"));

        mRecyclerView.setAdapter(mAdapter);

        mAdapter.updateList(myDataset);
    }
}
</code>```

Here is MyAdapter.java:

```<code>public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    private AsyncListDiffer<User> mAsyncListDiffer;

    public static class MyViewHolder extends RecyclerView.ViewHolder {

        public TextView singleItemTextView;
        public View layout;
        public ConstraintLayout constraintLayout;

        public MyViewHolder(View v) {
            super(v);
            layout = v;
            singleItemTextView = (TextView) v.findViewById(R.id.singleItemTextView);
            constraintLayout = (ConstraintLayout) v.findViewById(R.id.constraintLayout);
        }
    }

    // Provide a suitable constructor (depends on the kind of dataset)
    public MyAdapter() {
        DiffUtil.ItemCallback<User> diffUtilCallback = new DiffUtil.ItemCallback<User>() {

            @Override
            public boolean areItemsTheSame(@NonNull User newUser, @NonNull User oldUser) {
                return newUser.getUserId().equals(oldUser.getUserId());
            }

            @Override
            public boolean areContentsTheSame(@NonNull User newUser, @NonNull User oldUser) {
                return newUser.equals(oldUser);
            }
        };
        mAsyncListDiffer = new AsyncListDiffer<>(this, diffUtilCallback);
    }

    // Create new views (invoked by the layout manager)
    @Override
    public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_text_view, parent, false);
        MyViewHolder vh = new MyViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        User user = mAsyncListDiffer.getCurrentList().get(position);
        holder.singleItemTextView.setText(user.getUserId());
    }

    @Override
    public int getItemCount() {
        return mAsyncListDiffer.getCurrentList().size();
    }

    public void updateList(ArrayList<User> newList) {
        mAsyncListDiffer.submitList(newList);
    }

}
</code>```

Here is User.java:

```<code>public class User {

    private String mUserId;

    public User(String userId) {
        mUserId = userId;
    }

    public String getUserId() {
        return mUserId;
    }

}
</code>```

Here are the XML files:

acivity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="4dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:background="#FFFFFF"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

and here is single_text_view.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:layout_editor_absoluteY="81dp">

    <TextView
        android:id="@+id/singleItemTextView"
        android:layout_width="78dp"
        android:layout_height="78dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

I know that DiffUtil is supposed to compare 2 different lists and here I only set up the initial list, but still, shouldn't it at least display the first list (with 3 users in this case)?

答:
Do you check if your getItemCount() method returns more than 0 ?

If it is, you should look at your item view. Try to remove constraints on this view first to see if anything appears on the screen.

Body:
I'm trying to create a simple DiffUtil Adapter to work with a RecyclerView and nothing shows up (I only get a blank activity). Here is the code:

MainActivity.java:

public class MainActivity extends AppCompatActivity {

    private MyAdapter mAdapter;
    private ArrayList<User> myDataset;
    private RecyclerView mRecyclerView;

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

        mAdapter = new MyAdapter();
        myDataset = new ArrayList<User>();

        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        myDataset.add(new User("User1"));
        myDataset.add(new User("User2"));
        myDataset.add(new User("User3"));

        mRecyclerView.setAdapter(mAdapter);

        mAdapter.updateList(myDataset);
    }
}

Here is MyAdapter.java:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    private AsyncListDiffer<User> mAsyncListDiffer;

    public static class MyViewHolder extends RecyclerView.ViewHolder {

        public TextView singleItemTextView;
        public View layout;
        public ConstraintLayout constraintLayout;

        public MyViewHolder(View v) {
            super(v);
            layout = v;
            singleItemTextView = (TextView) v.findViewById(R.id.singleItemTextView);
            constraintLayout = (ConstraintLayout) v.findViewById(R.id.constraintLayout);
        }
    }

    // Provide a suitable constructor (depends on the kind of dataset)
    public MyAdapter() {
        DiffUtil.ItemCallback<User> diffUtilCallback = new DiffUtil.ItemCallback<User>() {

            @Override
            public boolean areItemsTheSame(@NonNull User newUser, @NonNull User oldUser) {
                return newUser.getUserId().equals(oldUser.getUserId());
            }

            @Override
            public boolean areContentsTheSame(@NonNull User newUser, @NonNull User oldUser) {
                return newUser.equals(oldUser);
            }
        };
        mAsyncListDiffer = new AsyncListDiffer<>(this, diffUtilCallback);
    }

    // Create new views (invoked by the layout manager)
    @Override
    public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_text_view, parent, false);
        MyViewHolder vh = new MyViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        User user = mAsyncListDiffer.getCurrentList().get(position);
        holder.singleItemTextView.setText(user.getUserId());
    }

    @Override
    public int getItemCount() {
        return mAsyncListDiffer.getCurrentList().size();
    }

    public void updateList(ArrayList<User> newList) {
        mAsyncListDiffer.submitList(newList);
    }

}

Here is User.java:

public class User {

    private String mUserId;

    public User(String userId) {
        mUserId = userId;
    }

    public String getUserId() {
        return mUserId;
    }

}

Here are the XML files:

acivity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="4dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:background="#FFFFFF"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

and here is single_text_view.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:layout_editor_absoluteY="81dp">

    <TextView
        android:id="@+id/singleItemTextView"
        android:layout_width="78dp"
        android:layout_height="78dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

I know that DiffUtil is supposed to compare 2 different lists and here I only set up the initial list, but still, shouldn't it at least display the first list (with 3 users in this case)?


问:
Animate Image transitions in Android
I have 4 ImageViews (Please see picture attached below)

The code for the 4 images are as such:

```<code><LinearLayout
    android:id="@id/LinearLayout_fromAddItemActivity_Priority"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintBottom_toTopOf="@+id/FAB_fromAddItemActivity_AddItem"
    app:layout_constraintTop_toBottomOf="@+id/TextView_fromAddItemActivity_SubtitlePriority"
    app:layout_constraintVertical_chainStyle="packed">

<ImageView
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:onClick="setPriority"
        android:tag="@{Constant.ENUM_PRIORITY_P1}"
        android:contentDescription="@string/ContentDescription_fromAddItemActivity_Priority1Icon"
        app:srcCompat="@drawable/ic_priority_1"/>
<ImageView
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:onClick="setPriority"
        android:tag="@{Constant.ENUM_PRIORITY_P2}"
        android:contentDescription="@string/ContentDescription_fromAddItemActivity_Priority2Icon"
        app:srcCompat="@drawable/ic_priority_2"/>
<ImageView
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:onClick="setPriority"
        android:tag="@{Constant.ENUM_PRIORITY_P3}"
        android:contentDescription="@string/ContentDescription_fromAddItemActivity_Priority3Icon"
        app:srcCompat="@drawable/ic_priority_3"/>
<ImageView
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:onClick="setPriority"
        android:tag="@{Constant.ENUM_PRIORITY_P4}"
        android:contentDescription="@string/ContentDescription_fromAddItemActivity_Priority4Icon"
        app:srcCompat="@drawable/ic_priority_4"/>
</code>```

On clicking on either of these images, I want them to transition as shown in the picture below with the image clicked to be on top!

Anybody can help me with these, please?

(I don't know much about transitions and animations in Android, I just know how to transition between activities).

答: I think you may set android:animateLayoutChanges="true" at your LinearLayout and then just set visibility of ImageView's, which need to be hidden, as View.GONE.

Title: Animate Image transitions in Android

Body:
I have 4 ImageViews (Please see picture attached below)

The code for the 4 images are as such:

<LinearLayout
    android:id="@id/LinearLayout_fromAddItemActivity_Priority"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintBottom_toTopOf="@+id/FAB_fromAddItemActivity_AddItem"
    app:layout_constraintTop_toBottomOf="@+id/TextView_fromAddItemActivity_SubtitlePriority"
    app:layout_constraintVertical_chainStyle="packed">

<ImageView
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:onClick="setPriority"
        android:tag="@{Constant.ENUM_PRIORITY_P1}"
        android:contentDescription="@string/ContentDescription_fromAddItemActivity_Priority1Icon"
        app:srcCompat="@drawable/ic_priority_1"/>
<ImageView
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:onClick="setPriority"
        android:tag="@{Constant.ENUM_PRIORITY_P2}"
        android:contentDescription="@string/ContentDescription_fromAddItemActivity_Priority2Icon"
        app:srcCompat="@drawable/ic_priority_2"/>
<ImageView
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:onClick="setPriority"
        android:tag="@{Constant.ENUM_PRIORITY_P3}"
        android:contentDescription="@string/ContentDescription_fromAddItemActivity_Priority3Icon"
        app:srcCompat="@drawable/ic_priority_3"/>
<ImageView
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:onClick="setPriority"
        android:tag="@{Constant.ENUM_PRIORITY_P4}"
        android:contentDescription="@string/ContentDescription_fromAddItemActivity_Priority4Icon"
        app:srcCompat="@drawable/ic_priority_4"/>

On clicking on either of these images, I want them to transition as shown in the picture below with the image clicked to be on top!

Anybody can help me with these, please?

(I don't know much about transitions and animations in Android, I just know how to transition between activities).


问:
Sentry doesn't show HttpContext User info in ASP.NET Core application
I've only used the base Sentry configuration from the webPage.

```<code>  "Sentry": {
    "Dsn": "",
    "IncludeRequestPayload": true,
    "SendDefaultPii": true,
    "MinimumBreadcrumbLevel": "Debug",
    "MinimumEventLevel": "Warning",
    "AttachStackTrace": true,
    "Debug": true,
    "DiagnosticsLevel": "Error"
  }
</code>```

From what I've gathered I should see User info which Setry picks up using its middleware from HttpContext.User.

But on the webPage I only see Ip ::1

Should I configure something else ? I can't seem to find any extra configuration.

EDIT

I'm using Sentry version 1.2.0. My HttpContext.

User is set for sure with user information.

For Authentication I'm using Jwt Tokens

```<code>services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; })
</code>```

Regards

答:
I don't remember what version I used on one of the projects I worked, and I don't remember exactly from where "User" was detected, but if I remember correct was ControllerBase.User

Anyway, depends what authorization mechanism you got, maybe you need to inject it HttpContext.User into ControllerBase.User (typeof ClaimsPrincipal)

On your serviceCollection (startup I guess) do this:

```<code>services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddTransient<IPrincipal>(provider => provider.GetService<IHttpContextAccessor>().HttpContext?.User);
</code>```

Body:
I've only used the base Sentry configuration from the webPage.

  "Sentry": {
    "Dsn": "",
    "IncludeRequestPayload": true,
    "SendDefaultPii": true,
    "MinimumBreadcrumbLevel": "Debug",
    "MinimumEventLevel": "Warning",
    "AttachStackTrace": true,
    "Debug": true,
    "DiagnosticsLevel": "Error"
  }

From what I've gathered I should see User info which Setry picks up using its middleware from HttpContext.User.

But on the webPage I only see Ip ::1

Should I configure something else ? I can't seem to find any extra configuration.

EDIT

I'm using Sentry version 1.2.0. My HttpContext.

User is set for sure with user information.

For Authentication I'm using Jwt Tokens

services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; })

Regards

Body:
I don't remember what version I used on one of the projects I worked, and I don't remember exactly from where "User" was detected, but if I remember correct was ControllerBase.User

Anyway, depends what authorization mechanism you got, maybe you need to inject it HttpContext.User into ControllerBase.User (typeof ClaimsPrincipal)

On your serviceCollection (startup I guess) do this:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddTransient<IPrincipal>(provider => provider.GetService<IHttpContextAccessor>().HttpContext?.User);


问:
Why does HttpClient appear to hang without .Result?
I have this code to call an API which returns a token. However, it will only return if I replace this line:

```<code>var response = await TokenClient.PostAsync(EnvironmentHelper.TokenUrl, formContent);
</code>```

with this line:

```<code>var response = TokenClient.PostAsync(EnvironmentHelper.TokenUrl, formContent).Result;
</code>```

Why?

```<code>public static async Task<Token> GetAPIToken()
{
    if (DateTime.Now < Token.Expiry)
        return Token;

    TokenClient.DefaultRequestHeaders.Clear();
    TokenClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    TokenClient.BaseAddress = new Uri(EnvironmentHelper.BaseUrl);
    TokenClient.Timeout = TimeSpan.FromSeconds(3);

    var formContent = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("grant_type", "client_credentials"),
        new KeyValuePair<string, string>("client_id", EnvironmentHelper.APITokenClientId),
        new KeyValuePair<string, string>("client_secret", EnvironmentHelper.APITokenClientSecret)
    });

    try
    {
        // HANGS - this next line will only ever return if suffixed with '.Result'
        var response = await TokenClient.PostAsync(EnvironmentHelper.TokenUrl, formContent);

        var content = await response.Content.ReadAsStringAsync();
        dynamic jsonContent = JsonConvert.DeserializeObject(content);

        Token token = new Token();
        token.AccessToken = jsonContent.access_token;
        token.Type = jsonContent.token_type;
        token.Expiry = DateTimeOffset.Now.AddSeconds(Convert.ToDouble(jsonContent.expires_in.ToString()) - 30);
        token.Scope = Convert.ToString(jsonContent.scope).Split(' ');

        Token = token;
    }
    catch (Exception ex)
    {
        var m = ex.Message;
    }

    return Token;
}
</code>```

答:
The top-most code where awaiting is not performed has this: var wm = new WebRepo().GetWeb(Id).Result

You're running into a deadlock since the synchronous code is blocking on async code. The best solution is to remove the blocking and go async all the way.

The calling code is a public static property with a getter, referenced in over 100 places. I'm not sure how best to convert the property to async friendly

There are a few approaches to async properties, depending on what the property's semantics are. If it re-evaluates each time it's called, then it's really a method in disguise and should become an async Task<T> method. If it is set once, then AsyncLazy<T> may be a better choice.

Is there a way to wrap one of the calls? It is a mammoth task to go and refactor that much code.

There's no wrapping that works for all scenarios. However, there are some techniques for mixing sync and async code that can work for specific scenarios.

Here's what I would consider, in order of precedence:

Make it async all the way. Refactor the code and make it better. (Requires lots of code changes, which may not be feasible at this time).

Make it sync all the way. Change GetAPIToken (and its callers) to be sync instead of async. (Requires all calling code to be made synchronous, which may not be possible).

Use the boolean argument hack to make GetAPIToken callable both synchronously and asynchronously. (Requires the ability to change GetAPIToken).

Use the thread pool hack to run GetAPIToken asynchronously on a thread pool thread and sycnhronously block another thread on it.

Body:
I have this code to call an API which returns a token. However, it will only return if I replace this line:

var response = await TokenClient.PostAsync(EnvironmentHelper.TokenUrl, formContent);

with this line:

var response = TokenClient.PostAsync(EnvironmentHelper.TokenUrl, formContent).Result;

Why?

public static async Task<Token> GetAPIToken()
{
    if (DateTime.Now < Token.Expiry)
        return Token;

    TokenClient.DefaultRequestHeaders.Clear();
    TokenClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    TokenClient.BaseAddress = new Uri(EnvironmentHelper.BaseUrl);
    TokenClient.Timeout = TimeSpan.FromSeconds(3);

    var formContent = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("grant_type", "client_credentials"),
        new KeyValuePair<string, string>("client_id", EnvironmentHelper.APITokenClientId),
        new KeyValuePair<string, string>("client_secret", EnvironmentHelper.APITokenClientSecret)
    });

    try
    {
        // HANGS - this next line will only ever return if suffixed with '.Result'
        var response = await TokenClient.PostAsync(EnvironmentHelper.TokenUrl, formContent);

        var content = await response.Content.ReadAsStringAsync();
        dynamic jsonContent = JsonConvert.DeserializeObject(content);

        Token token = new Token();
        token.AccessToken = jsonContent.access_token;
        token.Type = jsonContent.token_type;
        token.Expiry = DateTimeOffset.Now.AddSeconds(Convert.ToDouble(jsonContent.expires_in.ToString()) - 30);
        token.Scope = Convert.ToString(jsonContent.scope).Split(' ');

        Token = token;
    }
    catch (Exception ex)
    {
        var m = ex.Message;
    }

    return Token;
}


问:
ignore increacing font size of windows in .net
In Windows it's possible to increase the size of on-screen fonts. We realized that too late and if a user does this our program is unusable, because they cannot see all texts and controls. We're bringing out a release and we do not have the time to fix this.
So: how can I disable or ignore this increasing from Windows application-wide? I tried setting autoscale to none, but it is not working. Isn't it possible to ignore that setting for the whole application? How can I do that?

I know that this is a wak solution because the user has a reason why they want to increase the font size. But we cannot fix this problem within two weeks, and want to provide an application somebody can use.

We are using VB.NET.

答: There's no property or setting that you can adjust to tell a .NET application to ignore the settings you're talking about.  You will have to look for another option.</p>


问:
Tensorflow: create tf.NodeDef() and set attributes
I'm trying to create a new node and set its attributes.

For example printing one of the graph nodes I see that its attributes are:

```<code>attr {
  key: "T"
  value {
    type: DT_FLOAT
  }
}
</code>```

I can create a node like:

```<code>node = tf.NodeDef(name='MyConstTensor', op='Const',
                   attr={'value': tf.AttrValue(tensor=tensor_proto),
                         'dtype': tf.AttrValue(type=dt)})
</code>```

but how to add key: "T" atribute? i.e. what should be inside tf.AttrValue in this case?

Looking at attr_value.proto I have tried:

```<code>node = tf.NodeDef()
node.name = 'MySub'
node.op = 'Sub'
node.input.extend(['MyConstTensor', 'conv2'])
node.attr["key"].s = 'T' # TypeError: 'T' has type str, but expected one of: bytes
</code>```

UPDATE:

I figured out that in Tensorflow it should be written like:

```<code>node.attr["T"].type = b'float32'
</code>```

But this gives an error:

TypeError: b'float32' has type bytes, but expected one of: int, long

And I'm not sure which int value corresponds to float32.

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/attr_value.proto#L23

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/attr_value.proto#L35

答:
Try passing T as a byte:

```<code>node.attr["key"].s = b'T'
</code>```

If you would like to pass more characters try the bytearray class.

In the protobuf definition of AttrValue s is defined as bytes not string. The Protobuf manual states that this should be a string in python but your error suggests it is more like a byte array.

Body:
I'm trying to create a new node and set its attributes.

For example printing one of the graph nodes I see that its attributes are:

attr {
  key: "T"
  value {
    type: DT_FLOAT
  }
}

I can create a node like:

node = tf.NodeDef(name='MyConstTensor', op='Const',
                   attr={'value': tf.AttrValue(tensor=tensor_proto),
                         'dtype': tf.AttrValue(type=dt)})

but how to add key: "T" atribute? i.e. what should be inside tf.AttrValue in this case?

Looking at attr_value.proto I have tried:

node = tf.NodeDef()
node.name = 'MySub'
node.op = 'Sub'
node.input.extend(['MyConstTensor', 'conv2'])
node.attr["key"].s = 'T' # TypeError: 'T' has type str, but expected one of: bytes

UPDATE:

I figured out that in Tensorflow it should be written like:

node.attr["T"].type = b'float32'

But this gives an error:

TypeError: b'float32' has type bytes, but expected one of: int, long

And I'm not sure which int value corresponds to float32.

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/attr_value.proto#L23

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/attr_value.proto#L35

Body:
Try passing T as a byte:

node.attr["key"].s = b'T'

If you would like to pass more characters try the bytearray class.

In the protobuf definition of AttrValue s is defined as bytes not string. The Protobuf manual states that this should be a string in python but your error suggests it is more like a byte array.


问:
Newton Raphsons method in Matlab?
Newtons-Raphsons method is easy to implement in Mathematica but in Matlab it seems a bit difficult. I don't get if I can pass a function to a function and how to use the derivative as a function.

```<code>newtonRaphson[f_, n_, guess_] :=
 If[n == 0, guess, newtonRaphson[f, n - 1, guess - f[guess]/f'[guess]]]
newtonRaphsonOptimize[f_, n_, guess_] :=
 If[n == 0, guess,
  newtonRaphsonOptimize[f, n - 1, guess - f'[guess]/f''[guess]]]
</code>```

It doesn't seem like you can derive neither function-handles nor functions defined in a file but I might be wrong.

答:
There's no way to algebraically take derivatives of function handles or functions defined in m-files. You would have to do this numerically by evaluating the function at a number of points and approximating the derivative.

What you're probably wanting to do is differentiation of symbolic equations, and you need the Symbolic Math Toolbox for that. Here's an example of finding a root using the Newton-Raphson method:

```<code>>> syms x            %# Create a symbolic variable x
>> f = (x-4)^2-4;    %# Create a function of x to find a root of
>> xRoot = 1;        %# Initial guess for the root
>> g = x-f/diff(f);  %# Create a Newton-Raphson approximation function
>> xRoot = subs(g,'x',xRoot)  %# Evaluate the function at the initial guess

xRoot =

    1.8333

>> xRoot = subs(g,'x',xRoot)  %# Evaluate the function at the refined guess

xRoot =

    1.9936

>> xRoot = subs(g,'x',xRoot)  %# Evaluate the function at the refined guess

xRoot =

    2.0000
</code>```

You can see that the value of xRoot comes close to the value of the true root (which is 2) after just a couple of iterations. You could also place the function evaluation in a while loop with a condition that checks how big a difference there is between each new guess and the previous guess, stopping when that difference is sufficiently small (i.e. the root has been found):

```<code>xRoot = 1;                     %# Initial guess
xNew = subs(g,'x',xRoot);      %# Refined guess
while abs(xNew-xRoot) > 1e-10  %# Loop while they differ by more than 1e-10
  xRoot = xNew;                %# Update the old guess
  xNew = subs(g,'x',xRoot);    %# Update the new guess
end
xRoot = xNew;                  %# Update the final value for the root
</code>```

Title: Newton Raphsons method in Matlab?

Body:
Newtons-Raphsons method is easy to implement in Mathematica but in Matlab it seems a bit difficult. I don't get if I can pass a function to a function and how to use the derivative as a function.

newtonRaphson[f_, n_, guess_] :=
 If[n == 0, guess, newtonRaphson[f, n - 1, guess - f[guess]/f'[guess]]]
newtonRaphsonOptimize[f_, n_, guess_] :=
 If[n == 0, guess,
  newtonRaphsonOptimize[f, n - 1, guess - f'[guess]/f''[guess]]]

It doesn't seem like you can derive neither function-handles nor functions defined in a file but I might be wrong.

Body:
There's no way to algebraically take derivatives of function handles or functions defined in m-files. You would have to do this numerically by evaluating the function at a number of points and approximating the derivative.

What you're probably wanting to do is differentiation of symbolic equations, and you need the Symbolic Math Toolbox for that. Here's an example of finding a root using the Newton-Raphson method:

>> syms x            %# Create a symbolic variable x
>> f = (x-4)^2-4;    %# Create a function of x to find a root of
>> xRoot = 1;        %# Initial guess for the root
>> g = x-f/diff(f);  %# Create a Newton-Raphson approximation function
>> xRoot = subs(g,'x',xRoot)  %# Evaluate the function at the initial guess

xRoot =

    1.8333

>> xRoot = subs(g,'x',xRoot)  %# Evaluate the function at the refined guess

xRoot =

    1.9936

>> xRoot = subs(g,'x',xRoot)  %# Evaluate the function at the refined guess

xRoot =

    2.0000

You can see that the value of xRoot comes close to the value of the true root (which is 2) after just a couple of iterations. You could also place the function evaluation in a while loop with a condition that checks how big a difference there is between each new guess and the previous guess, stopping when that difference is sufficiently small (i.e. the root has been found):

xRoot = 1;                     %# Initial guess
xNew = subs(g,'x',xRoot);      %# Refined guess
while abs(xNew-xRoot) > 1e-10  %# Loop while they differ by more than 1e-10
  xRoot = xNew;                %# Update the old guess
  xNew = subs(g,'x',xRoot);    %# Update the new guess
end
xRoot = xNew;                  %# Update the final value for the root


问:
c# linq selecting words that not start with
Consider these arrays:

```<code>string[] bad_starts = { "a", "b", "col" };
string[] word_list = { "green", "blue", "color", "cyan", "maroon", "white", "black" };
</code>```

I need to select all the words in word_list that don't start with any string in bad_starts.
The expected result is:

```<code>{ "green", "cyan", "maroon", "white" };
</code>```

Any solution? Could we use linq join?

答:
I like the 'Except' option

```<code>  var result = word_list.Except(word_list.Where(w => bad_starts.Any(b => w.StartsWith(b)))).ToList();
</code>```

In the example I'm saying the following:

Select all words that starts with any character in bad_starts

Find all the words in word_list that contains these words

In the original 'word_list', exclude ('Except') all of these matches

So in plain English:

Select all words 'Except' the ones starting with specified characters

Another way of putting it is:

```<code>var bad_words = word_list.Where(w => bad_starts.Any(b => w.StartsWith(b));
var result = word_list.Except(bad_words);
</code>```

Body:
Consider these arrays:

string[] bad_starts = { "a", "b", "col" };
string[] word_list = { "green", "blue", "color", "cyan", "maroon", "white", "black" };

I need to select all the words in word_list that don't start with any string in bad_starts.
The expected result is:

{ "green", "cyan", "maroon", "white" };

Any solution? Could we use linq join?

Body:
I like the 'Except' option

  var result = word_list.Except(word_list.Where(w => bad_starts.Any(b => w.StartsWith(b)))).ToList();

In the example I'm saying the following:

Select all words that starts with any character in bad_starts

Find all the words in word_list that contains these words

In the original 'word_list', exclude ('Except') all of these matches

So in plain English:

Select all words 'Except' the ones starting with specified characters

Another way of putting it is:

var bad_words = word_list.Where(w => bad_starts.Any(b => w.StartsWith(b));
var result = word_list.Except(bad_words);


问:
How to set an initial/default value for the array used by <FieldArray/>?
I have been creating a form with react-final form. This form has some conditional fields, that only display when a user clicks a checkbox. If the checkbox is checked, then a  component is rendered.

It is very similar to the example they provide in the documentation, which you can see here. https://codesandbox.io/s/kx8qv67nk5

I am basing myself off that example, and i can add to the field array with a button that calls the push method, exactly as in the example.

What i would like to do is not have to push a button in order to push that object into the array, but rather have the array default already include one object inside.

in other words,

In the example provided, the array starts empty and you push() into the array,the fields that are defined within

How can i have it default to already having one object by default instead of manually pushing it?

Im not sure where that array is getting defined or initialized.

答:
Loick M is close, but for an array, you'd need:</p>

```<code><Form
  onSubmit={myOnSubmit}
  initialValues={{ musicians: [ { firstName: 'Bob', lastName: 'Marley' } ] }}>
  ...
</Form>
</code>```

Body:
Loick M is close, but for an array, you'd need:

<Form
  onSubmit={myOnSubmit}
  initialValues={{ musicians: [ { firstName: 'Bob', lastName: 'Marley' } ] }}>
  ...
</Form>


问:
Tableau Start, end, and center settings for colors in heat map
I think I have a simple question but I can't figure it out.

I have a measure that shows percentages. I want to use 'red-green-yellow diverging' under "edit colors" to set colors based on the following criteria:

0%-100% = green;
100%-115% = yellow;
greater than 115% = red
```

This should be so simple! I can't figure out how to use the "start", "end", "center" in the 'edit colors' to achieve what I want above.

答:
you need to write the if condition to achieve the result

```<code>if field >=0% and field <100%
then green
elseif field >=100% and field <115%
then yellow
else
red
</code>```

Place formula in colors and then edit colors and then assign required colors for the output

Body:
I think I have a simple question but I can't figure it out.

I have a measure that shows percentages. I want to use 'red-green-yellow diverging' under "edit colors" to set colors based on the following criteria:

0%-100% = green;
100%-115% = yellow;
greater than 115% = red

This should be so simple! I can't figure out how to use the "start", "end", "center" in the 'edit colors' to achieve what I want above.

Body:
you need to write the if condition to achieve the result

if field >=0% and field <100%
then green
elseif field >=100% and field <115%
then yellow
else
red

Place formula in colors and then edit colors and then assign required colors for the output


问:
Set label text to Bold on tap
I need to have the text of a cell turn bold when tapped then return to light when tapped again

I tried
self.preguntaLabel.font = UIFont.boldSystemFont(ofSize: 14.0)
and it works but it doesn't return to light weight.

So lets say

(This is the cell)

When tapped it has to turn the text bold

(This is the cell)

Then, when tapped again, return to light

(This is the cell)

答:
Try the switch or if statements to make it bold or not. with tap.

```<code>self.preguntaLabel.font == UIFont.boldSystemFont(ofSize: 14.0) {
  // bold
} else {
  // light
}
</code>```

Hope it will works.

Title: Set label text to Bold on tap

Body:
Try the switch or if statements to make it bold or not. with tap.

self.preguntaLabel.font == UIFont.boldSystemFont(ofSize: 14.0) {
  // bold
} else {
  // light
}

Hope it will works.


问:
Is there a difference between the statements below?
I was looking at the solution for the Titanic Problem in Kaggle and there is a part that it does:

```<code>data['Cabin'] = data['Cabin'].replace(['A', 'D', 'E', 'T'], 'M')
</code>```

What is the difference between the code above and only:

```<code>data['Cabin'].replace(['A', 'D', 'E', 'T'], 'M')
</code>```

答:
To modify the 'Cabin' column in data Dataframe use:

```<code>data['Cabin'] = data['Cabin'].replace(['A', 'D', 'E', 'T'], 'M')
</code>```

recommended way is:

```<code>data['Cabin'].replace(['A', 'D', 'E', 'T'], 'M', inplace=True)
</code>```

Below code will simply return new series. The data DataFrame will not be modified:

```<code>data['Cabin'].replace(['A', 'D', 'E', 'T'], 'M')
</code>```

Body:
I was looking at the solution for the Titanic Problem in Kaggle and there is a part that it does:

data['Cabin'] = data['Cabin'].replace(['A', 'D', 'E', 'T'], 'M')

What is the difference between the code above and only:

data['Cabin'].replace(['A', 'D', 'E', 'T'], 'M')

Body:
To modify the 'Cabin' column in data Dataframe use:

data['Cabin'] = data['Cabin'].replace(['A', 'D', 'E', 'T'], 'M')

recommended way is:

data['Cabin'].replace(['A', 'D', 'E', 'T'], 'M', inplace=True)

Below code will simply return new series. The data DataFrame will not be modified:

data['Cabin'].replace(['A', 'D', 'E', 'T'], 'M')


问:
Center align li with equal height and fixed width
Under an ul, there are 5 li's. wanted to have all the li with same height with fixed width(20% for each li is 100%). i have achieved that with the below code.But my problem is, if i have only 3 or 4 li's i want to display the li's with same height and width but in center. Right now if i have 3 or 4, the width is adjusting and occupying the whole ul container.

Even if its 3 li or 4 li, the li should have fixed width with aligned in the center.

.box-outer {
  text-align: center;
  display: table;
  table-layout: fixed;
  background-color: #333;
}

.boxes {
  vertical-align: middle;
  width: 10% !important;
  margin-right: 1% !important;
  background: #fff;
  border-radius: 6px;
  text-align: center;
  padding: 32px 29px;
  display: table-cell;
}

.field-number {
  color: #de008d;
  font-size: 48px;
  font-family: sans-serif;
}

.field-text {
  padding-top: 10px;
  color: #333;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-outer">
  <div class="boxes">
    <h4 class="field-number">83</h4>
    <span class="field-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit,</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">7,800</h4><span class="field-text">mod tempor incididunt ut labor</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">65k</h4><span class="field-text">ut aliquip</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">37k</h4><span class="field-text">Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">£250m</h4><span class="field-text">veniam, quis nostrud exercitation ullamco</span>
  </div>
</div></code>```

JS Fiddle Link

答:
You can use flexbox.

Just create a container with

```<code>display: flex;
justify-content: center;
align-items: stretch;
</code>```

and set your inner boxes with

```<code>flex: 0 0 20%;
display: flex;
align-items: center
</code>```

Like this each element has 20% width of the container, regardless how many they are, and are always centered in the container. Obviously, the sixth would wrap on a second line but still centered.

Body:
Under an ul, there are 5 li's. wanted to have all the li with same height with fixed width(20% for each li is 100%). i have achieved that with the below code.But my problem is, if i have only 3 or 4 li's i want to display the li's with same height and width but in center. Right now if i have 3 or 4, the width is adjusting and occupying the whole ul container.

Even if its 3 li or 4 li, the li should have fixed width with aligned in the center.

.box-outer {
  text-align: center;
  display: table;
  table-layout: fixed;
  background-color: #333;
}

.boxes {
  vertical-align: middle;
  width: 10% !important;
  margin-right: 1% !important;
  background: #fff;
  border-radius: 6px;
  text-align: center;
  padding: 32px 29px;
  display: table-cell;
}

.field-number {
  color: #de008d;
  font-size: 48px;
  font-family: sans-serif;
}

.field-text {
  padding-top: 10px;
  color: #333;
}

83

    Lorem ipsum dolor sit amet, consectetur adipiscing elit,

7,800
mod tempor incididunt ut labor

65k
ut aliquip

37k
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

£250m
veniam, quis nostrud exercitation ullamco

JS Fiddle Link

Body:
You can use flexbox.

Just create a container with

display: flex;
justify-content: center;
align-items: stretch;

and set your inner boxes with

flex: 0 0 20%;
display: flex;
align-items: center

Like this each element has 20% width of the container, regardless how many they are, and are always centered in the container. Obviously, the sixth would wrap on a second line but still centered.


问:
Dynamic SQL Query in Flink
I have a SQL query like this

```<code>String ipdetailsSql = "select sid, _zpsbd6 as ip_address, ssresp, reason,  " +
        "SUM(CASE WHEN botcode='r1' THEN 1 ELSE 0 END ) as icf_count, " +
        "SUM(CASE WHEN botcode='r2' THEN 1 ELSE 0 END ) as dc_count, " +
        "SUM(CASE WHEN botcode='r5' THEN 1 ELSE 0 END ) as badua_count, " +
        "COUNT(*) as hits, TUMBLE_START(ts, INTERVAL '1' MINUTE) AS fseen " +
        "from sourceTopic   " +
        "GROUP BY TUMBLE(ts, INTERVAL '1' MINUTE), sid, _zpsbd6, ssresp, reason";
</code>```

Based on the user input I want to change the  botcode='r1' to given input. Say botcode='r10' without restarting the job.
Is there a way to do this. I am on flink 1.7 using stream env. I tried config stream to read the inputs.
But stuck at how to change the query on fly.  Can anyone help me with this? Thanks in advance

答:
A stream SQL query isn't something that is executed once and is done, but rather is a declarative expression of a continuous computation. It's not possible to make arbitrary changes to that computation without starting a new job with a new query.

In simple cases, though, there are things you can do. You might consider whether it could work to join your sourcetopic with another stream that effectively provides some query parameters. Or you might find it affordable to compute all conceivably desired results and then select the actually desired results downstream.

Title: Dynamic SQL Query in Flink

Body:
I have a SQL query like this

String ipdetailsSql = "select sid, _zpsbd6 as ip_address, ssresp, reason,  " +
        "SUM(CASE WHEN botcode='r1' THEN 1 ELSE 0 END ) as icf_count, " +
        "SUM(CASE WHEN botcode='r2' THEN 1 ELSE 0 END ) as dc_count, " +
        "SUM(CASE WHEN botcode='r5' THEN 1 ELSE 0 END ) as badua_count, " +
        "COUNT(*) as hits, TUMBLE_START(ts, INTERVAL '1' MINUTE) AS fseen " +
        "from sourceTopic   " +
        "GROUP BY TUMBLE(ts, INTERVAL '1' MINUTE), sid, _zpsbd6, ssresp, reason";

Based on the user input I want to change the  botcode='r1' to given input. Say botcode='r10' without restarting the job.
Is there a way to do this. I am on flink 1.7 using stream env. I tried config stream to read the inputs.
But stuck at how to change the query on fly.  Can anyone help me with this? Thanks in advance