问:
How to know which is the exemplar for the cluster created by Affinity Propagation
I'm working on Image matching, I used Affinity Propagation in Python to create clusters of images. Since AP chooses an exemplar for each cluster, How do I know which is the image represented as an exemplar for that cluster ?</p>

答:
Affinity Propagation does not have a canonical way to "classify" new images. Clusters are not assigned by the affinity itself, but by "responsibility" and "availability". Roughly - but only approximately, and I think the sklearn implementation is incorrect there - objects are assigned to their "nearest" (highest affinity, although affinities are commonly derived from distances) cluster. But if the nearest has only low availability, and the second nearest is almost as close but with much higher availability and responsibility for this point, then points may be assigned not to the "nearest" exemplar. I'm not sure if some kind of transitivity (as in DBSCAN) can happen, too. If so, AP would be able to better handle clusters of varying diameter or shape, and be less similar to k-means. In my experiments, AP was pretty much similar to k-means, just much much slower... I don't have a simple test case for such a situation though, and it will IMHO usually only affect a few points.

Nevertheless, it appears to be a common approach to simply assign "new points" to the nearest exemplar. And if you read the sklearn documentation, it has a method that does exactly this. I don't think this is a good idea, because now fit then transform will not produce the same result as fit_transform... but this is likely never going to change because of "backwards compatibility".

sklearn also has an attribute that will give you the indexes of the exemplars chosen by AP, so you could easily do this yourself, too (which is necessary if you used a precomputed affinity matrix).


来源: stackexchange

问:
Show more, less list with + - buttons
I want to show 5 list items first with appending some ..., then when I click on + button, we display all the list, afterthat when I click on -, I undo the hidden items.

I need to display just the + first without the -, and once the list is displayed, the + become - to hide them again.

Here is my try:

https://jsfiddle.net/mpgt3znj/1/

Thanks

答:
Here's a solution to your problem, it's a little different from the good link that Lakshan offered.

It uses CSS to hide list items over a given value (using the pseudo class :nth-child(n+6), which matches the sixth and greater instance). The code below only does this when the list ul element has the .expanded or .collapsed class.

A short bit of jquery then toggles the .expanded and .collapsed classes for a ul list. A click on the toggle div then searches up the DOM tree to the nearest ul before flipping it's collapsed/expanded state.

Hope this helps

Solution

// Add click event to all list togggles
$(".list-toggle").click(function() {

  // Move up DOM tree to nearest list
  // Toggle collapsed and expanded classes
  $(this).closest("ul").toggleClass("collapsed").toggleClass("expanded");

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul.collapsed > li:nth-child(n+6) {
  display: none;
}

ul.collapsed > .list-toggle > span.collapse, ul.expanded > .list-toggle > span.expand {
  display: none;
}

.list-toggle {
  width: 0.5em;
  padding: 0.25em;
  line-height: 0.5em;
  text-align: center;
  background: green;
  color: white;
  border-radius: 50%;
  cursor: pointer;
}

ul.expanded > .list-toggle {
  background: red;
}</code>```

This list starts with the 'collapsed' class

Point one

Point two

Point three

Point four

Point five

Point six

Point seven

    +
    -

This list starts with the 'expanded' class

Point one

Point two

Point three

Point four

Point five

Point six

Point seven

    +
    -

```

ContentLicense: CC BY-SA 4.0

Title: Show more, less list with + - buttons

Body:
Here's a solution to your problem, it's a little different from the good link that Lakshan offered.

It uses CSS to hide list items over a given value (using the pseudo class :nth-child(n+6), which matches the sixth and greater instance). The code below only does this when the list ul element has the .expanded or .collapsed class.

A short bit of jquery then toggles the .expanded and .collapsed classes for a ul list. A click on the toggle div then searches up the DOM tree to the nearest ul before flipping it's collapsed/expanded state.

Hope this helps

Solution

// Add click event to all list togggles
$(".list-toggle").click(function() {

  // Move up DOM tree to nearest list
  // Toggle collapsed and expanded classes
  $(this).closest("ul").toggleClass("collapsed").toggleClass("expanded");

});

ul.collapsed > li:nth-child(n+6) {
  display: none;
}

ul.collapsed > .list-toggle > span.collapse, ul.expanded > .list-toggle > span.expand {
  display: none;
}

.list-toggle {
  width: 0.5em;
  padding: 0.25em;
  line-height: 0.5em;
  text-align: center;
  background: green;
  color: white;
  border-radius: 50%;
  cursor: pointer;
}

ul.expanded > .list-toggle {
  background: red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>This list starts with the 'collapsed' class</p>

<ul class="collapsed">

  <li>Point one</li>
  <li>Point two</li>
  <li>Point three</li>
  <li>Point four</li>
  <li>Point five</li>
  <li>Point six</li>
  <li>Point seven</li>

  <div class='list-toggle'>
    <span class="expand">+</span>
    <span class="collapse">-</span>
  </div>

</ul>

<p>This list starts with the 'expanded' class</p>

<ul class="expanded">

  <li>Point one</li>
  <li>Point two</li>
  <li>Point three</li>
  <li>Point four</li>
  <li>Point five</li>
  <li>Point six</li>
  <li>Point seven</li>

  <div class='list-toggle'>
    <span class="expand">+</span>
    <span class="collapse">-</span>
  </div>

</ul>


问:
C++ how to make a prototype of this kind of constructor?
I am honestly not sure how to google this even, and as my attempts have failed to do so, can you tell me how to write a prototype of constructor so that I can use it this way?

```<code>// MyClass.h
class Object;
class MyClass {
    Object a;
    Object b;
    std::string c;

    public:
    MyClass(int, int, std::string&); // I do not know how to declare this properly
};
// so that I can write this:
MyClass::MyClass(int a, int b, std::string& c = "uninstantialised") : a(a), b(b) {
    this->c = c;
}
// so that when I call the constructor like this:
Object a();
Object b();
MyClass mc(a, b);
// it doesn't produce an error when std::string argument is not specified.
</code>```

Thanks!

答:
Default arguments need to be specified in the declaration, not in the implementation. Furthermore, you should take the string by value, not by reference, and move it into the MyClass::c member:

```<code>public:
    MyClass(int a, int b, std::string c = "uninstantialised");

// ...

MyClass::MyClass(int a, int b, std::string c)
    : a(a), b(b), c(std::move(c))
{ }
</code>```

Taking by value and using std::move() is not required, but recommended as it can be more efficient since it avoids copying the string in some cases.

I recommend renaming private data members to something that avoids the same name being used for something else. Here, c is both the private member as well as the constructor parameter. You should use something different for the members. Like a_, b_ and c_ for example. Appending an underscore is a popular way to name private data members.

Body:
I am honestly not sure how to google this even, and as my attempts have failed to do so, can you tell me how to write a prototype of constructor so that I can use it this way?

// MyClass.h
class Object;
class MyClass {
    Object a;
    Object b;
    std::string c;

    public:
    MyClass(int, int, std::string&); // I do not know how to declare this properly
};
// so that I can write this:
MyClass::MyClass(int a, int b, std::string& c = "uninstantialised") : a(a), b(b) {
    this->c = c;
}
// so that when I call the constructor like this:
Object a();
Object b();
MyClass mc(a, b);
// it doesn't produce an error when std::string argument is not specified.

Thanks!

Body:
Default arguments need to be specified in the declaration, not in the implementation. Furthermore, you should take the string by value, not by reference, and move it into the MyClass::c member:

public:
    MyClass(int a, int b, std::string c = "uninstantialised");

// ...

MyClass::MyClass(int a, int b, std::string c)
    : a(a), b(b), c(std::move(c))
{ }

Taking by value and using std::move() is not required, but recommended as it can be more efficient since it avoids copying the string in some cases.

I recommend renaming private data members to something that avoids the same name being used for something else. Here, c is both the private member as well as the constructor parameter. You should use something different for the members. Like a_, b_ and c_ for example. Appending an underscore is a popular way to name private data members.


问:
How to save the items in textboxes for an single selected index in list box in xml and load those data? c#
I'm relatively new to c#,I had a requirement that a set 5 text box's data should get saved for an single item in the list box.the item in list box will be added at the run time.for each item in the list box the set of 5 data should get saved.and again if we clicked an item in list box the data should get displayed.this is requirement. here i had coded which not satisfactory.so please help me that in which i can simplify the program.the way which i had conveyed may be little bit confusing please apologies for that.
**Ultimate aim : for an selected item in the list box the data should get saved in xml and if we clicked the data should load to those textbox  **

```<code> namespace WindowsFormsApplication20
 public partial class Form1 : Form
{
    TextBox[] tb = new TextBox[5];
    TextBox[] t = new TextBox[5];
    TextBox[] t1 = new TextBox[5];
    int[] tblist = new int[5];

    public struct Tblist
    {
        string text;

    }
    public Form1()
    {
        InitializeComponent();
        tb[0] = new TextBox();
        tb[1] = new TextBox();
        tb[2] = new TextBox();
        tb[3] = new TextBox();
        tb[4] = new TextBox();
        t[0] = new TextBox();
        t[1] = new TextBox();
        t[2] = new TextBox();
        t[3] = new TextBox();
        t[4] = new TextBox();
        t1[0] = new TextBox();
        t1[1] = new TextBox();
        t1[2] = new TextBox();
        t1[3] = new TextBox();
        t1[4] = new TextBox();

    }

 here for every new text box I need to define an new object how can i simplify this?
</code>```

here is what when button has clicked:it save every data in the textbox for an selected index in the list box

```<code>    private void button1_Click(object sender, EventArgs e)
    {
        if (listBox1.SelectedIndex == 0)
        {
            tb[0].Text = textBox1.Text;
            tb[1].Text = textBox2.Text;
            tb[2].Text = textBox3.Text;
            tb[3].Text = textBox4.Text;
            tb[4].Text = textBox5.Text;
        }
        if (listBox1.SelectedIndex == 1)
        {
            t[0].Text = textBox1.Text;
            t[1].Text = textBox2.Text;
            t[2].Text = textBox3.Text;
            t[3].Text = textBox4.Text;
            t[4].Text = textBox5.Text;
        }
        if (listBox1.SelectedIndex == 2)
        {
            t1[0].Text = textBox1.Text;
            t1[1].Text = textBox2.Text;
            t1[2].Text = textBox3.Text;
            t1[3].Text = textBox4.Text;
            t1[4].Text = textBox5.Text;
        }
    }
</code>```

how can we implement a foreach statement ,so that everytime we click and save the entered the data.

```<code>    private void listBox1_Click(object sender, EventArgs e)
    {
        if (listBox1.SelectedIndex == 0)
        {
           /* textBox1.Text = textBox2.Text = textBox3.Text = textBox4.Text = textBox5.Text = " ";*/
            /*TextBox[] tb = new TextBox[5];*/
             textBox1.Text = tb[0].Text;
            textBox2.Text = tb[1].Text;
            textBox3.Text = tb[2].Text;
            textBox4.Text = tb[3].Text;
            textBox5.Text = tb[4].Text;
        }

       if (listBox1.SelectedIndex == 1)
        {
           /* textBox1.Text = textBox2.Text = textBox3.Text= textBox4.Text = textBox5.Text = " ";*/
          /*TextBox[] t = new TextBox[5];*/
            textBox1.Text = t[0].Text;
            textBox2.Text = t[1].Text;
            textBox3.Text = t[2].Text;
            textBox4.Text = t[3].Text;
            textBox5.Text = t[4].Text;
        }
        if (listBox1.SelectedIndex == 2)
        {
            /* textBox1.Text = textBox2.Text = textBox3.Text= textBox4.Text = textBox5.Text = " ";*/
            /*TextBox[] t = new TextBox[5];*/
            textBox1.Text = t1[0].Text;
            textBox2.Text = t1[1].Text;
            textBox3.Text = t1[2].Text;
            textBox4.Text = t1[3].Text;
            textBox5.Text = t1[4].Text;
        }
    }
</code>```

答:
First, give normal names to your variables. What do these tb, t, t1 mean?

Suppose some information about people is stored in these arrays. Then let's call them firstnames, lastnames, nicknames. Looks a lot better, huh?

for every new text box I need to define an new object how can i simplify this?

Use loops.

```<code>const int size = 5; // form field

TextBox[] firstnames = new TextBox[size];
TextBox[] lastnames = new TextBox[size];
TextBox[] nicknames = new TextBox[size];

for (int i = 0; i < size; i++)
{
    firstnames[i] = new TextBox();
    lastnames[i] = new TextBox();
    nicknames[i] = new TextBox();
}
</code>```

As far as I understand, you use arrays of textboxes just to store text. This is absolutely wrong.

Just create arrays of strings.

```<code>string[] firstnames = new string[size];
string[] lastnames = new string[size];
string[] nicknames = new string[size];
</code>```

It is not necessary to initialize them with initial values.

For convenient work with text boxes that are placed on the form, place them in an array.

```<code>TextBox[] textBoxes; // form field

textBoxes = this.Controls.OfType<TextBox>().ToArray();
</code>```

Or directly set them:

```<code>textBoxes = new TextBox[] { textBox1, textBox2, textBox3, textBox4, textBox5 };
</code>```

Now you can work with this array in a loop:

```<code>private void buttonSave_Click(object sender, EventArgs e)
{
    if (listBoxPeople.SelectedIndex == 0)
    {
        for (int i = 0; i < size; i++)
        {
            firstnames[i] = textBoxes[i].Text;
        }
    }
    //...
</code>```

Note the friendly names listBoxPeople, buttonSave (of course, give them proper names).

Let's save the data using serialization.

```<code>XmlSerializer xmlSerializer = new XmlSerializer(typeof(string[]));

using (var stream = new FileStream("data.xml", FileMode.Create))
{
    xmlSerializer.Serialize(stream, firstnames);
}
</code>```

Very simple and concise.

Data loading:

```<code>using (var stream = new FileStream("data.xml", FileMode.Open))
{
    firstnames = (string[])xmlSerializer.Deserialize(stream);
}
</code>```

A link to the documentation: XmlSerializer

Body:
I'm relatively new to c#,I had a requirement that a set 5 text box's data should get saved for an single item in the list box.the item in list box will be added at the run time.for each item in the list box the set of 5 data should get saved.and again if we clicked an item in list box the data should get displayed.this is requirement. here i had coded which not satisfactory.so please help me that in which i can simplify the program.the way which i had conveyed may be little bit confusing please apologies for that.
**Ultimate aim : for an selected item in the list box the data should get saved in xml and if we clicked the data should load to those textbox  **

 namespace WindowsFormsApplication20
 public partial class Form1 : Form
{
    TextBox[] tb = new TextBox[5];
    TextBox[] t = new TextBox[5];
    TextBox[] t1 = new TextBox[5];
    int[] tblist = new int[5];

    public struct Tblist
    {
        string text;

    }
    public Form1()
    {
        InitializeComponent();
        tb[0] = new TextBox();
        tb[1] = new TextBox();
        tb[2] = new TextBox();
        tb[3] = new TextBox();
        tb[4] = new TextBox();
        t[0] = new TextBox();
        t[1] = new TextBox();
        t[2] = new TextBox();
        t[3] = new TextBox();
        t[4] = new TextBox();
        t1[0] = new TextBox();
        t1[1] = new TextBox();
        t1[2] = new TextBox();
        t1[3] = new TextBox();
        t1[4] = new TextBox();

    }

 here for every new text box I need to define an new object how can i simplify this?

here is what when button has clicked:it save every data in the textbox for an selected index in the list box

    private void button1_Click(object sender, EventArgs e)
    {
        if (listBox1.SelectedIndex == 0)
        {
            tb[0].Text = textBox1.Text;
            tb[1].Text = textBox2.Text;
            tb[2].Text = textBox3.Text;
            tb[3].Text = textBox4.Text;
            tb[4].Text = textBox5.Text;
        }
        if (listBox1.SelectedIndex == 1)
        {
            t[0].Text = textBox1.Text;
            t[1].Text = textBox2.Text;
            t[2].Text = textBox3.Text;
            t[3].Text = textBox4.Text;
            t[4].Text = textBox5.Text;
        }
        if (listBox1.SelectedIndex == 2)
        {
            t1[0].Text = textBox1.Text;
            t1[1].Text = textBox2.Text;
            t1[2].Text = textBox3.Text;
            t1[3].Text = textBox4.Text;
            t1[4].Text = textBox5.Text;
        }
    }

how can we implement a foreach statement ,so that everytime we click and save the entered the data.

    private void listBox1_Click(object sender, EventArgs e)
    {
        if (listBox1.SelectedIndex == 0)
        {
           /* textBox1.Text = textBox2.Text = textBox3.Text = textBox4.Text = textBox5.Text = " ";*/
            /*TextBox[] tb = new TextBox[5];*/
             textBox1.Text = tb[0].Text;
            textBox2.Text = tb[1].Text;
            textBox3.Text = tb[2].Text;
            textBox4.Text = tb[3].Text;
            textBox5.Text = tb[4].Text;
        }

       if (listBox1.SelectedIndex == 1)
        {
           /* textBox1.Text = textBox2.Text = textBox3.Text= textBox4.Text = textBox5.Text = " ";*/
          /*TextBox[] t = new TextBox[5];*/
            textBox1.Text = t[0].Text;
            textBox2.Text = t[1].Text;
            textBox3.Text = t[2].Text;
            textBox4.Text = t[3].Text;
            textBox5.Text = t[4].Text;
        }
        if (listBox1.SelectedIndex == 2)
        {
            /* textBox1.Text = textBox2.Text = textBox3.Text= textBox4.Text = textBox5.Text = " ";*/
            /*TextBox[] t = new TextBox[5];*/
            textBox1.Text = t1[0].Text;
            textBox2.Text = t1[1].Text;
            textBox3.Text = t1[2].Text;
            textBox4.Text = t1[3].Text;
            textBox5.Text = t1[4].Text;
        }
    }

Body:
First, give normal names to your variables. What do these tb, t, t1 mean?

Suppose some information about people is stored in these arrays. Then let's call them firstnames, lastnames, nicknames. Looks a lot better, huh?

for every new text box I need to define an new object how can i simplify this?

Use loops.

const int size = 5; // form field

TextBox[] firstnames = new TextBox[size];
TextBox[] lastnames = new TextBox[size];
TextBox[] nicknames = new TextBox[size];

for (int i = 0; i < size; i++)
{
    firstnames[i] = new TextBox();
    lastnames[i] = new TextBox();
    nicknames[i] = new TextBox();
}

As far as I understand, you use arrays of textboxes just to store text. This is absolutely wrong.

Just create arrays of strings.

string[] firstnames = new string[size];
string[] lastnames = new string[size];
string[] nicknames = new string[size];

It is not necessary to initialize them with initial values.

For convenient work with text boxes that are placed on the form, place them in an array.

TextBox[] textBoxes; // form field

textBoxes = this.Controls.OfType<TextBox>().ToArray();

Or directly set them:

textBoxes = new TextBox[] { textBox1, textBox2, textBox3, textBox4, textBox5 };

Now you can work with this array in a loop:

private void buttonSave_Click(object sender, EventArgs e)
{
    if (listBoxPeople.SelectedIndex == 0)
    {
        for (int i = 0; i < size; i++)
        {
            firstnames[i] = textBoxes[i].Text;
        }
    }
    //...

Note the friendly names listBoxPeople, buttonSave (of course, give them proper names).

Let's save the data using serialization.

XmlSerializer xmlSerializer = new XmlSerializer(typeof(string[]));

using (var stream = new FileStream("data.xml", FileMode.Create))
{
    xmlSerializer.Serialize(stream, firstnames);
}

Very simple and concise.

Data loading:

using (var stream = new FileStream("data.xml", FileMode.Open))
{
    firstnames = (string[])xmlSerializer.Deserialize(stream);
}

A link to the documentation: XmlSerializer


问:
Reducing the number of IOPS - Performance improvement question

so I have an application that is processing a large text document which is composed of many logical documents. Say for eg it has 200,000 logical documents. Right now I read one logical document and do the transformation and write logical document out. This works well because nothing is stored in memory so the workflow ends up finishing fast but the number of IOPS end up being high! Is there any recommendation on how I can reduce the number of IOPS ?

答:
If this is a single pass through the document, increase your read buffer size (i.e. 2 reads with a buffer size of 1024 becomes 1 read with a buffer size of 2048, which means less overhead).

If you want more detailed suggestions, you'll need to provide more details in your question.

ContentLicense: CC BY-SA 3.0


问:
Set dropdown button width to same as dropdown item width
I have a dropdown div and its button width is different from that of its dropdown items. I want the button and the dropdown items to have the same width.

```<code><div class="dropdown col">
    <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Choose a form</button>
    <ul class="dropdown-menu col-xs-12">
        <a class="dropdown-item" href="#">word</a>
        <div class="dropdown-divider"></div>
        <a class="dropdown-item" href="#">word</a>
        <div class="dropdown-divider"></div>
        <a class="dropdown-item" href="#">Very long word</a>
    </ul>
</div>
</code>```

The width of Very long word item is the same as that of word items, only the button that has a different width.

答:
One way to do that would be to wrap the button and the dropdown menu to a new div and set your desired width in it (I've set a width of 200px for the example), then just making its children (button + dropdown menu) inherit their parent's div width (width: inherit !important;) like so :

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

        <button style="width: inherit !important;" class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Choose a form</button>

            word

            word

            Very long word

```

Body:
I have a dropdown div and its button width is different from that of its dropdown items. I want the button and the dropdown items to have the same width.

    <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Choose a form</button>

        word

        word

        Very long word

The width of Very long word item is the same as that of word items, only the button that has a different width.

Body:
One way to do that would be to wrap the button and the dropdown menu to a new div and set your desired width in it (I've set a width of 200px for the example), then just making its children (button + dropdown menu) inherit their parent's div width (width: inherit !important;) like so :

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<div class="dropdown col">
    <div style="width: 200px;">
        <button style="width: inherit !important;" class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Choose a form</button>
        <ul style="width: inherit !important;" class="dropdown-menu dropdown-menu-center">
            <a class="dropdown-item" href="#">word</a>
            <div class="dropdown-divider"></div>
            <a class="dropdown-item" href="#">word</a>
            <div class="dropdown-divider"></div>
            <a class="dropdown-item" href="#">Very long word</a>
        </ul>
    </div>
</div>


问:
React transition group animate between components (fade in component in place of another)
I'm using react-transition-group for animations in my app.

I have a Popup where I want to animate between two contents. I want to make the first content fade out and the second content appear in its place.

So far I have a problem where while animating the second content appears below the first one while the first one is still visible. (See the screenshot)

Any help will be much appreciated.

My code

```<code>const [stage, setStage] = useState('register');

  function changeStage(stageVal) {
    setStage(stageVal);
  }
...
<Popup togglePopupWindow={togglePopupWindow} setStage={setStage}>
        <CSSTransitionGroup
          transitionName="example"
          transitionEnterTimeout={500}
          transitionLeaveTimeout={300}
        >
          {stage === 'register' && (
          <>
            <Form>
              <h2>Register</h2>
              <Input type="text" placeholder="Login" />
              <Input type="email" placeholder="Email" />
              <Input type="password" placeholder="Password" />
              <Button text="Register" />
            </Form>
            <p>
              <span>Already registered?</span>
              <Button className="popup__login" text="Login" onClick={() => changeStage('login')} />
            </p>
        </>
          )
      }
          {stage === 'login' && (
          <Form>
            <h2>Login</h2>
            <Input type="text" placeholder="Login" />
            <Input type="password" placeholder="Password" />
            <Button text="Register" />
          </Form>
          )
   }
        </CSSTransitionGroup>
      </Popup>
</code>```

Styles

```<code>.example-enter {
    opacity: 0;
    }

.example-enter.example-enter-active {
   opacity: 1;
   transition: opacity 500ms ease-in-out;
}

.example-leave {
   opacity: 1;
}

.example-leave.example-leave-active {
   opacity: 0;
   transition: opacity 300ms ease-in-out;
}
</code>```

答:
Try taking out .example-enter and .example-leave on each of the ...-active CSS properties.. You set .example-enter to 0 opacity and then replace the .example-enter to 1.. meaning you're setting 1 on .example-enter with your .example-enter-active after the initial declaration... so the 0 is overwritten.

```<code>.example-enter {
    opacity: 0;
    }
.example-enter-active {
   opacity: 1;
   transition: opacity 500ms ease-in-out;
}

.example-leave {
   opacity: 1;
}

.example-leave-active {
   opacity: 0;
   transition:
}
</code>```

Body:
I'm using react-transition-group for animations in my app.

I have a Popup where I want to animate between two contents. I want to make the first content fade out and the second content appear in its place.

So far I have a problem where while animating the second content appears below the first one while the first one is still visible. (See the screenshot)

Any help will be much appreciated.

My code

const [stage, setStage] = useState('register');

  function changeStage(stageVal) {
    setStage(stageVal);
  }
...
<Popup togglePopupWindow={togglePopupWindow} setStage={setStage}>
        <CSSTransitionGroup
          transitionName="example"
          transitionEnterTimeout={500}
          transitionLeaveTimeout={300}
        >
          {stage === 'register' && (
          <>
            <Form>

Register

              <Input type="text" placeholder="Login" />
              <Input type="email" placeholder="Email" />
              <Input type="password" placeholder="Password" />
              <Button text="Register" />
            </Form>

              Already registered?
              <Button className="popup__login" text="Login" onClick={() => changeStage('login')} />

        </>
          )
      }
          {stage === 'login' && (
          <Form>

Login

            <Input type="text" placeholder="Login" />
            <Input type="password" placeholder="Password" />
            <Button text="Register" />
          </Form>
          )
   }
        </CSSTransitionGroup>
      </Popup>

Styles

.example-enter {
    opacity: 0;
    }

.example-enter.example-enter-active {
   opacity: 1;
   transition: opacity 500ms ease-in-out;
}

.example-leave {
   opacity: 1;
}

.example-leave.example-leave-active {
   opacity: 0;
   transition: opacity 300ms ease-in-out;
}

Body:
Try taking out .example-enter and .example-leave on each of the ...-active CSS properties.. You set .example-enter to 0 opacity and then replace the .example-enter to 1.. meaning you're setting 1 on .example-enter with your .example-enter-active after the initial declaration... so the 0 is overwritten.

.example-enter {
    opacity: 0;
    }
.example-enter-active {
   opacity: 1;
   transition: opacity 500ms ease-in-out;
}

.example-leave {
   opacity: 1;
}

.example-leave-active {
   opacity: 0;
   transition:
}


问:
How to achieve Flutter Checkbox Stepper?
I am trying to achieve the following layout

I tried using Stepper but it didn't really solved my issue so I tried using vanilla dart code itself

```<code>Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Checkbox(value: true, onChanged: (value) {}),
              Text("Complaint Received"),
            ],
          ),
          Padding(
            padding: const EdgeInsets.only(
              left: 20,
            ),
            child: Container(
              padding: const EdgeInsets.all(0),
              width: 2,
              height: 80,
              color: Colors.black,
            ),
          ),
          Row(
            children: <Widget>[
              Checkbox(value: true, onChanged: (value) {}),
              Text("Complaint Received"),
            ],
          ),
          Container(
            width: 2,
            height: 10,
            color: Colors.black,
          ),
          Row(
            children: <Widget>[
              Checkbox(value: true, onChanged: (value) {}),
              Text("Complaint Received"),
            ],
          ),
          Container(
            width: 2,
            height: 10,
            color: Colors.black,
          ),
          Row(
            children: <Widget>[
              Checkbox(value: true, onChanged: (value) {}),
              Text("Complaint Received"),
            ],
          ),
          Container(
            width: 2,
            height: 10,
            color: Colors.black,
          ),
        ],
      ),
</code>```

Following is the ui which I achieved

I don't understand why there is padding between the first two row and the container

答:
In Flutter, Checkboxes are not pure widgets like the StatelessWidget that we are used to.

Checkbox draws its bounds, a box with rounded edges, and the 'check' mark itself through RenderObject's paint method, sort of like HTML5 Canvas (if you are familiar).

This fact makes it hard to customize Flutter checkboxes, even changing such trivial stuff like the padding around it.

My solution does not solve your problem in the way you tried to, but it does provide a great view just like the one you wanted to achieve.

final double barsHeight = 40.0;
final double barsWidth = 3.0;
final Color inactiveBarColor = Colors.grey;
final Color activeBarColor = Colors.blue;

Map<String, bool> steps = {
  "Complaint Received": true,
  "Engineer Assigned": true,
  "Engineer On the way": false,
  "Complaint Done": false,
};

@override
Widget build(BuildContext context) {
  double rowPadding = (barsHeight - kRadialReactionRadius) / 2;
  double _barHeight = barsHeight;
  if (rowPadding < 0) {
    rowPadding = 0;
    _barHeight = kRadialReactionRadius;
  }
  return Padding(
    padding: EdgeInsets.symmetric(horizontal: 8, vertical: 16),
    child: Stack(fit: StackFit.loose, children: <Widget>[

      Positioned(
        left: kRadialReactionRadius - barsWidth / 2,
        top: kRadialReactionRadius + rowPadding,
        bottom: kRadialReactionRadius + rowPadding,
        width: barsWidth,
        child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: List.generate(steps.length - 1, (i) =>
          Container(
            margin: EdgeInsets.symmetric(vertical: kRadialReactionRadius / 2 - 2),
            height: _barHeight + 4,
            color: steps.values.elementAt(i) && steps.values.elementAt(i + 1) ? activeBarColor : inactiveBarColor,
          )
        ))
      ),
      Theme(
        data: Theme.of(context).copyWith(disabledColor: inactiveBarColor, unselectedWidgetColor: inactiveBarColor),
        child: Column(mainAxisSize: MainAxisSize.min, children: steps.keys.map((key) =>
          Padding(
            padding: EdgeInsets.symmetric(vertical: rowPadding),
            child: Row(crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[
              Checkbox(
                value: steps[key],
                onChanged: steps[key] ? (_) {} : null,
                activeColor: activeBarColor,
                materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
              ),
              Text(key),
            ])
          )
        ).toList())
      )

    ]),
  );
}
```

<p>How it works, in short:</p>

<ul>
<li><code>Checkbox</code> uses <code>kRadialReactionRadius</code> constant for its size and padding. That's how we know its exact size and now we can draw our bars in-between each checkbox row.</li>
<li>Vertical bars are drawn underneath the <code>Column</code> with Checkboxes using <code>Stack</code>.</li>
<li>Checkboxes default border color is overridden by <code>Theme</code> widget.</li>
</ul>

<p>To change checkbox state - simply modify values in <code>steps</code> variable. e.g.</p>

<pre class="lang-dart prettyprint-override"><code>setState(() {
  steps[steps.keys.elementAt(/*checkbox index*/)] = true;
});
</code>```

Final result:

Let me know if this helped.

Body:
I am trying to achieve the following layout

I tried using Stepper but it didn't really solved my issue so I tried using vanilla dart code itself

Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Checkbox(value: true, onChanged: (value) {}),
              Text("Complaint Received"),
            ],
          ),
          Padding(
            padding: const EdgeInsets.only(
              left: 20,
            ),
            child: Container(
              padding: const EdgeInsets.all(0),
              width: 2,
              height: 80,
              color: Colors.black,
            ),
          ),
          Row(
            children: <Widget>[
              Checkbox(value: true, onChanged: (value) {}),
              Text("Complaint Received"),
            ],
          ),
          Container(
            width: 2,
            height: 10,
            color: Colors.black,
          ),
          Row(
            children: <Widget>[
              Checkbox(value: true, onChanged: (value) {}),
              Text("Complaint Received"),
            ],
          ),
          Container(
            width: 2,
            height: 10,
            color: Colors.black,
          ),
          Row(
            children: <Widget>[
              Checkbox(value: true, onChanged: (value) {}),
              Text("Complaint Received"),
            ],
          ),
          Container(
            width: 2,
            height: 10,
            color: Colors.black,
          ),
        ],
      ),

Following is the ui which I achieved

I don't understand why there is padding between the first two row and the container

Body:
In Flutter, Checkboxes are not pure widgets like the StatelessWidget that we are used to.

Checkbox draws its bounds, a box with rounded edges, and the 'check' mark itself through RenderObject's paint method, sort of like HTML5 Canvas (if you are familiar).

This fact makes it hard to customize Flutter checkboxes, even changing such trivial stuff like the padding around it.

My solution does not solve your problem in the way you tried to, but it does provide a great view just like the one you wanted to achieve.

final double barsHeight = 40.0;
final double barsWidth = 3.0;
final Color inactiveBarColor = Colors.grey;
final Color activeBarColor = Colors.blue;

Map<String, bool> steps = {
  "Complaint Received": true,
  "Engineer Assigned": true,
  "Engineer On the way": false,
  "Complaint Done": false,
};

@override
Widget build(BuildContext context) {
  double rowPadding = (barsHeight - kRadialReactionRadius) / 2;
  double _barHeight = barsHeight;
  if (rowPadding < 0) {
    rowPadding = 0;
    _barHeight = kRadialReactionRadius;
  }
  return Padding(
    padding: EdgeInsets.symmetric(horizontal: 8, vertical: 16),
    child: Stack(fit: StackFit.loose, children: <Widget>[

      Positioned(
        left: kRadialReactionRadius - barsWidth / 2,
        top: kRadialReactionRadius + rowPadding,
        bottom: kRadialReactionRadius + rowPadding,
        width: barsWidth,
        child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: List.generate(steps.length - 1, (i) =>
          Container(
            margin: EdgeInsets.symmetric(vertical: kRadialReactionRadius / 2 - 2),
            height: _barHeight + 4,
            color: steps.values.elementAt(i) && steps.values.elementAt(i + 1) ? activeBarColor : inactiveBarColor,
          )
        ))
      ),
      Theme(
        data: Theme.of(context).copyWith(disabledColor: inactiveBarColor, unselectedWidgetColor: inactiveBarColor),
        child: Column(mainAxisSize: MainAxisSize.min, children: steps.keys.map((key) =>
          Padding(
            padding: EdgeInsets.symmetric(vertical: rowPadding),
            child: Row(crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[
              Checkbox(
                value: steps[key],
                onChanged: steps[key] ? (_) {} : null,
                activeColor: activeBarColor,
                materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
              ),
              Text(key),
            ])
          )
        ).toList())
      )

    ]),
  );
}

How it works, in short:

Checkbox uses kRadialReactionRadius constant for its size and padding. That's how we know its exact size and now we can draw our bars in-between each checkbox row.

Vertical bars are drawn underneath the Column with Checkboxes using Stack.

Checkboxes default border color is overridden by Theme widget.

To change checkbox state - simply modify values in steps variable. e.g.

setState(() {
  steps[steps.keys.elementAt(/*checkbox index*/)] = true;
});

Final result:

Let me know if this helped.


问:
What is the correct way to layer if statements in order to get the desired results
[enter image description here]

IMAGE 2 (results)
enter image description here

2I'm working with data manipulation in csvs using python + pandas.
Example #s

PL       T

0.569999695

0.960002899

1.729999542

1.590000153

1.450000763

1.530002594
1.530002594

1.770000458

0.890003204

0.490001678

1.11000061

1.340000153

2.390003204
2.390003204

2.470001221

2.760002136

3.200000763

2.880001068

2.479999542
2.479999542

3.100002289

1.269996643

1.269996643

1.590000153

2.13999939

I have used if statements in the past however this one is very specific and I can't seem to get the syntax working correctly.

If you look at the code I want column 'T' to be calculated like this
there are a few numbers filled into the row already from previous code and the rest are blank.

The code working will hypothetically run through the rows in column t.

The first rows are mostly blank so it will skip those until it hits a row that has a number in it. if(df['T'].iat[x-1] != "")

once it hits the row with a number in it the script will check the logical (if the cell in the row next to it is greater than the cell above it)(if

```<code>df['PL'].iat[x] > df['PL'].iat[x-1]
</code>```

if that logical is true it will print the cell from next to it over into the column. df['T'].iat[x] = df['PL'].iat[x]
and if the logical is false then the cell stays blank

I think the real issue is how it iterates after that step. Right now I think its going back and just checking the last if statement again but I want it to iterate through all of them for each row.

It should read the column above to see if it is blank or filled in and then go through the if statements again only printing a number when all are met.

I have tried multiple arrangements as well as using and/or statements. I just can't seem to get it to print the right results.

```<code>

import pandas as pd
import csv

df=pd.read_csv(filename)

len1 = len(df)

for x in range(len3):

       if (df['T'].iat[x-1] != ""):

                if(df['T'].iat[x] == ""):

                    if (df['PL'].iat[x] > df['PL'].iat[x-1]):

                        df['T'].iat[x] = df['PL'].iat[x]
</code>```

The code displays no error messages however it is not printing the right results. Please let me know if I can explain it any better or if anyone has any ideas. Thanks!

答:
Your first if statement doesn't skip rows until it finds an empty cell - your second if statement does that. Your first if statement (I think) will cause this to fail when you check the very first row.

Try removing the first if. If that doesn't work, try removing the other ifs too, and see if you are able to set any values at all with df['T'].iat[x] = df['PL'].iat[x] - it may be that pandas has a separate method to set values than to get them.

Body:
[enter image description here]

IMAGE 2 (results)
enter image description here

2I'm working with data manipulation in csvs using python + pandas.
Example #s

PL       T

0.569999695

0.960002899

1.729999542

1.590000153

1.450000763

1.530002594
1.530002594

1.770000458

0.890003204

0.490001678

1.11000061

1.340000153

2.390003204
2.390003204

2.470001221

2.760002136

3.200000763

2.880001068

2.479999542
2.479999542

3.100002289

1.269996643

1.269996643

1.590000153

2.13999939

I have used if statements in the past however this one is very specific and I can't seem to get the syntax working correctly.

If you look at the code I want column 'T' to be calculated like this
there are a few numbers filled into the row already from previous code and the rest are blank.

The code working will hypothetically run through the rows in column t.

The first rows are mostly blank so it will skip those until it hits a row that has a number in it. if(df['T'].iat[x-1] != "")

once it hits the row with a number in it the script will check the logical (if the cell in the row next to it is greater than the cell above it)(if

df['PL'].iat[x] > df['PL'].iat[x-1]

if that logical is true it will print the cell from next to it over into the column. df['T'].iat[x] = df['PL'].iat[x]
and if the logical is false then the cell stays blank

I think the real issue is how it iterates after that step. Right now I think its going back and just checking the last if statement again but I want it to iterate through all of them for each row.

It should read the column above to see if it is blank or filled in and then go through the if statements again only printing a number when all are met.

I have tried multiple arrangements as well as using and/or statements. I just can't seem to get it to print the right results.

import pandas as pd
import csv

df=pd.read_csv(filename)

len1 = len(df)

for x in range(len3):

       if (df['T'].iat[x-1] != ""):

                if(df['T'].iat[x] == ""):

                    if (df['PL'].iat[x] > df['PL'].iat[x-1]):

                        df['T'].iat[x] = df['PL'].iat[x]

The code displays no error messages however it is not printing the right results. Please let me know if I can explain it any better or if anyone has any ideas. Thanks!


问:
Override index array from API result
Having a problem overriding the index of array in redux state :/

I am receiving a data from an endpoint and the results are:

e.g.

```<code>data:
 [{
    0: {id: 123, name: test1 },
    1: {id: 456, name: test2 },
    3: {id: 789, name: test3 },
 }]
</code>```

But I want to change the index of the array based on the result object.

```<code>data:
 [{
    123: {id: 123, name: test1 },
    456: {id: 456, name: test2 },
    789: {id: 789, name: test3 },
 }]
</code>```

Then save these to reducer.

This is the exact data that returned from an endpoint.

I have tried

```<code>let data = action.payload.data.map(item => {
    return {
        [item.id]: item
    }
})
</code>```

and got the result of

```<code>[
0: {123: {id: 123, name: 'test1'}},
1: {456: {id: 456, name: 'test2'}}
]
</code>```

Any help is much appreciated!

答:
You can use map and Object.entries and Object.fromEntries

let data = [{0: { id: 123,name: 'test1'},1: {id: 456,name: 'test2'}, 3: {id: 789,name: 'test3'},}]

let op = data.map(val => Object.fromEntries(Object.entries(val).map(([key, value]) => [value.id, value])))

console.log(op)```
</div>
</div>
</p>

<p>Or you can use <code>map</code> and <code>Object.values</code> and <code>reduce</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let data = [{0: { id: 123,name: 'test1'},1: {id: 456,name: 'test2'}, 3: {id: 789,name: 'test3'},}]

let op = data.map(val=> {
  let values = Object.values(val)
  let obj = values.reduce((op, inp) => {
    op[inp.id] = inp
    return op
  },{})
  return obj
})

console.log(op)</code>```

Title: Override index array from API result

Body:
Having a problem overriding the index of array in redux state :/

I am receiving a data from an endpoint and the results are:

e.g.

data:
 [{
    0: {id: 123, name: test1 },
    1: {id: 456, name: test2 },
    3: {id: 789, name: test3 },
 }]

But I want to change the index of the array based on the result object.

data:
 [{
    123: {id: 123, name: test1 },
    456: {id: 456, name: test2 },
    789: {id: 789, name: test3 },
 }]

Then save these to reducer.

This is the exact data that returned from an endpoint.

I have tried

let data = action.payload.data.map(item => {
    return {
        [item.id]: item
    }
})

and got the result of

[
0: {123: {id: 123, name: 'test1'}},
1: {456: {id: 456, name: 'test2'}}
]

Any help is much appreciated!

Body:
You can use map and Object.entries and Object.fromEntries

let data = [{0: { id: 123,name: 'test1'},1: {id: 456,name: 'test2'}, 3: {id: 789,name: 'test3'},}]

let op = data.map(val => Object.fromEntries(Object.entries(val).map(([key, value]) => [value.id, value])))

console.log(op)

Or you can use map and Object.values and reduce

let data = [{0: { id: 123,name: 'test1'},1: {id: 456,name: 'test2'}, 3: {id: 789,name: 'test3'},}]

let op = data.map(val=> {
  let values = Object.values(val)
  let obj = values.reduce((op, inp) => {
    op[inp.id] = inp
    return op
  },{})
  return obj
})

console.log(op)


问:
How to print the actual MAVEN_OPTS that are being used?
Is there a way to get maven to output the value of environment and maven variables during a build? This would be very useful for debugging things when they're going wrong.</p>

答:
Add this plugin under plugins section in pom.xml and use mvn validate :

```<code><plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-antrun-plugin</artifactId>
  <version>1.1</version>
  <executions>
    <execution>
      <phase>validate</phase>
      <goals>
        <goal>run</goal>
      </goals>
      <configuration>
        <tasks>
          <echo>Displaying value of system variables</echo>
          <echo> ${env.YOUR_ENVIRONMENT_VARIABLE_NAME}</echo>
        </tasks>
      </configuration>
    </execution>
  </executions>
</plugin>
</code>```

This will print your env variable value.

Body:
Add this plugin under plugins section in pom.xml and use mvn validate :

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-antrun-plugin</artifactId>
  <version>1.1</version>
  <executions>
    <execution>
      <phase>validate</phase>
      <goals>
        <goal>run</goal>
      </goals>
      <configuration>
        <tasks>
          <echo>Displaying value of system variables</echo>
          <echo> ${env.YOUR_ENVIRONMENT_VARIABLE_NAME}</echo>
        </tasks>
      </configuration>
    </execution>
  </executions>
</plugin>

This will print your env variable value.


问:
How to set default redirect with different session on laravel 5.8
I have a manage login with roles . its user ,admin ,superadmin . i create this all roles in middleware , and at this code in LoginController :

```<code>protected function authenticated(Request $request, $user)
{
    if ( $user->isAdmin() ) {
        return redirect()->route('admin_dashboard');
    }
    elseif ($user->isSuperadmin()) {
        return redirect()->route('superadmin_dashboard');
    }
    else{
        return redirect()->route('dashboard');
    }

}
</code>```

its work normaly , if i login admin its redirect to admin_dashboard , but  this problem is , if i close this browser and run localhost:8000 , its redirect to home not admin_dashboard .

my question , how i can set if login as admin and close the browser and run localhost:8000 its going to admin_dashboard ?

答:
I think you should create multiple guards according to roles name like 'admin','superamdin'.

Here is link for create multiauth in laravel .
https://www.youtube.com/watch?v=iKRLrJXNN4M&t=1s

After your create multiple guards you can just use middleware to redirect authenticated user.

```<code>public function handle($request, Closure $next, $guard = null)
{
    switch ($guard) {
        case 'admin':
            if (Auth::guard('admin')->check()) {
                return redirect()->route('admin.dashboard');
            }
            break;

        case 'superadmin':
            if (Auth::guard('superadmin')->check()) {
                return redirect()->route('superadmin.dashboard');
            }
            break;

        default:
            //user gaurd
            if (Auth::guard($guard)->check()) {
                return redirect('/');
            }
            break;
    }

    return $next($request);
}
</code>```

Second Option

Store authentication details in cookie and while staring app just check once to redirect accordingly.

Body:
I have a manage login with roles . its user ,admin ,superadmin . i create this all roles in middleware , and at this code in LoginController :

protected function authenticated(Request $request, $user)
{
    if ( $user->isAdmin() ) {
        return redirect()->route('admin_dashboard');
    }
    elseif ($user->isSuperadmin()) {
        return redirect()->route('superadmin_dashboard');
    }
    else{
        return redirect()->route('dashboard');
    }

}

its work normaly , if i login admin its redirect to admin_dashboard , but  this problem is , if i close this browser and run localhost:8000 , its redirect to home not admin_dashboard .

my question , how i can set if login as admin and close the browser and run localhost:8000 its going to admin_dashboard ?

Body:
I think you should create multiple guards according to roles name like 'admin','superamdin'.

Here is link for create multiauth in laravel .
https://www.youtube.com/watch?v=iKRLrJXNN4M&t=1s

After your create multiple guards you can just use middleware to redirect authenticated user.

public function handle($request, Closure $next, $guard = null)
{
    switch ($guard) {
        case 'admin':
            if (Auth::guard('admin')->check()) {
                return redirect()->route('admin.dashboard');
            }
            break;

        case 'superadmin':
            if (Auth::guard('superadmin')->check()) {
                return redirect()->route('superadmin.dashboard');
            }
            break;

        default:
            //user gaurd
            if (Auth::guard($guard)->check()) {
                return redirect('/');
            }
            break;
    }

    return $next($request);
}

Second Option

Store authentication details in cookie and while staring app just check once to redirect accordingly.


问:
Compare values in GroupBy and count the matching rows
This is a sample row I have in my data frame:

```<code>{
"sessionId" : "454ec8b8-7f00-40b2-901c-724c5d9f5a91",
"useCaseId" : "3652b5d7-55b8-4bee-82b6-ab32d5543352",
"timestamp" : "1559403699899",
"endFlow" : "true"
}
</code>```

And there are 100s of rows like this with similar/different 'sessionId','useCaseId' and 'endFlow' values. I'm grouping it by 'sessionId' and 'useCaseId' as follows:

```<code>groupby_session_usecase = seperate_dates_df.groupby(['sessionId','useCaseId'])
</code>```

Within the groups in 'groupby_session_usecase', I want to find if there's any row who's 'endFlow' value is 'true'. I have tried the following:

```<code>'true' in groupby_session_usecase['endFlow']
</code>```

However, the above line always returns 'False' even if there are 'endFlow' values equal to 'true'

Whats the correct approach to check if there's any row within the  groups in 'groupby_session_usecase' having 'endFlow' value equal to 'true'?

答:
OP writes:

"I have to take a count of 'endFlow=true' based on 'sessionId' and
  'useCaseId'. Any idea how to achieve this requirement?"

Yes, all you have to do is to compare the rows first, then group on that result using SeriesGroupBy.sum().

```<code>(df['endFlow'] == "true").groupby([df['session'], df['useCaseId']]).sum()
</code>```

Alternatively, you can assign the comparison back to df, then your grouping becomes slightly simpler:

```<code>(df.assign(msk=df['endFlow'].eq('true'))
   .groupby(['session', 'useCaseId'])['msk']
   .sum())
</code>```

Body:
This is a sample row I have in my data frame:

{
"sessionId" : "454ec8b8-7f00-40b2-901c-724c5d9f5a91",
"useCaseId" : "3652b5d7-55b8-4bee-82b6-ab32d5543352",
"timestamp" : "1559403699899",
"endFlow" : "true"
}

And there are 100s of rows like this with similar/different 'sessionId','useCaseId' and 'endFlow' values. I'm grouping it by 'sessionId' and 'useCaseId' as follows:

groupby_session_usecase = seperate_dates_df.groupby(['sessionId','useCaseId'])

Within the groups in 'groupby_session_usecase', I want to find if there's any row who's 'endFlow' value is 'true'. I have tried the following:

'true' in groupby_session_usecase['endFlow']

However, the above line always returns 'False' even if there are 'endFlow' values equal to 'true'

Whats the correct approach to check if there's any row within the  groups in 'groupby_session_usecase' having 'endFlow' value equal to 'true'?

Body:
OP writes:

"I have to take a count of 'endFlow=true' based on 'sessionId' and
  'useCaseId'. Any idea how to achieve this requirement?"

Yes, all you have to do is to compare the rows first, then group on that result using SeriesGroupBy.sum().

(df['endFlow'] == "true").groupby([df['session'], df['useCaseId']]).sum()

Alternatively, you can assign the comparison back to df, then your grouping becomes slightly simpler:

(df.assign(msk=df['endFlow'].eq('true'))
   .groupby(['session', 'useCaseId'])['msk']
   .sum())


问:
What is the fastest way to convert an imageURL from Firebase into a UIImage?
In my iOS app I need to take an imageURL string and convert it into a UIImage.

I wrote the below function to handle this:

```<code> func getImage(urlString: String) -> UIImage {
    let url = URL(string: urlString)!
    do {
        let data = try Data(contentsOf: url)
        let image = UIImage(data: data)!
        return image
    } catch {
        print(error, " This was the error in p2")
    }
    return UIImage(named: "media")!
}
</code>```

The issue is that this takes too long. I believe it's a solid second or longer for this to complete.

I need that time to be significantly shorter.

Question: Is there a faster way to get the UIImage based on an imageURL from Firebase? (maybe a cocoa-pod? or better way to write the code?)

Additional questions:

Would this be any faster if the image in Firebase were of lower quality?

Would it be a viable solution to lower the quality of the image right before being passed into this function?

答:
A lot the prominent iOS apps (and web and mobile and general) that do a lot of downloading of images take advantage of progressive jpeg. This way your user will see at least something while the image loads and over time the image will get progressively better. As a lot of commenters have mentioned, you’re not in control of Firebase like you would be if you had your own backend server delivering the pictures that you could do performance optimizations. Therefore one of the best things you can do is implement progressive jpeg in your app.

The first link is a library that will allow you to use progressive jpeg in your iOS app. The second link is a detailed approach used at FaceBook on faster loading of images.

https://www.airpair.com/ios/posts/loading-images-ios-faster-with-progressive-jpegs

https://code.fb.com/ios/faster-photos-in-facebook-for-ios/

Body:
In my iOS app I need to take an imageURL string and convert it into a UIImage.

I wrote the below function to handle this:

 func getImage(urlString: String) -> UIImage {
    let url = URL(string: urlString)!
    do {
        let data = try Data(contentsOf: url)
        let image = UIImage(data: data)!
        return image
    } catch {
        print(error, " This was the error in p2")
    }
    return UIImage(named: "media")!
}

The issue is that this takes too long. I believe it's a solid second or longer for this to complete.

I need that time to be significantly shorter.

Question: Is there a faster way to get the UIImage based on an imageURL from Firebase? (maybe a cocoa-pod? or better way to write the code?)

Additional questions:

Would this be any faster if the image in Firebase were of lower quality?

Would it be a viable solution to lower the quality of the image right before being passed into this function?


问:
Getter and setter methods in a Peewee model
I have the following simple model in Peewee:

```<code>class SiteText(BaseModel):
    url = TextField()
    text = TextField()
    my_counter = IntegerField()

    def get_text_by_url(url):
        d = [s.text for s in SiteText.select(SiteText.url == url)]
        d = d[0] if len(d) > 0 else None
        return d

    def save_text(updates):
        # updates is a dict containing, url, text, my_counter
        SiteText.upsert(**updates)

    def get_outage_counter(url):
        c = [c.my_counter for c in SiteText.select(SiteText.url == url)]
        c = c[0] if len(c) > 0 else None
        return c

    def set_outage_counter(url, counter):
        c = SiteText.get(SiteText.url == url)
        c.counter = counter
        c.save()
</code>```

However, it feels rather strange writing getters and setters for some of the attributes. Is there a more Pythonic way of doing this? Should I, for example, have a single method for getting and setting the outage counter for a specified URL? Should I convert the getter and setter functions to properties (though then they would clash with the actual attributes). Feedback welcome!

答:
Due to the way peewee uses metaclasses and class variables, cannot define your fields in <code>__init__</code> you have to alternate the name </p>

```<code>class SiteText(db.Model):
    url = CharField()

    @property
    def gs_url(self):
        return self.url

    @gs_url.setter
    def gs_url(self, val):
        self.url = val
</code>```

Body:
I have the following simple model in Peewee:

class SiteText(BaseModel):
    url = TextField()
    text = TextField()
    my_counter = IntegerField()

    def get_text_by_url(url):
        d = [s.text for s in SiteText.select(SiteText.url == url)]
        d = d[0] if len(d) > 0 else None
        return d

    def save_text(updates):
        # updates is a dict containing, url, text, my_counter
        SiteText.upsert(**updates)

    def get_outage_counter(url):
        c = [c.my_counter for c in SiteText.select(SiteText.url == url)]
        c = c[0] if len(c) > 0 else None
        return c

    def set_outage_counter(url, counter):
        c = SiteText.get(SiteText.url == url)
        c.counter = counter
        c.save()

However, it feels rather strange writing getters and setters for some of the attributes. Is there a more Pythonic way of doing this? Should I, for example, have a single method for getting and setting the outage counter for a specified URL? Should I convert the getter and setter functions to properties (though then they would clash with the actual attributes). Feedback welcome!

Body:
Due to the way peewee uses metaclasses and class variables, cannot define your fields in __init__ you have to alternate the name

class SiteText(db.Model):
    url = CharField()

    @property
    def gs_url(self):
        return self.url

    @gs_url.setter
    def gs_url(self, val):
        self.url = val


问:
How to make a string from separate int values
I'm trying to make a string out of 3 elements with the following format '0/5'.

int start = 0;
int finish = 5;

I've tried doing this:

```<code>    char string[20];

    string[0] = (char) start;
    string[1] = '/';
    string[2] = (char) finish;

    string[strlen(string)] = '\0';

</code>```

But when I printf I get nothing.

```<code>    char buffer[10];
    char aux[5] = {'/', '\0'};
    char aux2[5];
    sprintf(buffer, "%d", start);
    strcat(buffer, aux);
    sprintf(aux2, "%d", finish);
    strcat(buffer, aux2);
</code>```

This is what is working but seems very inefficient.

答:
When you print a char using printf, it's ASCII value is used. In this specific case, you could use

```<code>string[0] = (char) (start + '0');
string[1] = '/';
string[2] = (char) (finish + '0');
</code>```

Or you could use string[0] = (char) start + 48;. The ASCII value of '0' is 48.

Or better initialize start and finish as char start = '0', char finish = '5', etc.

In addition, make sure that start and finish are between 0 and 9. Other values, will give you unexpected results.

Also, the last line should be string[3] = '\0'. strlen works by iterating till it encounters a \0 and thus is useless in this case.

Demo

Body:
I'm trying to make a string out of 3 elements with the following format '0/5'.

int start = 0;
int finish = 5;

I've tried doing this:

    char string[20];

    string[0] = (char) start;
    string[1] = '/';
    string[2] = (char) finish;

    string[strlen(string)] = '\0';

But when I printf I get nothing.

    char buffer[10];
    char aux[5] = {'/', '\0'};
    char aux2[5];
    sprintf(buffer, "%d", start);
    strcat(buffer, aux);
    sprintf(aux2, "%d", finish);
    strcat(buffer, aux2);

This is what is working but seems very inefficient.

Body:
When you print a char using printf, it's ASCII value is used. In this specific case, you could use

string[0] = (char) (start + '0');
string[1] = '/';
string[2] = (char) (finish + '0');

Or you could use string[0] = (char) start + 48;. The ASCII value of '0' is 48.

Or better initialize start and finish as char start = '0', char finish = '5', etc.

In addition, make sure that start and finish are between 0 and 9. Other values, will give you unexpected results.

Also, the last line should be string[3] = '\0'. strlen works by iterating till it encounters a \0 and thus is useless in this case.

Demo


问:
Puppeteer - Page.evaluate using moment
I am trying to use "puppeteer": "^1.16.0", and "moment": "^2.24.0",. When running page.evaluate() to convert a string to a date obj via moment I get:

Error: Evaluation failed: ReferenceError: moment is not defined

Find below my minimum example:

```<code>const puppeteer = require("puppeteer-extra")
const moment = require('moment')

function shuffle(dataObjArr) {
    let res = dataObjArr.sort(() => Math.random() - 0.5);
    return res
}

let issuerUrls = JSON.parse('[{"id":62,"name":"Product 1","ecomUrl":"/product/252","createdAt":"2019-05-25T07:51:49.000Z","updatedAt":"2019-05-25T07:51:49.000Z"},  {"id":15,"name":"Product 2","ecomUrl":"/product/251","createdAt":"2019-05-25T07:51:49.000Z","updatedAt":"2019-05-25T07:51:49.000Z"}]')

let issuerUrlsShuffled = shuffle(issuerUrls)
let BASE_URL = "https://www.webscraper.io/test-sites/e-commerce/allinone"
// puppeteer usage as normal
puppeteer.launch({
    headless: false,
    args: ["--disable-notifications"]
}).then(async browser => {
    const page = await browser.newPage()
    await page.setViewport({
        width: 800,
        height: 600
    })

    for (let i = 0; i < issuerUrlsShuffled.length; i++) {
        try {

            let URL = BASE_URL + issuerUrlsShuffled[i].ecomUrl;

            await page.goto(URL)

            page.waitForNavigation({
                timeout: 60,
                waitUntil: 'domcontentloaded'
            });

            const data = await page.evaluate(() => {

                const priceData = []

                let date = "9/23/2016" // this is needed for testing purposes only!!!

                priceData.push({
                    price_date: moment(date, 'M/DD/YYYY').toDate()
                })
                return priceData
            }, moment)

            // show data
            console.log(JSON.stringify(data, null, 2))

            await page.waitFor(3000)
        } catch (error) {
            console.log(error)
        }
    }
    await browser.close()
})
</code>```

As you can see I tried to pass the moment instance to the evaluate function, however I still get the error.

Any suggestions what I am doing wrong?

I appreciate your replies!

答:
You can only pass serializable data to the page.evaluate function as argument. (see the docs for more information). As moment is a function and a function cannot be serialized you cannot use it that easy.

To expose a function to the page from your Node.js environment, you can use the page.exposeFunction. Quote from the docs:

The method adds a function called name on the page's window object. When called, the function executes puppeteerFunction in node.js and returns a Promise which resolves to the return value of puppeteerFunction.

Code sample:

The following code inside your Node.js environment sets up a function formatDate which returns the formatted date:

await page.exposeFunction('formatDate', (date) =>
  moment(date, 'M/DD/YYYY').toDate()
);
```

<p>Be aware that you only need to call <code>exposeFunction</code> once on the page as it survives navigation. That means you can put this code outside of the loop.</p>

<p>Then your puppeteer code could use the function like this:</p>

<pre class="lang-js prettyprint-override"><code>const data = await page.evaluate(async () => {
  const priceData = []
  let date = "9/23/2016"
  priceData.push({
    price_date: await window.formatDate(date)
  })
  return priceData
})
</code>```

Title: Puppeteer - Page.evaluate using moment

Body:
I am trying to use "puppeteer": "^1.16.0", and "moment": "^2.24.0",. When running page.evaluate() to convert a string to a date obj via moment I get:

Error: Evaluation failed: ReferenceError: moment is not defined

Find below my minimum example:

const puppeteer = require("puppeteer-extra")
const moment = require('moment')

function shuffle(dataObjArr) {
    let res = dataObjArr.sort(() => Math.random() - 0.5);
    return res
}

let issuerUrls = JSON.parse('[{"id":62,"name":"Product 1","ecomUrl":"/product/252","createdAt":"2019-05-25T07:51:49.000Z","updatedAt":"2019-05-25T07:51:49.000Z"},  {"id":15,"name":"Product 2","ecomUrl":"/product/251","createdAt":"2019-05-25T07:51:49.000Z","updatedAt":"2019-05-25T07:51:49.000Z"}]')

let issuerUrlsShuffled = shuffle(issuerUrls)
let BASE_URL = "https://www.webscraper.io/test-sites/e-commerce/allinone"
// puppeteer usage as normal
puppeteer.launch({
    headless: false,
    args: ["--disable-notifications"]
}).then(async browser => {
    const page = await browser.newPage()
    await page.setViewport({
        width: 800,
        height: 600
    })

    for (let i = 0; i < issuerUrlsShuffled.length; i++) {
        try {

            let URL = BASE_URL + issuerUrlsShuffled[i].ecomUrl;

            await page.goto(URL)

            page.waitForNavigation({
                timeout: 60,
                waitUntil: 'domcontentloaded'
            });

            const data = await page.evaluate(() => {

                const priceData = []

                let date = "9/23/2016" // this is needed for testing purposes only!!!

                priceData.push({
                    price_date: moment(date, 'M/DD/YYYY').toDate()
                })
                return priceData
            }, moment)

            // show data
            console.log(JSON.stringify(data, null, 2))

            await page.waitFor(3000)
        } catch (error) {
            console.log(error)
        }
    }
    await browser.close()
})

As you can see I tried to pass the moment instance to the evaluate function, however I still get the error.

Any suggestions what I am doing wrong?

I appreciate your replies!

Body:
You can only pass serializable data to the page.evaluate function as argument. (see the docs for more information). As moment is a function and a function cannot be serialized you cannot use it that easy.

To expose a function to the page from your Node.js environment, you can use the page.exposeFunction. Quote from the docs:

The method adds a function called name on the page's window object. When called, the function executes puppeteerFunction in node.js and returns a Promise which resolves to the return value of puppeteerFunction.

Code sample:

The following code inside your Node.js environment sets up a function formatDate which returns the formatted date:

await page.exposeFunction('formatDate', (date) =>
  moment(date, 'M/DD/YYYY').toDate()
);

Be aware that you only need to call exposeFunction once on the page as it survives navigation. That means you can put this code outside of the loop.

Then your puppeteer code could use the function like this:

const data = await page.evaluate(async () => {
  const priceData = []
  let date = "9/23/2016"
  priceData.push({
    price_date: await window.formatDate(date)
  })
  return priceData
})


答:
```<code>df.loc[((df['T'] > df['T'].shift(-1)) & (df['T'] != df['PL'])), 'PL'] = df['T']
</code>```

IIUC, this should do what you want.

EDIT:

```<code>df.loc[(((df['T'].shift(-1).isnull())&(df['PL'].diff()>0))|(~df['T'].shift().isnull())) , 'T'] = df['PL']
</code>```

This works for me. I don't understand though why in your example why 4.65 and 4.87 are not filled. They fill all the requirements, and are filled in my case.

Title: What is the correct way to layer if statements in order to get the desired results

Body:
df.loc[((df['T'] > df['T'].shift(-1)) & (df['T'] != df['PL'])), 'PL'] = df['T']

IIUC, this should do what you want.

EDIT:

df.loc[(((df['T'].shift(-1).isnull())&(df['PL'].diff()>0))|(~df['T'].shift().isnull())) , 'T'] = df['PL']

This works for me. I don't understand though why in your example why 4.65 and 4.87 are not filled. They fill all the requirements, and are filled in my case.


问:
Recording an entire row of cells (with references to other cells) automatically when I change the referenced cells
I have formulas that I need to change that have outputs and solutions. I have created an entire row A46:CV42 that shows every effected Value (formulas solution) in each cell. What I need is to record every single change to that entire row automatically every time any cell value is changed. Be it on the same sheet below it in recurring rows or on another sheet.

I have tried some things I have found but they all deal with individual cells being changed or when you manually change data.

Example of what I've tried. I am a novice in this area.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$A$2" Then
        a = Sheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Row + 1
        Sheets("Sheet2").Range("A" & a).Value = Sheets("Sheet1").Range("A").Value
    End If
End Sub
```

答:
I'm not quite sure if you want row 46 or row 42. Please see below an approach, and comments in the code for further details:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim wb As Workbook: Set wb = ThisWorkbook

    Dim wsWatch As Worksheet: Set wsWatch = wb.Sheets("Sheet1") 'declare and set the sheet (change the name or use Target.Worksheet instead as needed)
    Dim rngWatch As Range: Set rngWatch = wsWatch.Range("A46:CV46") 'declare and set the range to watch over
    Dim arrWatch As Variant: arrWatch = rngWatch 'allocate the range to an array

    Dim wsHistory As Worksheet: Set wsHistory = wb.Sheets("Sheet2") 'declare and set the sheet
    With wsHistory
        Dim lRow As Long: lRow = .Cells(.Rows.Count, "A").End(xlUp).Row 'get the last row in the history
        Dim rngHistory As Range: Set rngHistory = .Range(.Cells(lRow, 1), .Cells(lRow, 100)) 'declare and set the range of the last populated row (last historic change)
    End With
    Dim arrHistory As Variant: arrHistory = rngHistory 'allocate the range to an array

    Dim C As Long

    'Only one row in the arrays, let's loop over the columns
    For C = LBound(arrWatch, 2) To UBound(arrWatch, 2) 'for each column in the ranges
        If arrWatch(1, C) <> arrHistory(1, C) Then 'if there is a mismatch
            rngHistory.Offset(1) = rngWatch.Value 'allocate the values in the next free row
            Exit For 'exit here if mismatch found
        End If
    Next C
End Sub
```

This might not be the ideal solution, but i'm looking forward to see other solutions... meanwhile, I think it does what you've asked.

Body:
I'm not quite sure if you want row 46 or row 42. Please see below an approach, and comments in the code for further details:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim wb As Workbook: Set wb = ThisWorkbook

    Dim wsWatch As Worksheet: Set wsWatch = wb.Sheets("Sheet1") 'declare and set the sheet (change the name or use Target.Worksheet instead as needed)
    Dim rngWatch As Range: Set rngWatch = wsWatch.Range("A46:CV46") 'declare and set the range to watch over
    Dim arrWatch As Variant: arrWatch = rngWatch 'allocate the range to an array

    Dim wsHistory As Worksheet: Set wsHistory = wb.Sheets("Sheet2") 'declare and set the sheet
    With wsHistory
        Dim lRow As Long: lRow = .Cells(.Rows.Count, "A").End(xlUp).Row 'get the last row in the history
        Dim rngHistory As Range: Set rngHistory = .Range(.Cells(lRow, 1), .Cells(lRow, 100)) 'declare and set the range of the last populated row (last historic change)
    End With
    Dim arrHistory As Variant: arrHistory = rngHistory 'allocate the range to an array

    Dim C As Long

    'Only one row in the arrays, let's loop over the columns
    For C = LBound(arrWatch, 2) To UBound(arrWatch, 2) 'for each column in the ranges
        If arrWatch(1, C) <> arrHistory(1, C) Then 'if there is a mismatch
            rngHistory.Offset(1) = rngWatch.Value 'allocate the values in the next free row
            Exit For 'exit here if mismatch found
        End If
    Next C
End Sub

This might not be the ideal solution, but i'm looking forward to see other solutions... meanwhile, I think it does what you've asked.


问:
Laravel CRUD delete route parameters
Id' like to use a CRUD Controller to handle the admin profile. I created the Controller and edited my routes/web.php like this.

Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'as' => 'admin.', 'middleware' => ['auth:admin']], function(){
    Route::resource('profile', 'ProfileController')->only(['index', 'edit', 'update', 'destroy']);
});
```

<p>This creates the following routes.</p>

```admin/profile -> admin.profile.index
admin/profile/{profile} -> admin.profile.destroy
admin/profile/{profile} -> admin.profile.update
admin/profile/{profile}/edit -> admin.profile.edit
```

Since I get the admin_id through the session I don't need to get it through the URL via the profile parameter. I know that I could just ignore the parameter, but it makes the URL unnecessary long.
Is there a chance to delete the {profile} parameter from the routes, so that my routes are like teacher/profile/edit and not like teacher/profile/12345678/edit?

答:
You can use separate routes instead of resource for your individual operation.
Like

```<code>For index operation you can use:-
Route::get('profile', 'ProfileController@index');
For destroy operation you can use:-
Route::delete('profile', 'ProfileController@destroy');
For edit operation you can use:-
Route::put('profile', 'ProfileController@edit');
</code>```

And you can send your admin_id  in input or from session.
Hope it will work for you :)

Title: Laravel CRUD delete route parameters

Body:
Id' like to use a CRUD Controller to handle the admin profile. I created the Controller and edited my routes/web.php like this.

Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'as' => 'admin.', 'middleware' => ['auth:admin']], function(){
    Route::resource('profile', 'ProfileController')->only(['index', 'edit', 'update', 'destroy']);
});

This creates the following routes.

admin/profile -> admin.profile.index
admin/profile/{profile} -> admin.profile.destroy
admin/profile/{profile} -> admin.profile.update
admin/profile/{profile}/edit -> admin.profile.edit

Since I get the admin_id through the session I don't need to get it through the URL via the profile parameter. I know that I could just ignore the parameter, but it makes the URL unnecessary long.
Is there a chance to delete the {profile} parameter from the routes, so that my routes are like teacher/profile/edit and not like teacher/profile/12345678/edit?

Body:
You can use separate routes instead of resource for your individual operation.
Like

For index operation you can use:-
Route::get('profile', 'ProfileController@index');
For destroy operation you can use:-
Route::delete('profile', 'ProfileController@destroy');
For edit operation you can use:-
Route::put('profile', 'ProfileController@edit');

And you can send your admin_id  in input or from session.
Hope it will work for you :)


问:
LWUIT httpconnection not working on Blackberry
1) I made a J2ME app using LWUIT in which I am accessing internet to get info from my server....
2) The app is perfectly connecting to my sever on Nokia, Android handsets
3) But when the same app is run on Blackberry ....I get NullPointer exception during httpconnection...
4) The code snippet is as follows

```<code>import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
StringBuffer b = new StringBuffer();
InputStream is = null;
private HttpConnection connection;
try
{
        connection=(HttpConnection) Connector.open("http://curiousinc.in/ipl4app/LiveMatch.txt");
    is = connection.openInputStream();
}
</code>```

5) Now why is this code not working on BB???.....I compiled BB jar & cod file using netbeans & BB SDK v4.6

答: It does not work because Blackberry is special, i.e. does not entirely follow the norm. Use this HttpConnection factory.</p>

Body:
1) I made a J2ME app using LWUIT in which I am accessing internet to get info from my server....
2) The app is perfectly connecting to my sever on Nokia, Android handsets
3) But when the same app is run on Blackberry ....I get NullPointer exception during httpconnection...
4) The code snippet is as follows

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
StringBuffer b = new StringBuffer();
InputStream is = null;
private HttpConnection connection;
try
{
        connection=(HttpConnection) Connector.open("http://curiousinc.in/ipl4app/LiveMatch.txt");
    is = connection.openInputStream();
}

5) Now why is this code not working on BB???.....I compiled BB jar & cod file using netbeans & BB SDK v4.6


问:
How to split Golang strings without deleting separator?
According to the answer at How to split a string and assign it to variables in Golang? splitting a string results in an array of strings where the separator is not present in any of the strings in the array. Is there a way to split strings such that the separator is on the last line of a given string?

e.x.

```<code>s := strings.split("Potato:Salad:Popcorn:Cheese", ":")
for _, element := range s {
    fmt.Printf(element)
}
</code>```

outputs:

```<code>Potato
Salad
Popcorn
Cheese
</code>```

I wish to output the following instead:

```<code>Potato:
Salad:
Popcorn:
Cheese
</code>```

I know I could theoretically append ":" to the end of each element except for the last, but I'm looking for a more general, elegant solution if possible.

答:
Try this to get the proper result.

```<code>package main

    import (
        "fmt"
        "strings"
    )

    func main() {
        str := "Potato:Salad:Popcorn:Cheese"
        a := strings.SplitAfter(str, ":")
        for i := 0; i < len(a); i++ {
            fmt.Println(a[i])
        }
    }
</code>```

Body:
According to the answer at How to split a string and assign it to variables in Golang? splitting a string results in an array of strings where the separator is not present in any of the strings in the array. Is there a way to split strings such that the separator is on the last line of a given string?

e.x.

s := strings.split("Potato:Salad:Popcorn:Cheese", ":")
for _, element := range s {
    fmt.Printf(element)
}

outputs:

Potato
Salad
Popcorn
Cheese

I wish to output the following instead:

Potato:
Salad:
Popcorn:
Cheese

I know I could theoretically append ":" to the end of each element except for the last, but I'm looking for a more general, elegant solution if possible.

Body:
Try this to get the proper result.

package main

    import (
        "fmt"
        "strings"
    )

    func main() {
        str := "Potato:Salad:Popcorn:Cheese"
        a := strings.SplitAfter(str, ":")
        for i := 0; i < len(a); i++ {
            fmt.Println(a[i])
        }
    }


问:
The app associated with the sound, flies out of the emulator
I need to make an app so that when I click on the picture, there is a sound. I write on Java (Android Studio).

```<code>package com.example.project_1;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

private ImageView img1, img2;
private MediaPlayer sound1, sound2;

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

  img1=(ImageView)findViewById(R.id.image1);
  img2=(ImageView)findViewById(R.id.image2);

  sound1=MediaPlayer.create(this, R.raw.sn1);
  sound2=MediaPlayer.create(this, R.raw.sn2);

  imageClick();
}

public void imageClick() {
  img1.setOnClickListener(
        new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SoundPlay(sound1);
            }
        }
  );

  img2.setOnClickListener(
        new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SoundPlay(sound2);
            }
        }
  );
}

public void SoundPlay(MediaPlayer allsounds) {
  allsounds.start();
}

}
</code>```

The code is compiled, but when you click on the image in the emulator, the application crashes. in logs found it:

```<code>2019-06-01 21:15:08.408 13431-13431/? E/ample.project_: Unknown bits set in runtime_flags: 0x8000
2019-06-01 21:15:08.798 13431-13453/? E/vndksupport: Could not load /vendor/lib/egl/libGLES_emulation.so from sphal namespace: dlopen failed: library "/vendor/lib/egl/libGLES_emulation.so" not found.
2019-06-01 21:15:08.798 13431-13453/? E/libEGL: load_driver(/vendor/lib/egl/libGLES_emulation.so): unknown
2019-06-01 21:15:09.798 13431-13452/com.example.project_1 E/EGL_emulation: tid 13452: eglQueryString(923): error 0x3008 (EGL_BAD_DISPLAY)
2019-06-01 21:15:17.712 13431-13447/com.example.project_1 E/MediaPlayerNative: error (1, -2147483648)
2019-06-01 21:15:17.715 13431-13431/com.example.project_1 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.project_1, PID: 13431 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference at
com.example.project_1.MainActivity.SoundPlay(MainActivity.java:51) at
com.example.project_1.MainActivity$2.onClick(MainActivity.java:43) at
android.view.View.performClick(View.java:7251) at
android.view.View.performClickInternal(View.java:7228) at
android.view.View.access$3500(View.java:802) at
android.view.View$PerformClick.run(View.java:27843) at
android.os.Handler.handleCallback(Handler.java:883) at
android.os.Handler.dispatchMessage(Handler.java:100) at
android.os.Looper.loop(Looper.java:214) at
android.app.ActivityThread.main(ActivityThread.java:7116) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:925)
</code>```

答:
I'm not familiar with Android development but in Java, we use ActionListener

the format is something like this.

```<code>private variableName = new DataType("params");
variableName.addActionListener(
    new methodName());
</code>```

then you add that object onto a JPanel or something...

again, I don't know Android, but that's how it's done in Java. So take this with a pinch of salt.

Body:
I need to make an app so that when I click on the picture, there is a sound. I write on Java (Android Studio).

package com.example.project_1;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

private ImageView img1, img2;
private MediaPlayer sound1, sound2;

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

  img1=(ImageView)findViewById(R.id.image1);
  img2=(ImageView)findViewById(R.id.image2);

  sound1=MediaPlayer.create(this, R.raw.sn1);
  sound2=MediaPlayer.create(this, R.raw.sn2);

  imageClick();
}

public void imageClick() {
  img1.setOnClickListener(
        new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SoundPlay(sound1);
            }
        }
  );

  img2.setOnClickListener(
        new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SoundPlay(sound2);
            }
        }
  );
}

public void SoundPlay(MediaPlayer allsounds) {
  allsounds.start();
}

}

The code is compiled, but when you click on the image in the emulator, the application crashes. in logs found it:

2019-06-01 21:15:08.408 13431-13431/? E/ample.project_: Unknown bits set in runtime_flags: 0x8000
2019-06-01 21:15:08.798 13431-13453/? E/vndksupport: Could not load /vendor/lib/egl/libGLES_emulation.so from sphal namespace: dlopen failed: library "/vendor/lib/egl/libGLES_emulation.so" not found.
2019-06-01 21:15:08.798 13431-13453/? E/libEGL: load_driver(/vendor/lib/egl/libGLES_emulation.so): unknown
2019-06-01 21:15:09.798 13431-13452/com.example.project_1 E/EGL_emulation: tid 13452: eglQueryString(923): error 0x3008 (EGL_BAD_DISPLAY)
2019-06-01 21:15:17.712 13431-13447/com.example.project_1 E/MediaPlayerNative: error (1, -2147483648)
2019-06-01 21:15:17.715 13431-13431/com.example.project_1 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.project_1, PID: 13431 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference at
com.example.project_1.MainActivity.SoundPlay(MainActivity.java:51) at
com.example.project_1.MainActivity$2.onClick(MainActivity.java:43) at
android.view.View.performClick(View.java:7251) at
android.view.View.performClickInternal(View.java:7228) at
android.view.View.access$3500(View.java:802) at
android.view.View$PerformClick.run(View.java:27843) at
android.os.Handler.handleCallback(Handler.java:883) at
android.os.Handler.dispatchMessage(Handler.java:100) at
android.os.Looper.loop(Looper.java:214) at
android.app.ActivityThread.main(ActivityThread.java:7116) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:925)

Body:
I'm not familiar with Android development but in Java, we use ActionListener

the format is something like this.

private variableName = new DataType("params");
variableName.addActionListener(
    new methodName());

then you add that object onto a JPanel or something...

again, I don't know Android, but that's how it's done in Java. So take this with a pinch of salt.


问:
How to check if a recipient email address domain has TLS implemented?
We are trying to check if a recipient email id (domain of a given email id) has TLS implemented or not. If not implemented we cannot send the email. Is there any way in C# to check it? e.g. Following is a service where we can enter any email id and it will tell us if that email domain has TLS implemented or not.   https://www.checktls.com/TestReceiver  How to do this in C#?   C# email client comes with the property smtpClient.EnableSsl = true;  question is what will happen if at the recipient side the TLS is not implemented? Will it fail or it will go through? If it fails that's what we want. Our SMTP server has TLS implemented.

I tried STARTTLS command and EHLO from telnet. It gives 250 STARTTLS, which tells me that the destination server has TLS implemented. How to do it programmatically?

smtpClient.EnableSsl = true;

答:
If you use a library like MailKit, you can do this:

```<code>bool supportsStartTls;

using (var client = new SmtpClient ()) {
    client.Connect ("smtp.host.com", 587, SecureSocketOptions.None);
    supportsStartTls = client.Capabilities.HasFlag (SmtpCapabilities.StartTls);
    client.Disconnect (true);
}
</code>```

If you want to use MailKit to send mail, you have full control over what happens if STARTTLS is not available.

For example, if you wanted it to fail if STARTTLS is not supported, then use SecureSocketOptions.StartTls as the third argument to the Connect method.

If you want MailKit to use STARTTLS when it is available but not fail if it isn't, then use SecureSocketOptions.StartTlsWhenAvailable instead.

Body:
If you use a library like MailKit, you can do this:

bool supportsStartTls;

using (var client = new SmtpClient ()) {
    client.Connect ("smtp.host.com", 587, SecureSocketOptions.None);
    supportsStartTls = client.Capabilities.HasFlag (SmtpCapabilities.StartTls);
    client.Disconnect (true);
}

If you want to use MailKit to send mail, you have full control over what happens if STARTTLS is not available.

For example, if you wanted it to fail if STARTTLS is not supported, then use SecureSocketOptions.StartTls as the third argument to the Connect method.

If you want MailKit to use STARTTLS when it is available but not fail if it isn't, then use SecureSocketOptions.StartTlsWhenAvailable instead.


问:
Sending message from HTML input box using ajax and showing response
When i load this file on my server and launch the address from my browser
the input field is showing and working but when I enter a new string I dont get a response back.

<!DOCTYPE html>

Sending / retrieving a message with AJAX

Enter message below:

<input type="text" id="msgID" name="name" onchange="loadDoc()" required minlength="1" size="30">

```

答:
Your url is not updated onchange. You should update the url with the value from msgID and send XMLHttpRequest on the new url.

```<code><!DOCTYPE html>
<html>
<body>

<h2>Sending / retrieving a message with AJAX</h2>
<label for="name">Enter message below:</label><BR>
<input type="text" id="msgID" name="name" onchange="loadDoc()" required minlength="1" size="30">

<p id="demo"></p>

<script>
function loadDoc() {
  var newmsg = document.getElementById("msgID").value;
  var blob = new Blob([newmsg], {type: 'text/plain'});
  var url = URL.createObjectURL(blob);
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", url, true);
  xhttp.send();
}
</script>

</body>
</html>
</code>```

Body:
Your url is not updated onchange. You should update the url with the value from msgID and send XMLHttpRequest on the new url.

<!DOCTYPE html>
<html>
<body>

<h2>Sending / retrieving a message with AJAX</h2>
<label for="name">Enter message below:</label><BR>
<input type="text" id="msgID" name="name" onchange="loadDoc()" required minlength="1" size="30">

<p id="demo"></p>

<script>
function loadDoc() {
  var newmsg = document.getElementById("msgID").value;
  var blob = new Blob([newmsg], {type: 'text/plain'});
  var url = URL.createObjectURL(blob);
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", url, true);
  xhttp.send();
}
</script>

</body>
</html>