问:
Exception.ToString() throws exception
I am trying to log an exception using the Exception.ToString() method. However, I get a new exception from the ToString() method - it seems to originate from the stack trace handling.
The original error is a FileNotFoundException. Here is the output:

```<code>The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException
   at System.Signature.GetSignature(Void*, Int32, System.RuntimeFieldHandleInternal, System.IRuntimeMethodInfo, System.RuntimeType)
   at System.Reflection.RuntimeMethodInfo.FetchNonReturnParameters()
   at System.Reflection.RuntimeMethodInfo.GetParameters()
   at System.Diagnostics.StackTrace.ToString(TraceFormat)
   at System.Environment.GetStackTrace(System.Exception, Boolean)
   at System.Exception.GetStackTrace(Boolean)
   at System.Exception.get_StackTrace()
   at System.IO.FileNotFoundException.ToString()
   at InSQLMDASDriver.InSQLMDASDriver.Init(System.String, System.String)
   at InSQLMDASDriver.InSQLMDASDriverLogic.InSQLMDASDriverLogicInit(System.String, System.String)
   at InSQLMDASDriver.InSQLMDASDriverLogic..ctor(System.String, System.String)
   at InSQLMDASDriverWCFServer.Service1.MainTread()
   at System.Threading.ThreadHelper.ThreadStart_Context(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.ThreadHelper.ThreadStart()
</code>```

When I run this code I can verify that the exception is thrown from Exception.ToString():

```<code>    private void Init(string defaultWindowName, string mainPath)
    {
       try
       {

            // code that fails

        }
        catch(FileNotFoundException e)
        {
             string errorAsString = GetErrorAsString(e);

             Logger.Log(string.Format("Init error at line block {0}: {1}", initBlockCounter, errorAsString), level: LogLevel.Error);

             throw new Exception("FileNotFoundException: " + e.FileName + ", " + e.FusionLog, e);
       }
       catch (Exception e)
       {
              string errorAsString = GetErrorAsString(e);

              Logger.Log(string.Format("Init error at line block {0}: {1}", initBlockCounter, errorAsString), level: LogLevel.Error);

          throw;
      }
}

    string GetErrorAsString(Exception e)
    {
         try
         {
             return e.ToString();
         }
         catch(Exception ne)
         {
                     return e.Message + " (ERROR getting stacktrace: " + ne.Message + ")";
          }
    }
</code>```

Why does this happen..?

答:
Here is a description that matches my issue where an assembly failing to load  causes a FileNotFoundException, and calling ToString() gives another exception:

Here is what happens. The
Newtonsoft.Json.JsonConvert.DeserializeObject needs
System.Runtime.Serialization.Primitives assembly. But it is not
present, so it tries to throw the FileNotFoundException. It creates
the exception object and then it wants to set the stack trace for it.
So it looks at the topmost frame of the exception stack trace, finds
the Newtonsoft.Json.JsonConvert.DeserializeObject method there and
tries to use reflection to get its parameters info. When looking at
the 2nd parameter of the method which is of type
Newtonsoft.Json.JsonSerializerSettings, it tries to build the metadata
structure for this parameter type. And accidentally, one of the fields
of this type is of the StreamingContext type that comes from the
System.Runtime.Serialization.Primitives assembly. To get details on
the type, it attempts to load this assembly - and since it doesn't
exist (that was the reason for the original exception we are trying to
build stack trace for), it throws an exception and the result is what
you can see.

See the bug report and discussion there: https://github.com/dotnet/runtime/issues/5203. It should be fixed meanwhile.

Title: Exception.ToString() throws exception

Body:
I am trying to log an exception using the Exception.ToString() method. However, I get a new exception from the ToString() method - it seems to originate from the stack trace handling.
The original error is a FileNotFoundException. Here is the output:

The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException
   at System.Signature.GetSignature(Void*, Int32, System.RuntimeFieldHandleInternal, System.IRuntimeMethodInfo, System.RuntimeType)
   at System.Reflection.RuntimeMethodInfo.FetchNonReturnParameters()
   at System.Reflection.RuntimeMethodInfo.GetParameters()
   at System.Diagnostics.StackTrace.ToString(TraceFormat)
   at System.Environment.GetStackTrace(System.Exception, Boolean)
   at System.Exception.GetStackTrace(Boolean)
   at System.Exception.get_StackTrace()
   at System.IO.FileNotFoundException.ToString()
   at InSQLMDASDriver.InSQLMDASDriver.Init(System.String, System.String)
   at InSQLMDASDriver.InSQLMDASDriverLogic.InSQLMDASDriverLogicInit(System.String, System.String)
   at InSQLMDASDriver.InSQLMDASDriverLogic..ctor(System.String, System.String)
   at InSQLMDASDriverWCFServer.Service1.MainTread()
   at System.Threading.ThreadHelper.ThreadStart_Context(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.ThreadHelper.ThreadStart()

When I run this code I can verify that the exception is thrown from Exception.ToString():

    private void Init(string defaultWindowName, string mainPath)
    {
       try
       {

            // code that fails

        }
        catch(FileNotFoundException e)
        {
             string errorAsString = GetErrorAsString(e);

             Logger.Log(string.Format("Init error at line block {0}: {1}", initBlockCounter, errorAsString), level: LogLevel.Error);

             throw new Exception("FileNotFoundException: " + e.FileName + ", " + e.FusionLog, e);
       }
       catch (Exception e)
       {
              string errorAsString = GetErrorAsString(e);

              Logger.Log(string.Format("Init error at line block {0}: {1}", initBlockCounter, errorAsString), level: LogLevel.Error);

          throw;
      }
}

    string GetErrorAsString(Exception e)
    {
         try
         {
             return e.ToString();
         }
         catch(Exception ne)
         {
                     return e.Message + " (ERROR getting stacktrace: " + ne.Message + ")";
          }
    }

Why does this happen..?


来源: stackexchange

问:
Vue router and Bootstrap
I'm using Vue with vue-router and vue-strap. I'm trying to register components from vue-strap, but the examples look like this:

```<code>var alert = require('vue-strap').alert;

new Vue({
  components: {
    alert: alert
  }
})
</code>```

vue-router, on the other hand, doesn't create a Vue object.

```<code>Vue.use(VueRouter);

const router = new VueRouter({
  history: true,
  linkActiveClass : 'active'
});

router.map({
  '/': {
    component: Home
  }
});

const App = Vue.extend(Index);
router.start(App, '#root');
</code>```

So how do I declare my components?

答:
you can try it instead,</p>

```<code>import { alert } from 'vue-strap'
Vue.use(VueRouter);

const router = new VueRouter({
  history: true,
  linkActiveClass : 'active'
});

router.map({
  '/': {
    component: alert
  }
});

const App = Vue.extend(Index);
router.start(App, '#root');
</code>```

ContentLicense: CC BY-SA 3.0

Title: Vue router and Bootstrap

Body:
I'm using Vue with vue-router and vue-strap. I'm trying to register components from vue-strap, but the examples look like this:

var alert = require('vue-strap').alert;

new Vue({
  components: {
    alert: alert
  }
})

vue-router, on the other hand, doesn't create a Vue object.

Vue.use(VueRouter);

const router = new VueRouter({
  history: true,
  linkActiveClass : 'active'
});

router.map({
  '/': {
    component: Home
  }
});

const App = Vue.extend(Index);
router.start(App, '#root');

So how do I declare my components?

Body:
you can try it instead,

import { alert } from 'vue-strap'
Vue.use(VueRouter);

const router = new VueRouter({
  history: true,
  linkActiveClass : 'active'
});

router.map({
  '/': {
    component: alert
  }
});

const App = Vue.extend(Index);
router.start(App, '#root');


问:
Form validation losing variables
Let's say I enter a registration form with this ending URL: registration.php?accountType=a
The form is parsed on the same page (registration.php).  If the user doesn't pass form validation they are taken to registration.php with error messages.  So you see I lost my variable accountType=a.  My question:

Can I submit a form for validation and retain the accountType variable?  I'm aware that this could easily be done using a cookie.  I just want a further understanding.

Solution: Although all of the answers below were valid, I went with a Session variable and <form action="registration.php?<?php print 'accountType=' . $_SESSION['accountType']; ?>" etc.  Thanks for the help.

答:
You can easily to it in 3 ways...

Using PHP Sessions. Simply do something like

session_start();
$_SESSION['namespace'] = array('post' => $_POST, 'get' => $_GET);

Using Cookie (Session seems for me to be more elegant).

Use Ajax request; it will make your tasks easier.

ContentLicense: CC BY-SA 2.5

Title: Form validation losing variables


问:
Jquery Add class to next image in  tag using JQuery
How can jQuery be used to add class to next image?

I have set of images in webpage using for loop. They are displayed in table rows.

```<code><table class="table table-bordered">
  <?php
    <td><img class="img1" src="http://s5.tinypic.com/30v0ncn_th.jpg"/></td>

    for ($x = 0; $x < 5; $x++) { ?>
      <td>
        <img class="loopimg" src="http://s5.tinypic.com/30v0ncn_th.jpg"/>
      </td>
    <?php  } ?>
</table>
</code>```

What I would like to achieve is when i click on first image (class="img1"), it add class to the next image , clicking on that would add class to the next image.

```<code>$('.img1').click(function(){
  $(this).parent().next("td").addClass("active");
  alert("class");
});
</code>```

This Jquery code add "active" class to next  tag, i would like class to be added to next image. Thank you in advance

答:
while your next tag is a td and you want to add class to it's child image you have to use the children function of jquery library like this </p>

```<code>  $(document).ready(function(){
            $('.img1').click(function(){

         $(this).parent().next("td").children( "img" ).addClass("active");

        alert("class");
        });
        });
</code>```

Title: Jquery Add class to next image in <td> tag using JQuery

Body:
How can jQuery be used to add class to next image?

I have set of images in webpage using for loop. They are displayed in table rows.

  <?php

    for ($x = 0; $x < 5; $x++) { ?>

    <?php  } ?>

What I would like to achieve is when i click on first image (class="img1"), it add class to the next image , clicking on that would add class to the next image.

$('.img1').click(function(){
  $(this).parent().next("td").addClass("active");
  alert("class");
});

This Jquery code add "active" class to next  tag, i would like class to be added to next image. Thank you in advance

Body:
while your next tag is a td and you want to add class to it's child image you have to use the children function of jquery library like this

  $(document).ready(function(){
            $('.img1').click(function(){

         $(this).parent().next("td").children( "img" ).addClass("active");

        alert("class");
        });
        });


问:
Inline if-else with conditional operator not working React
I've been struggeling with this basic stuff for a while now, but I cant seem to get it to work.

I'm getting data from our backend and if there're any deliveries objects it will be displayed with this:

```<code><Expandable>
  <ObjectDisplay
    key={id}
    parentDocumentId={id}
    schema={schema[this.props.schema.collectionName]}
    value={this.props.collection.documents[id]}
  />
</Expandable>
</code>```

But if there is no deliveries I'd like to display a message like there's no deliveries. I can use .length and !deliveries (I get that), but it seems like my conditional isn't working:

```<code>render() {
  console.log(this.props.collection.ids.length) //Getting how many deliveries there are with their id
  return (
    <div>//Struggling with this:

      {!this.props.collection.ids && this.props.collection.ids.length < 1
        ? <p>No deliviers</p>
        : <div className="box">
            {this.props.collection.ids
              .filter(
                id =>
                  // note: this is only passed when in top level of document
                  this.props.collection.documents[id][
                    this.props.schema.foreignKey
                  ] === this.props.parentDocumentId
              )
              .map(id => {
                return (
                  <Expandable>
                    <ObjectDisplay
                      key={id}
                      parentDocumentId={id}
                      schema={schema[this.props.schema.collectionName]}
                      value={this.props.collection.documents[id]}
                    />
                  </Expandable>
                )
              })}
          </div>}
    </div>
  )
}
</code>```

I bet my problem is super basic, but I just can't get it to work.. Help is much appreciated!!

答:
Your condition throws an error. See here

```<code>!this.props.collection.ids && this.props.collection.ids.length < 1
                       ^
                      !false && undefined
</code>```

Change your condition to

```<code>this.props.collection.ids && this.props.collection.ids.length > 1
</code>```

and put your placeholder in the else block of your ternary.

Body:
I've been struggeling with this basic stuff for a while now, but I cant seem to get it to work.

I'm getting data from our backend and if there're any deliveries objects it will be displayed with this:

<Expandable>
  <ObjectDisplay
    key={id}
    parentDocumentId={id}
    schema={schema[this.props.schema.collectionName]}
    value={this.props.collection.documents[id]}
  />
</Expandable>

But if there is no deliveries I'd like to display a message like there's no deliveries. I can use .length and !deliveries (I get that), but it seems like my conditional isn't working:

render() {
  console.log(this.props.collection.ids.length) //Getting how many deliveries there are with their id
  return (

//Struggling with this:

      {!this.props.collection.ids && this.props.collection.ids.length < 1
        ?
No deliviers

        :

            {this.props.collection.ids
              .filter(
                id =>
                  // note: this is only passed when in top level of document
                  this.props.collection.documents[id][
                    this.props.schema.foreignKey
                  ] === this.props.parentDocumentId
              )
              .map(id => {
                return (
                  <Expandable>
                    <ObjectDisplay
                      key={id}
                      parentDocumentId={id}
                      schema={schema[this.props.schema.collectionName]}
                      value={this.props.collection.documents[id]}
                    />
                  </Expandable>
                )
              })}

}

  )
}

I bet my problem is super basic, but I just can't get it to work.. Help is much appreciated!!

Body:
Your condition throws an error. See here

!this.props.collection.ids && this.props.collection.ids.length < 1
                       ^
                      !false && undefined

Change your condition to

this.props.collection.ids && this.props.collection.ids.length > 1

and put your placeholder in the else block of your ternary.


问:
Change checkbox toggle function from click to touchstart
I am developing a cordova app. Because of the 300ms delay with the click event I don't want to use that. How do I change the event a <input type='checkbox'> element listens to for toggeling it's checkmark from click to e.g. touchstart?

The closest I got was making the checkbox disabled and adding this code:

```<code>$(':checkbox').each(function(){
        $(this).bind('touchstart', function(){
            if(this.checked) {
                this.checked = true;
            } else {
                this.checked = false;
            }
        })
    });
</code>```

Unfortunately touchstart does not trigger.

答:
for one, I need to call preventDefault() on the caught event.

The other problem was, that checked is not an actual jquery property of checkboxes, and I need to work with prop()

So what ended up working was:

```<code>$('.divClassContainingCheckbox').each(function(){
    $(this).bind('touchstart', function(e){
        e.preventDefault();  // prevents click from triggering check
        checkbox = $(this).find(':checkbox');
        if(checkbox.is(":checked")) {
            checkbox.prop('checked', false);
        } else {
            checkbox.prop('checked', true);
        }
    })
});
</code>```

HTML:

```<code><div class='divClassContainingCheckbox'>
    <input type='checkbox' />
</div>
</code>```

Body:
I am developing a cordova app. Because of the 300ms delay with the click event I don't want to use that. How do I change the event a <input type='checkbox'> element listens to for toggeling it's checkmark from click to e.g. touchstart?

The closest I got was making the checkbox disabled and adding this code:

$(':checkbox').each(function(){
        $(this).bind('touchstart', function(){
            if(this.checked) {
                this.checked = true;
            } else {
                this.checked = false;
            }
        })
    });

Unfortunately touchstart does not trigger.

Body:
for one, I need to call preventDefault() on the caught event.

The other problem was, that checked is not an actual jquery property of checkboxes, and I need to work with prop()

So what ended up working was:

$('.divClassContainingCheckbox').each(function(){
    $(this).bind('touchstart', function(e){
        e.preventDefault();  // prevents click from triggering check
        checkbox = $(this).find(':checkbox');
        if(checkbox.is(":checked")) {
            checkbox.prop('checked', false);
        } else {
            checkbox.prop('checked', true);
        }
    })
});

HTML:

<div class='divClassContainingCheckbox'>
    <input type='checkbox' />
</div>


问:
Detect a speed in android
is it possible to detect a speed of a car using GPS or accelerometer in android phone ?

can anyone give me the road map to implement this ?

答:
Yes, it's possible using GPS via object of Location class. There is getSpeed() method in this class.

It's very easy to find code of getting location. Check this link for example.

Title: Detect a speed in android


问:
Basic Python looping and appending
Write a program that takes a list and prints a message for each element in the list, based on that element's data type.

Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At the end of your program print the string, the number and an analysis of what the array contains. If it contains only one type, print that type, otherwise, print 'mixed'.

So the above is what I am trying to accomplish. And I am extremely new to all this so sorry if I don't make sense at times. Right now I am just trying to set up running through my list and appending any str to string list, and any int to my num list. Ive tried tons of ways and read documentation, and tried to search for help but I am either misreading stuff or just searching the wrong stuff. any help would be greatly appreciated.

```<code>stuff = ['magical unicorns',19,'hello',98.98,'world']

string = []
num = []

for i in range(len(stuff)):
    if isinstance(i,str):
        string.append(value,i)
    if isinstance(i,int):
        num.append(i)

print (string)
print (num)
</code>```

答:
```<code>for i in range(len(stuff))
</code>```

This will iterate over the indexes of your lists. So, you will only append this indexes to your list num.

Do the same loop but replace for i in range(len(stuff)) by for i in stuff. With this, you will iterate over your list elements.

Title: Basic Python looping and appending

Body:
Write a program that takes a list and prints a message for each element in the list, based on that element's data type.

Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At the end of your program print the string, the number and an analysis of what the array contains. If it contains only one type, print that type, otherwise, print 'mixed'.

So the above is what I am trying to accomplish. And I am extremely new to all this so sorry if I don't make sense at times. Right now I am just trying to set up running through my list and appending any str to string list, and any int to my num list. Ive tried tons of ways and read documentation, and tried to search for help but I am either misreading stuff or just searching the wrong stuff. any help would be greatly appreciated.

stuff = ['magical unicorns',19,'hello',98.98,'world']

string = []
num = []

for i in range(len(stuff)):
    if isinstance(i,str):
        string.append(value,i)
    if isinstance(i,int):
        num.append(i)

print (string)
print (num)

Body:
for i in range(len(stuff))

This will iterate over the indexes of your lists. So, you will only append this indexes to your list num.

Do the same loop but replace for i in range(len(stuff)) by for i in stuff. With this, you will iterate over your list elements.


问:
TableAdapter with multiple "LIKE" constraints
I'm using an Access database in my VB program and sorting it if a field has a value.

How would I add multiple conditions? Like if two values exist then show the results.

This is what I have now:

```<code>FROM    Orders
WHERE    ([Level] LIKE 'DD')
</code>```

How would I add ([NAME] Like 'Smith') to the constraints as well?

答:
You just need to append the conditions with AND:

```<code>FROM Orders WHERE ( [Level] LIKE 'DD' ) AND ( [NAME] Like 'Smith' )
</code>```

Body:
I'm using an Access database in my VB program and sorting it if a field has a value.

How would I add multiple conditions? Like if two values exist then show the results.

This is what I have now:

FROM    Orders
WHERE    ([Level] LIKE 'DD')

How would I add ([NAME] Like 'Smith') to the constraints as well?

Body:
You just need to append the conditions with AND:

FROM Orders WHERE ( [Level] LIKE 'DD' ) AND ( [NAME] Like 'Smith' )


答:
This should do the trick.    </p>

```<code>stuff = ['magical unicorns',19,'hello',98.98,'world']

s = ""
num = 0
hasnum = False
hasstr = False

for i in stuff:
    if isinstance(i, str):
        s += i
        hasstr = True
    if isinstance(i, int):
        num += i
        hasnum = True

print (string)
print (num)
if hasnum and not hasstr:
    print "Only ints"
elif hasstr:
    print "Only strs"
else:
     print "Mixed"
</code>```

Title: Basic Python looping and appending

Body:
This should do the trick.

stuff = ['magical unicorns',19,'hello',98.98,'world']

s = ""
num = 0
hasnum = False
hasstr = False

for i in stuff:
    if isinstance(i, str):
        s += i
        hasstr = True
    if isinstance(i, int):
        num += i
        hasnum = True

print (string)
print (num)
if hasnum and not hasstr:
    print "Only ints"
elif hasstr:
    print "Only strs"
else:
     print "Mixed"


问:
Take the sum of a list as variable and edit it at runtime
I'm trying to calculate the end value of a specific variable that depends whether a checkbox is checked. This is however dynamically done.

What I'm trying to achieve:

The example above works fine but it starts going wrong when I start to uncheck the check boxes. It subtracts by the double amount of the time and I have no idea why:

My Code (TimeSpent is the variable that I want to have at the end):

Class

```<code>public class Activity
{
    public int ID { get; set; }
    public int IncidentID { get; set; }
    public string Description { get; set; }
    public int TimeSpent { get; set; }
    public static int StartX { get; set; } = 10;
    public static int StartY { get; set; } = 10;

    private TextBox textBox = null;

    private CheckBox checkBox = null;

    public Activity(int iD, int incidentID, string description, int timeSpent)
    {
        this.ID = iD;
        this.IncidentID = incidentID;
        this.Description = description;
        this.TimeSpent = timeSpent;
    }

    public Activity()
    { }

    public bool isChecked() {
        return checkBox.Checked;
    }

    public void setTimeSpent(int timeSpent) {
        this.TimeSpent = timeSpent;
        textBox.Text = timeSpent.ToString();
    }

    public int getTimeSpent()
    {
        return Int32.Parse(textBox.Text);
    }

    public void DrawToForm(Panel p)
    {
        var label = new Label();
        textBox = new TextBox();
        checkBox = new CheckBox();
        checkBox.Checked = true;
        textBox.Size = new System.Drawing.Size(40, 20);
        label.Text = Description.ToString();
        label.AutoSize = true;
        textBox.Text = TimeSpent.ToString();
        label.Left = StartX;
        label.Top = StartY;
        StartX += 430;// Move position to right
        textBox.Left = StartX;
        textBox.Top = StartY;
        StartX += 160;// Move position to right
        checkBox.Left = StartX;
        checkBox.Top = StartY;
        StartX = 10;// Reset to start
        StartY += 50;// Move position to down
        p.Controls.Add(label);
        p.Controls.Add(textBox);
        p.Controls.Add(checkBox);
    }
}
</code>```

GUI:

```<code>private void Btn_Validate_Click(object sender, EventArgs e)
{
    tb_TotalTime.Text = calculateTotalTime().ToString();
}

public int calculateTotalTime()
{
    int total = 0;
    foreach (Activity a in activities)
    {
        if(a.isChecked())
        {
            total += a.getTimeSpent();
        }else
        {
            total -= a.getTimeSpent();
        }
    }
    return total;
}
</code>```

Why is subtracting not done correctly?

答:
Your logic is add if Check subtract if unchecked. Your logic should be add if Checked only.</p>

```<code>private void Btn_Validate_Click(object sender, EventArgs e)
    {

        tb_TotalTime.Text = calculateTotalTime().ToString();
    }

    public int calculateTotalTime()
    {
        int total = 0;
        foreach (Activity a in activities)
        {

            if (a.isChecked())
            {
                total += a.getTimeSpent();
            }
        }
        return total;
    }
</code>```

Body:
I'm trying to calculate the end value of a specific variable that depends whether a checkbox is checked. This is however dynamically done.

What I'm trying to achieve:

The example above works fine but it starts going wrong when I start to uncheck the check boxes. It subtracts by the double amount of the time and I have no idea why:

My Code (TimeSpent is the variable that I want to have at the end):

Class

public class Activity
{
    public int ID { get; set; }
    public int IncidentID { get; set; }
    public string Description { get; set; }
    public int TimeSpent { get; set; }
    public static int StartX { get; set; } = 10;
    public static int StartY { get; set; } = 10;

    private TextBox textBox = null;

    private CheckBox checkBox = null;

    public Activity(int iD, int incidentID, string description, int timeSpent)
    {
        this.ID = iD;
        this.IncidentID = incidentID;
        this.Description = description;
        this.TimeSpent = timeSpent;
    }

    public Activity()
    { }

    public bool isChecked() {
        return checkBox.Checked;
    }

    public void setTimeSpent(int timeSpent) {
        this.TimeSpent = timeSpent;
        textBox.Text = timeSpent.ToString();
    }

    public int getTimeSpent()
    {
        return Int32.Parse(textBox.Text);
    }

    public void DrawToForm(Panel p)
    {
        var label = new Label();
        textBox = new TextBox();
        checkBox = new CheckBox();
        checkBox.Checked = true;
        textBox.Size = new System.Drawing.Size(40, 20);
        label.Text = Description.ToString();
        label.AutoSize = true;
        textBox.Text = TimeSpent.ToString();
        label.Left = StartX;
        label.Top = StartY;
        StartX += 430;// Move position to right
        textBox.Left = StartX;
        textBox.Top = StartY;
        StartX += 160;// Move position to right
        checkBox.Left = StartX;
        checkBox.Top = StartY;
        StartX = 10;// Reset to start
        StartY += 50;// Move position to down
        p.Controls.Add(label);
        p.Controls.Add(textBox);
        p.Controls.Add(checkBox);
    }
}

GUI:

private void Btn_Validate_Click(object sender, EventArgs e)
{
    tb_TotalTime.Text = calculateTotalTime().ToString();
}

public int calculateTotalTime()
{
    int total = 0;
    foreach (Activity a in activities)
    {
        if(a.isChecked())
        {
            total += a.getTimeSpent();
        }else
        {
            total -= a.getTimeSpent();
        }
    }
    return total;
}

Why is subtracting not done correctly?

Body:
Your logic is add if Check subtract if unchecked. Your logic should be add if Checked only.

private void Btn_Validate_Click(object sender, EventArgs e)
    {

        tb_TotalTime.Text = calculateTotalTime().ToString();
    }

    public int calculateTotalTime()
    {
        int total = 0;
        foreach (Activity a in activities)
        {

            if (a.isChecked())
            {
                total += a.getTimeSpent();
            }
        }
        return total;
    }


问:
ngrx Effects: Are actions dispatched by one effect processed immediately by other effects?
I have an Angular (2) app with four ngrx actions:

START

Not processed by the reducer (no state change)

ngrx Effect calls an async task and maps to SUCCESS or ERROR

SUCCESS

Processed by the reducer

ngrx Effect maps to ADVANCE

ADVANCE

Not processed by the reducer

ngrx Effect navigates to a different route

ERROR

Processed by the reducer

No Effect

The problem is that the Effect that catches ADVANCE seems to run before the reducer that processes SUCCESS

Here's the Effects code:

```<code>@Effect() start$ = this.actions$
    .ofType('START')
    .map(toPayload)
    .switchMap(input => doAsyncTask(input)
        .map(result => ({type: 'SUCCESS', payload: result}))
        .catch(error => ({type: 'ERROR', payload: error})));

@Effect() success$ = this.actions$
    .ofType('SUCCESS')
    .map(() => ({type: 'ADVANCE'}));

@Effect({dispatch: false}) advance$ = this.actions$
    .ofType('ADVANCE')
    .withLatestFrom(this.store$.select(state => state.route))
    .map(action_route => action_route[1])
    .do(route => this.router.navigate([route.foo.bar]));
</code>```

The error that I am getting is Cannot read property 'bar' of null. The property foo is set by the reducer that processes SUCCESS.

If I add a delay to the SUCCESS effect, it all works nicely:

```<code>@Effect() success$ = this.actions$
    .ofType('SUCCESS')
    .delay(1)
    .map(() => ({type: 'ADVANCE'}));
</code>```

But having to add this delay doesn't make sense to me.

I added console.log statements everywhere and the output looks like this:

SUCCESS effect

ADVANCE effect (showing route.foo === null)

SUCCESS reducer (showing route.foo === something)

Error

I expected the SUCCESS effect and the SUCCESS reducer to run before the ADVANCE effect.

Am I doing something wrong?

Is it incorrect to expect that actions are processed by the reducers in the same order that they are dispatched?

Versions:

@angular/cli: 1.0.0-beta.32.3

node: 7.5.0

os: darwin x64

@angular/common: 2.4.7

@angular/compiler: 2.4.7

@angular/core: 2.4.7

@angular/forms: 2.4.7

@angular/http: 2.4.7

@angular/platform-browser: 2.4.7

@angular/platform-browser-dynamic: 2.4.7

@angular/router: 3.4.7

@angular/cli: 1.0.0-beta.32.3

@angular/compiler-cli: 2.4.7

@ngrx/core@1.2.0

@ngrx/effects@2.0.0

@ngrx/store@2.2.1

rxjs: 5.1.1

答:
It might work to replace your .map in the catch of the START action with a .concatMap and put both your map to SUCCESS and to ACTION there.</p>

```<code>@Effect() start$ = this.actions$
    .ofType('START')
    .map(toPayload)
    .switchMap(input => doAsyncTask(input)
        .concatMap(result => {
            return Observable.from([type: 'SUCCESS', payload: result,
                                    type: 'ADVANCE'])
        .catch(error => ({type: 'ERROR', payload: error})));
</code>```

Body:
I have an Angular (2) app with four ngrx actions:

START

Not processed by the reducer (no state change)

ngrx Effect calls an async task and maps to SUCCESS or ERROR

SUCCESS

Processed by the reducer

ngrx Effect maps to ADVANCE

ADVANCE

Not processed by the reducer

ngrx Effect navigates to a different route

ERROR

Processed by the reducer

No Effect

The problem is that the Effect that catches ADVANCE seems to run before the reducer that processes SUCCESS

Here's the Effects code:

@Effect() start$ = this.actions$
    .ofType('START')
    .map(toPayload)
    .switchMap(input => doAsyncTask(input)
        .map(result => ({type: 'SUCCESS', payload: result}))
        .catch(error => ({type: 'ERROR', payload: error})));

@Effect() success$ = this.actions$
    .ofType('SUCCESS')
    .map(() => ({type: 'ADVANCE'}));

@Effect({dispatch: false}) advance$ = this.actions$
    .ofType('ADVANCE')
    .withLatestFrom(this.store$.select(state => state.route))
    .map(action_route => action_route[1])
    .do(route => this.router.navigate([route.foo.bar]));

The error that I am getting is Cannot read property 'bar' of null. The property foo is set by the reducer that processes SUCCESS.

If I add a delay to the SUCCESS effect, it all works nicely:

@Effect() success$ = this.actions$
    .ofType('SUCCESS')
    .delay(1)
    .map(() => ({type: 'ADVANCE'}));

But having to add this delay doesn't make sense to me.

I added console.log statements everywhere and the output looks like this:

SUCCESS effect

ADVANCE effect (showing route.foo === null)

SUCCESS reducer (showing route.foo === something)

Error

I expected the SUCCESS effect and the SUCCESS reducer to run before the ADVANCE effect.

Am I doing something wrong?

Is it incorrect to expect that actions are processed by the reducers in the same order that they are dispatched?

Versions:

@angular/cli: 1.0.0-beta.32.3

node: 7.5.0

os: darwin x64

@angular/common: 2.4.7

@angular/compiler: 2.4.7

@angular/core: 2.4.7

@angular/forms: 2.4.7

@angular/http: 2.4.7

@angular/platform-browser: 2.4.7

@angular/platform-browser-dynamic: 2.4.7

@angular/router: 3.4.7

@angular/cli: 1.0.0-beta.32.3

@angular/compiler-cli: 2.4.7

@ngrx/core@1.2.0

@ngrx/effects@2.0.0

@ngrx/store@2.2.1

rxjs: 5.1.1

Body:
It might work to replace your .map in the catch of the START action with a .concatMap and put both your map to SUCCESS and to ACTION there.

@Effect() start$ = this.actions$
    .ofType('START')
    .map(toPayload)
    .switchMap(input => doAsyncTask(input)
        .concatMap(result => {
            return Observable.from([type: 'SUCCESS', payload: result,
                                    type: 'ADVANCE'])
        .catch(error => ({type: 'ERROR', payload: error})));


问:
Five star rating component: How to get rid of all JavaScript code and replace it with only CSS?
I built a five star simple component (to be used for ranking). The component works fine. I used JavaScript to save the result (when user click on a star (which is not shown here) ).

The problem I have is that I didn't found a proper way to simulate the mouseover event (when you pass the mouse over a star and before clicking). So I did it using JavaScript.

Is there a proper way to use only CSS to achieve this (instead of all those JS lines)?

I'm sharing what I already did.

document.getElementById('star1').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
});
document.getElementById('star1').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
});

document.getElementById('star2').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
 document.getElementById('star1').classList.remove("fa-star-o");
 document.getElementById('star1').classList.add("fa-star");
});
document.getElementById('star2').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
 document.getElementById('star1').classList.remove("fa-star");
 document.getElementById('star1').classList.add("fa-star-o");
});

document.getElementById('star3').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
 document.getElementById('star1').classList.remove("fa-star-o");
 document.getElementById('star1').classList.add("fa-star");
 document.getElementById('star2').classList.remove("fa-star-o");
 document.getElementById('star2').classList.add("fa-star");
});
document.getElementById('star3').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
 document.getElementById('star1').classList.remove("fa-star");
 document.getElementById('star1').classList.add("fa-star-o");
 document.getElementById('star2').classList.remove("fa-star");
 document.getElementById('star2').classList.add("fa-star-o");
});

document.getElementById('star4').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
 document.getElementById('star1').classList.remove("fa-star-o");
 document.getElementById('star1').classList.add("fa-star");
 document.getElementById('star2').classList.remove("fa-star-o");
 document.getElementById('star2').classList.add("fa-star");
 document.getElementById('star3').classList.remove("fa-star-o");
 document.getElementById('star3').classList.add("fa-star");
});
document.getElementById('star4').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
 document.getElementById('star1').classList.remove("fa-star");
 document.getElementById('star1').classList.add("fa-star-o");
 document.getElementById('star2').classList.remove("fa-star");
 document.getElementById('star2').classList.add("fa-star-o");
 document.getElementById('star3').classList.remove("fa-star");
 document.getElementById('star3').classList.add("fa-star-o");
});

document.getElementById('star5').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
 document.getElementById('star1').classList.remove("fa-star-o");
 document.getElementById('star1').classList.add("fa-star");
 document.getElementById('star2').classList.remove("fa-star-o");
 document.getElementById('star2').classList.add("fa-star");
 document.getElementById('star3').classList.remove("fa-star-o");
 document.getElementById('star3').classList.add("fa-star");
 document.getElementById('star4').classList.remove("fa-star-o");
 document.getElementById('star4').classList.add("fa-star");
});
document.getElementById('star5').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
 document.getElementById('star1').classList.remove("fa-star");
 document.getElementById('star1').classList.add("fa-star-o");
 document.getElementById('star2').classList.remove("fa-star");
 document.getElementById('star2').classList.add("fa-star-o");
 document.getElementById('star3').classList.remove("fa-star");
 document.getElementById('star3').classList.add("fa-star-o");
 document.getElementById('star4').classList.remove("fa-star");
 document.getElementById('star4').classList.add("fa-star-o");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.content > span > i{
    font-size: 50px;
    margin-right: 10px;
    color: #f0d124;
 cursor: pointer;
}
#star1:hover #star1{
 /*an example: I don't know what to do here???*/
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

```

答:
This demo uses radio buttons for the "sticking" feature. A click will keep selected star(s) highlighted, but it will only persist until the page is reloaded of course. Note: if there is a partial selection of stars we can hover over the remaining unselected stars and the hover effect still works properly.

Details commented in demo

Demo

<!DOCTYPE html>

  <meta charset="utf-8">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

    <fieldset class='set'>
      <legend>Rate It</legend>
      <input id="rad5" class="rad" name="rad" type="radio">

      <input id="rad4" class="rad" name="rad" type="radio">

      <input id="rad3" class="rad" name="rad" type="radio">

      <input id="rad2" class="rad" name="rad" type="radio">

      <input id="rad1" class="rad" name="rad" type="radio">

    </fieldset>

```

Body:
I built a five star simple component (to be used for ranking). The component works fine. I used JavaScript to save the result (when user click on a star (which is not shown here) ).

The problem I have is that I didn't found a proper way to simulate the mouseover event (when you pass the mouse over a star and before clicking). So I did it using JavaScript.

Is there a proper way to use only CSS to achieve this (instead of all those JS lines)?

I'm sharing what I already did.

document.getElementById('star1').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
});
document.getElementById('star1').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
});

document.getElementById('star2').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
 document.getElementById('star1').classList.remove("fa-star-o");
 document.getElementById('star1').classList.add("fa-star");
});
document.getElementById('star2').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
 document.getElementById('star1').classList.remove("fa-star");
 document.getElementById('star1').classList.add("fa-star-o");
});

document.getElementById('star3').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
 document.getElementById('star1').classList.remove("fa-star-o");
 document.getElementById('star1').classList.add("fa-star");
 document.getElementById('star2').classList.remove("fa-star-o");
 document.getElementById('star2').classList.add("fa-star");
});
document.getElementById('star3').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
 document.getElementById('star1').classList.remove("fa-star");
 document.getElementById('star1').classList.add("fa-star-o");
 document.getElementById('star2').classList.remove("fa-star");
 document.getElementById('star2').classList.add("fa-star-o");
});

document.getElementById('star4').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
 document.getElementById('star1').classList.remove("fa-star-o");
 document.getElementById('star1').classList.add("fa-star");
 document.getElementById('star2').classList.remove("fa-star-o");
 document.getElementById('star2').classList.add("fa-star");
 document.getElementById('star3').classList.remove("fa-star-o");
 document.getElementById('star3').classList.add("fa-star");
});
document.getElementById('star4').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
 document.getElementById('star1').classList.remove("fa-star");
 document.getElementById('star1').classList.add("fa-star-o");
 document.getElementById('star2').classList.remove("fa-star");
 document.getElementById('star2').classList.add("fa-star-o");
 document.getElementById('star3').classList.remove("fa-star");
 document.getElementById('star3').classList.add("fa-star-o");
});

document.getElementById('star5').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
 document.getElementById('star1').classList.remove("fa-star-o");
 document.getElementById('star1').classList.add("fa-star");
 document.getElementById('star2').classList.remove("fa-star-o");
 document.getElementById('star2').classList.add("fa-star");
 document.getElementById('star3').classList.remove("fa-star-o");
 document.getElementById('star3').classList.add("fa-star");
 document.getElementById('star4').classList.remove("fa-star-o");
 document.getElementById('star4').classList.add("fa-star");
});
document.getElementById('star5').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
 document.getElementById('star1').classList.remove("fa-star");
 document.getElementById('star1').classList.add("fa-star-o");
 document.getElementById('star2').classList.remove("fa-star");
 document.getElementById('star2').classList.add("fa-star-o");
 document.getElementById('star3').classList.remove("fa-star");
 document.getElementById('star3').classList.add("fa-star-o");
 document.getElementById('star4').classList.remove("fa-star");
 document.getElementById('star4').classList.add("fa-star-o");
});

.content > span > i{
    font-size: 50px;
    margin-right: 10px;
    color: #f0d124;
 cursor: pointer;
}
#star1:hover #star1{
 /*an example: I don't know what to do here???*/
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

Body:
This demo uses radio buttons for the "sticking" feature. A click will keep selected star(s) highlighted, but it will only persist until the page is reloaded of course. Note: if there is a partial selection of stars we can hover over the remaining unselected stars and the hover effect still works properly.

Details commented in demo

Demo

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
  <style>
    body {
      color: #FFB300;
      background: #000;
      font: 700 16px/1.5 Verdana;
    }

    .rating {
      font-size: 0;
    }

    .set {
      display: inline-block;
      font-size: 1rem;
      border: 1px solid #FC0;
    }

    .set:after {
      content: "";
      display: table;
      clear: both;
    }

    .star {
      float: right;
      padding-left: 2px;
      cursor: pointer;
      color: #FFB300;
    }

    .star:last-child {
      padding-left: 0;
    }

    .rad {
      display: none;
    }
    /* 1. hover over a label.star directly and display
    ||    the full gold star in the ::before pseudo
    ||    element.
    */
    /* 2. hover over a label.star and display it and all
    ||    other label.star before it as a full gold star
    */
    /* 3. check a label.star and display it and all other
    ||    label.star before it as a full gold star.
    ||    Full persistent empty stars are possible because
    ||    of the :checked pseudo-selector
    */
    .star:hover:before,
    .star:hover~.star:before,
    .rad:checked~.star:before {
      content: "\f005";
    }
  </style>
</head>

<body>
  <section id="rating">
    <fieldset class='set'>
      <legend>Rate It</legend>
      <input id="rad5" class="rad" name="rad" type="radio">
      <label for="rad5" class="star fa fa-star-o fa-lg"></label>
      <input id="rad4" class="rad" name="rad" type="radio">
      <label for="rad4" class="star fa fa-star-o fa-lg"></label>
      <input id="rad3" class="rad" name="rad" type="radio">
      <label for="rad3" class="star fa fa-star-o fa-lg"></label>
      <input id="rad2" class="rad" name="rad" type="radio">
      <label for="rad2" class="star fa fa-star-o fa-lg"></label>
      <input id="rad1" class="rad" name="rad" type="radio">
      <label for="rad1" class="star fa fa-star-o fa-lg"></label>
    </fieldset>
  </section>
</body>

</html>


问:
Find an exact text inside an string with MySQL
I have a database table with two columns, one for the ID and another one for Colors. Imagine that I have 3 lines in this table with the following data:

```<code>ID: 1 => Colors: Blue; Yellow; Red;
ID: 2 => Colors: Green; GreenYellow; Yellowgreen; Blue;
ID: 3 => Colors: Yellow; Blue;
</code>```

If I want to make a SQL call to know if there is a register with yellow color (just Yellow, no GreenYellow or Yellowgreen). How can I do it? I´m trying with:

```<code>$statement = $conexion->prepare("SELECT * FROM comentarios  WHERE suscritos LIKE :suscritos");
$statement->execute(array(":suscritos" => "%Yellow%"));
$todos_mis_mensajes = $statement->fetchAll();
</code>```

IDs results: 1, 2 and 3

```<code> $statement = $conexion->prepare("SELECT * FROM comentarios  WHERE suscritos LIKE :suscritos");
 $statement->execute(array(":suscritos" => "%Yellow_"));
 $todos_mis_mensajes = $statement->fetchAll();
</code>```

IDs results: No result

```<code>$statement = $conexion->prepare("SELECT * FROM comentarios  WHERE suscritos LIKE :suscritos");
$statement->execute(array(":suscritos" => "_Yellow%"));
$todos_mis_mensajes = $statement->fetchAll();
</code>```

IDs results: 3

答:
Try this call:

```<code>select * from comentarios where suscritos regexp '[[:<:]]Yellow[[:>:]]';
</code>```

Find more here about MySQL regular expressions:
https://dev.mysql.com/doc/refman/5.7/en/regexp.html

Body:
I have a database table with two columns, one for the ID and another one for Colors. Imagine that I have 3 lines in this table with the following data:

ID: 1 => Colors: Blue; Yellow; Red;
ID: 2 => Colors: Green; GreenYellow; Yellowgreen; Blue;
ID: 3 => Colors: Yellow; Blue;

If I want to make a SQL call to know if there is a register with yellow color (just Yellow, no GreenYellow or Yellowgreen). How can I do it? I´m trying with:

$statement = $conexion->prepare("SELECT * FROM comentarios  WHERE suscritos LIKE :suscritos");
$statement->execute(array(":suscritos" => "%Yellow%"));
$todos_mis_mensajes = $statement->fetchAll();

IDs results: 1, 2 and 3

 $statement = $conexion->prepare("SELECT * FROM comentarios  WHERE suscritos LIKE :suscritos");
 $statement->execute(array(":suscritos" => "%Yellow_"));
 $todos_mis_mensajes = $statement->fetchAll();

IDs results: No result

$statement = $conexion->prepare("SELECT * FROM comentarios  WHERE suscritos LIKE :suscritos");
$statement->execute(array(":suscritos" => "_Yellow%"));
$todos_mis_mensajes = $statement->fetchAll();

IDs results: 3

Body:
Try this call:

select * from comentarios where suscritos regexp '[[:<:]]Yellow[[:>:]]';

Find more here about MySQL regular expressions:
https://dev.mysql.com/doc/refman/5.7/en/regexp.html


问:
How to set some spaces before a link without moving the link position?
I need to higlight a div 5 pixels before its current position on mouse over. That is to say if the user passes the pointer over it the div would be highlighted 5 pixels before, but without changing its content position.

.container {
  width: 100%;
  &:hover {
    background-color: rgba(0, 0, 0, 0.1);
    position: relative;
    padding-left: 5px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
  Click me!
</div></code>```

On mouse over it highlights but the "Click me!" message moves 5 pixels to the right. How can I achieve this?

答: Use the outline property. This is literally the use case it is meant for. It improves accessibility. For more info read http://www.outlinenone.com

Body:
I need to higlight a div 5 pixels before its current position on mouse over. That is to say if the user passes the pointer over it the div would be highlighted 5 pixels before, but without changing its content position.

.container {
  width: 100%;
  &:hover {
    background-color: rgba(0, 0, 0, 0.1);
    position: relative;
    padding-left: 5px;
  }
}

  Click me!

On mouse over it highlights but the "Click me!" message moves 5 pixels to the right. How can I achieve this?


答:
Your problem seems indeed to be with your condition.

```<code>!this.props.collection.ids && this.props.collection.ids.length < 1
</code>```

!this.props.collection.ids is only true when the array is falsy. However, an empty array is not falsy - it's truthy.

this.props.collection.ids.length < 1 is true when the array is empty.

Since you are doing && you require the array to be falsy and empty at the same time, which can never happen.

So simply change the condition from && to ||  and it should work. In other words:

```<code>!this.props.collection.ids || this.props.collection.ids.length < 1
</code>```

though I think this is prettier:

```<code>!this.props.collection.ids || !this.props.collection.ids.length
</code>```

Title: Inline if-else with conditional operator not working React

Body:
I've been struggeling with this basic stuff for a while now, but I cant seem to get it to work.

I'm getting data from our backend and if there're any deliveries objects it will be displayed with this:

<Expandable>
  <ObjectDisplay
    key={id}
    parentDocumentId={id}
    schema={schema[this.props.schema.collectionName]}
    value={this.props.collection.documents[id]}
  />
</Expandable>

But if there is no deliveries I'd like to display a message like there's no deliveries. I can use .length and !deliveries (I get that), but it seems like my conditional isn't working:

render() {
  console.log(this.props.collection.ids.length) //Getting how many deliveries there are with their id
  return (

//Struggling with this:

      {!this.props.collection.ids && this.props.collection.ids.length < 1
        ?
No deliviers

        :

            {this.props.collection.ids
              .filter(
                id =>
                  // note: this is only passed when in top level of document
                  this.props.collection.documents[id][
                    this.props.schema.foreignKey
                  ] === this.props.parentDocumentId
              )
              .map(id => {
                return (
                  <Expandable>
                    <ObjectDisplay
                      key={id}
                      parentDocumentId={id}
                      schema={schema[this.props.schema.collectionName]}
                      value={this.props.collection.documents[id]}
                    />
                  </Expandable>
                )
              })}

}

  )
}

I bet my problem is super basic, but I just can't get it to work.. Help is much appreciated!!

Body:
Your problem seems indeed to be with your condition.

!this.props.collection.ids && this.props.collection.ids.length < 1

!this.props.collection.ids is only true when the array is falsy. However, an empty array is not falsy - it's truthy.

this.props.collection.ids.length < 1 is true when the array is empty.

Since you are doing && you require the array to be falsy and empty at the same time, which can never happen.

So simply change the condition from && to ||  and it should work. In other words:

!this.props.collection.ids || this.props.collection.ids.length < 1

though I think this is prettier:

!this.props.collection.ids || !this.props.collection.ids.length


问:
Saving small strings of data on local storage on android studio
I am trying to make a projects which reminds users  for their vaccines. I have made some progress and have created birth date forms using EditText. I just can't seem to find how to save those strings to a file so when the user closes the app they are saved. Here is the code. There are two activities. I am trying to save dita1 muaji 1 and viti1 which are on the second activity.

---------------------------------First Activity----------------------------------------------------------------------------------

```<code>package al.programming.erlisciko.vaksinimi;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MyVaccines extends AppCompatActivity {

    public Button vendosni_ditelindjen;

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

    public void OnClickButtonListener(){
        vendosni_ditelindjen = (Button)findViewById(R.id.vendosni_ditelindjen);
        vendosni_ditelindjen.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent set = new Intent ("al.programming.erlisciko.vaksinimi.SetDate");
                                startActivity(set);
                    }
                }
        );

    }
}
</code>```

----------------------------Second Activity-------------------------------------

```<code>package al.programming.erlisciko.vaksinimi;

import android.app.DatePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class SetDate extends AppCompatActivity {
    public Button ruani;
    public EditText dita, muaji, viti;
    public String dita1, muaji1, viti1;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_date);

        ruani = (Button)findViewById(R.id.ruani);
        dita   = (EditText)findViewById(R.id.dita);
        muaji   = (EditText)findViewById(R.id.muaji);
        viti  = (EditText)findViewById(R.id.viti);

        ruani.setOnClickListener(new View.OnClickListener(){
            public void onClick(View view){
                Log.v("dita1", dita.getText().toString());
                Log.v("muaji1", muaji.getText().toString());
                Log.v("viti1", viti.getText().toString());
            }
        });
        System.out.print(dita1);

    }
}
</code>```

-------------------------------XML 1--------------------------------------------

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="al.programming.erlisciko.vaksinimi.MyVaccines">

    <Button
        android:id="@+id/vendosni_ditelindjen"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        android:text="Vendosni Ditëlindjen"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_bias="0.481"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"
        app:layout_constraintVertical_bias="0.984" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ju lutem vendosni ditëlindjen"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

--------------------------------XML 2-------------------------------------------

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="al.programming.erlisciko.vaksinimi.SetDate">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Vendosni Ditëlindjen"
        android:textAlignment="center"
        android:textSize="24sp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="16dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.497" />

    <EditText
        android:id="@+id/dita"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="Dita"
        android:inputType="date"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.229" />

    <EditText
        android:id="@+id/muaji"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="Muaji"
        android:inputType="date"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.431" />

    <EditText
        android:id="@+id/viti"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="Viti"
        android:inputType="date"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.647" />

    <Button
        android:id="@+id/ruani"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:text="Ruani Datën"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.914" />

</android.support.constraint.ConstraintLayout>
</code>```

Thank You

答:
If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences

Write to Shared Preferences

```<code>SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("Name", yourname);
editor.commit();
</code>```

Read from Shared Preferences

```<code>SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String name = sharedPref.getString("Name", "");
</code>```

Body:
I am trying to make a projects which reminds users  for their vaccines. I have made some progress and have created birth date forms using EditText. I just can't seem to find how to save those strings to a file so when the user closes the app they are saved. Here is the code. There are two activities. I am trying to save dita1 muaji 1 and viti1 which are on the second activity.

---------------------------------First Activity----------------------------------------------------------------------------------

package al.programming.erlisciko.vaksinimi;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MyVaccines extends AppCompatActivity {

    public Button vendosni_ditelindjen;

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

    public void OnClickButtonListener(){
        vendosni_ditelindjen = (Button)findViewById(R.id.vendosni_ditelindjen);
        vendosni_ditelindjen.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent set = new Intent ("al.programming.erlisciko.vaksinimi.SetDate");
                                startActivity(set);
                    }
                }
        );

    }
}

----------------------------Second Activity-------------------------------------

package al.programming.erlisciko.vaksinimi;

import android.app.DatePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class SetDate extends AppCompatActivity {
    public Button ruani;
    public EditText dita, muaji, viti;
    public String dita1, muaji1, viti1;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_date);

        ruani = (Button)findViewById(R.id.ruani);
        dita   = (EditText)findViewById(R.id.dita);
        muaji   = (EditText)findViewById(R.id.muaji);
        viti  = (EditText)findViewById(R.id.viti);

        ruani.setOnClickListener(new View.OnClickListener(){
            public void onClick(View view){
                Log.v("dita1", dita.getText().toString());
                Log.v("muaji1", muaji.getText().toString());
                Log.v("viti1", viti.getText().toString());
            }
        });
        System.out.print(dita1);

    }
}

-------------------------------XML 1--------------------------------------------

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="al.programming.erlisciko.vaksinimi.MyVaccines">

    <Button
        android:id="@+id/vendosni_ditelindjen"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        android:text="Vendosni Ditëlindjen"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_bias="0.481"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"
        app:layout_constraintVertical_bias="0.984" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ju lutem vendosni ditëlindjen"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent" />

</android.support.constraint.ConstraintLayout>

--------------------------------XML 2-------------------------------------------

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="al.programming.erlisciko.vaksinimi.SetDate">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Vendosni Ditëlindjen"
        android:textAlignment="center"
        android:textSize="24sp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="16dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.497" />

    <EditText
        android:id="@+id/dita"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="Dita"
        android:inputType="date"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.229" />

    <EditText
        android:id="@+id/muaji"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="Muaji"
        android:inputType="date"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.431" />

    <EditText
        android:id="@+id/viti"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="Viti"
        android:inputType="date"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.647" />

    <Button
        android:id="@+id/ruani"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:text="Ruani Datën"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.914" />

</android.support.constraint.ConstraintLayout>

Thank You

Body:
If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences

Write to Shared Preferences

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("Name", yourname);
editor.commit();

Read from Shared Preferences

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String name = sharedPref.getString("Name", "");


问:
How can I write a UTF-8-encoded file to the user’s computer using JavaScript on IE?
I am writing a local file using JavaScript and I am using IE for the same.

My code is as follows:

```<code>function savefile( f,g){

var w = window.frames.w;
if( !w ) {
    w = document.createElement( 'iframe' );
    w.id = 'w';
    w.style.display = 'none';
    document.body.insertBefore( w );
    w = window.frames.w;
    if( !w ) {
        w = window.open( '', '_temp', 'width=100,height=100' );
        if( !w ) {
            window.alert( 'Sorry, could not create file.' );
            return false;
        }
    }
}

var d = w.document;
d.open( 'text/xml', 'replace');
d.charset = "UTF-8";

d.write(JWPFormToHTML(f));
d.close();
var name= g.filename.value;

if( d.execCommand( 'SaveAs', false , name ) )
{
    g.filename.value=name;
    //document.getElementById("filename").value="";
    alert('File has been saved.' );
}
else
{
    alert( 'The file has not been saved.\nIs there a problem?' );
}
w.close();
return false;
}
</code>```

The problem I am facing is the file is not getting saved as a UTF-8 encoded file, although I have added <meta http-equiv='Content-Type' content='text/html; charset=utf-8'> to it.

Please help me on this or suggest some alternative to me.

NOTE: I would like a file manager to open before the file gets saved as in the case of execCommand.

答:
Most likely you have an issue with the fact that Windows typically encodes unicode at utf-16 and the browser doesn't care to consider any alternative.

You could go the ActiveX route, The FileSystemObject supports a unicode format flag for text streams but I'd wager it's the same 16 encoding.  The ADODB.Stream object however contains a charset property which can be set to a variety of formats including utf-8

http://msdn.microsoft.com/en-us/library/ms526296(v=exchg.10).aspx

Outside of that I think your best bet would be to write a bho or have the specs changed.  You will of course need higher permissions manually changed in the browser, but maybe you're lucky and this is an intranet application :D

```<code>
    var adTypeBinary = 1;
    var adTypeText = 2;
    var adSaveCreateOverwrite = 2;
    var stream = new ActiveXObject("ADODB.Stream");
        stream.Type = adTypeText;
        stream.Charset = "utf-8";
        stream.Open();
        stream.Write(txt);
        stream.SaveToFile(path, adSaveCreateOverwrite);
</code>```

(*this code was not tested, for example only)

Body:
I am writing a local file using JavaScript and I am using IE for the same.

My code is as follows:

function savefile( f,g){

var w = window.frames.w;
if( !w ) {
    w = document.createElement( 'iframe' );
    w.id = 'w';
    w.style.display = 'none';
    document.body.insertBefore( w );
    w = window.frames.w;
    if( !w ) {
        w = window.open( '', '_temp', 'width=100,height=100' );
        if( !w ) {
            window.alert( 'Sorry, could not create file.' );
            return false;
        }
    }
}

var d = w.document;
d.open( 'text/xml', 'replace');
d.charset = "UTF-8";

d.write(JWPFormToHTML(f));
d.close();
var name= g.filename.value;

if( d.execCommand( 'SaveAs', false , name ) )
{
    g.filename.value=name;
    //document.getElementById("filename").value="";
    alert('File has been saved.' );
}
else
{
    alert( 'The file has not been saved.\nIs there a problem?' );
}
w.close();
return false;
}

The problem I am facing is the file is not getting saved as a UTF-8 encoded file, although I have added <meta http-equiv='Content-Type' content='text/html; charset=utf-8'> to it.

Please help me on this or suggest some alternative to me.

NOTE: I would like a file manager to open before the file gets saved as in the case of execCommand.

Body:
Most likely you have an issue with the fact that Windows typically encodes unicode at utf-16 and the browser doesn't care to consider any alternative.

You could go the ActiveX route, The FileSystemObject supports a unicode format flag for text streams but I'd wager it's the same 16 encoding.  The ADODB.Stream object however contains a charset property which can be set to a variety of formats including utf-8

http://msdn.microsoft.com/en-us/library/ms526296(v=exchg.10).aspx

Outside of that I think your best bet would be to write a bho or have the specs changed.  You will of course need higher permissions manually changed in the browser, but maybe you're lucky and this is an intranet application :D

    var adTypeBinary = 1;
    var adTypeText = 2;
    var adSaveCreateOverwrite = 2;
    var stream = new ActiveXObject("ADODB.Stream");
        stream.Type = adTypeText;
        stream.Charset = "utf-8";
        stream.Open();
        stream.Write(txt);
        stream.SaveToFile(path, adSaveCreateOverwrite);

(*this code was not tested, for example only)


问:
How to initiate a function using data(){} but not mounted(){} while using vue-resource
This works, but I need to use mounted(){} to initiate the function which I think can be avoided but not sure how.

```<code><script>
  export default {
    data () {
      return {
        domains: [],
      }
    },

    methods: {
      fetchDomains() {
        let _this = this;

        api._get({url: 'api/domains'})
          .then(function (response) {
            _this.domains = response.data;
          })
      }
    },

    mounted() {
      this.fetchDomains()
    }
  }
</script>
</code>```

This code doesn't work, but I like to do something like this. Initiating the function in data(){} itself.

```<code><script>
  export default {
    data () {
      return {
        domains: this.fetchDomains(),
      }
    },

    methods: {
      fetchDomains() {
        let data = [];

        api._get({url: 'api/domains'})
          .then(function (response) {
            data = response.data;
          })

        return data
      }
    }
  }
</script>
</code>```

Thanks in advance.

答:
Your first code snippet is the correct way to do it.

You can't initialize domains with the data from the API response because it is an async operation which may or may not be resolved successfully at some point in the future, well after the component is mounted. You might also want to do other things like keeping track of the async operation with a loading property which you set to true for the duration of the request.

Your component will initially be in a loading state which does not yet have any domains data, and you need to account for this. Show a loading spinner or something during this time.

Body:
This works, but I need to use mounted(){} to initiate the function which I think can be avoided but not sure how.

This code doesn't work, but I like to do something like this. Initiating the function in data(){} itself.

Thanks in advance.


问:
jQuery highlighting clicked list item
When I clicked on list item it is highlighting only one. If list item has sub list then the total sub list is also highlighting but only one list should be highlight.

CSS

```<code>.active {
  background: #f00;
}
</code>```

HTML

```<code><ul id="orgCat">
  <li class="list-group-item active">Cras justo odio</li>
  <li class="list-group-item">Dapibus ac facilisis in</li>
  <li class="list-group-item">Morbi leo risus
    <ul>
    <li>abc</li>
    <li>sdf</li>
    <li>oupu
      <ul>
      <li>progf</li>
      <li>ghfhg</li>
      </ul>
    </li>
    </ul>
  </li>
  <li class="list-group-item">Porta ac consectetur ac</li>
  <li class="list-group-item">Vestibulum at eros</li>
  <li class="list-group-item">Cras justo odio</li>
  <li class="list-group-item">Dapibus ac facilisis in</li>
  <li class="list-group-item">Morbi leo risus</li>
  <li class="list-group-item">Porta ac consectetur ac</li>
  <li class="list-group-item">Vestibulum at eros</li>
</ul>
</code>```

JQUERY

```<code>$('#orgCat li').click(function(e) {
    e.preventDefault()

    $that = $(this);

    $that.parent().find('li').removeClass('active');
    $that.addClass('active');
  });
</code>```

Demo

答:
You can use  tag in li

HTML:

```<code> <ul id="orgCat">
  <li class="list-group-item"><span class='active'>Cras justo odio</span></li>
  <li class="list-group-item"><span>Dapibus ac facilisis in</span></li>
  <li class="list-group-item"><span>Morbi leo risus</span>
    <ul>
    <li><span>abc</span></li>
    <li><span>sdf</span></li>
    <li>oupu
      <ul>
      <li><span>progf</span></li>
      <li><span>ghfhg</span></li>
      </ul>
    </li>
    </ul>
  </li>
  <li class="list-group-item"><span>Porta ac consectetur ac</span></li>
  <li class="list-group-item"><span>Vestibulum at eros</span></li>
  <li class="list-group-item"><span>Cras justo odio</span></li>
  <li class="list-group-item"><span>Dapibus ac facilisis in</span></li>
  <li class="list-group-item"><span>Morbi leo risus</span></li>
  <li class="list-group-item"><span>Porta ac consectetur ac</span></li>
  <li class="list-group-item"><span>Vestibulum at eros</span></li>
</ul>
</code>```

jQuery:

```<code> $('#orgCat li span').click(function(e) {
    e.preventDefault();
    $that = $(this);
   $('li span').removeClass('active');
    $that.addClass('active');
  });
</code>```

ContentLicense: CC BY-SA 4.0

Title: jQuery highlighting clicked list item

Body:
When I clicked on list item it is highlighting only one. If list item has sub list then the total sub list is also highlighting but only one list should be highlight.

CSS

.active {
  background: #f00;
}

HTML

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

abc

sdf

oupu

progf

ghfhg

Porta ac consectetur ac

Vestibulum at eros

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Vestibulum at eros

JQUERY

$('#orgCat li').click(function(e) {
    e.preventDefault()

    $that = $(this);

    $that.parent().find('li').removeClass('active');
    $that.addClass('active');
  });

Demo

Body:
You can use <span> tag in li

HTML:

 <ul id="orgCat">
  <li class="list-group-item"><span class='active'>Cras justo odio</span></li>
  <li class="list-group-item"><span>Dapibus ac facilisis in</span></li>
  <li class="list-group-item"><span>Morbi leo risus</span>
    <ul>
    <li><span>abc</span></li>
    <li><span>sdf</span></li>
    <li>oupu
      <ul>
      <li><span>progf</span></li>
      <li><span>ghfhg</span></li>
      </ul>
    </li>
    </ul>
  </li>
  <li class="list-group-item"><span>Porta ac consectetur ac</span></li>
  <li class="list-group-item"><span>Vestibulum at eros</span></li>
  <li class="list-group-item"><span>Cras justo odio</span></li>
  <li class="list-group-item"><span>Dapibus ac facilisis in</span></li>
  <li class="list-group-item"><span>Morbi leo risus</span></li>
  <li class="list-group-item"><span>Porta ac consectetur ac</span></li>
  <li class="list-group-item"><span>Vestibulum at eros</span></li>
</ul>

jQuery:

 $('#orgCat li span').click(function(e) {
    e.preventDefault();
    $that = $(this);
   $('li span').removeClass('active');
    $that.addClass('active');
  });


问:
Create a new table using existing tables and remove duplicates
Hi I have two tables with a column that has phone numbers and several other columns.  There are duplicate phone numbers within each table and duplicates across the two tables.  I'd like to create a new table with only the phone numbers and no duplicate phone numbers in the new table.</p>

答:
Assumptions here as you haven't really asked the question with much thought but;</p>

```<code>create table dbo.Table3
     (
     PhoneNumber varchar(100)
     )
go
insert into dbo.Table3
select
    distinct PhoneNumber
from
    (
    select
        PhoneNumber
    from
        Table1
    union
    select
        PhoneNumber
from
    Table2
)nos
go
</code>```

Body:
Assumptions here as you haven't really asked the question with much thought but;

create table dbo.Table3
     (
     PhoneNumber varchar(100)
     )
go
insert into dbo.Table3
select
    distinct PhoneNumber
from
    (
    select
        PhoneNumber
    from
        Table1
    union
    select
        PhoneNumber
from
    Table2
)nos
go


问:
Variables in Template Haskell custom quasiquoter
An example is worth a thousand words. Here is a pretty simple quasi quoter I just made up.

```<code>import Language.Haskell.TH.Quote
import Language.Haskell.TH.Syntax

quoter :: QuasiQuoter
quoter = QuasiQuoter { quotePat = parse }
  where
    parse :: String -> Q Pat
    parse ('$':x) = pure (VarP (mkName x))
    parse "_" = pure WildP
    parse _ = fail "Invalid pattern"
</code>```

Then, using it in GHCi

```<code>ghci> :set -XQuasiQuotes
ghci> [quoter|_|] = 2
ghci> [quoter|$x|] = 2
ghci> x
error: Variable not in scope: x
</code>```

I would have liked 2 to be bound to x. <s>So: is there any way to introduce variable patterns in custom quasi-quotes that we can use again?</s> Note that my actual use case is a fair bit more involved than the above - parse actual does some substantial work.

EDIT

The following works:

```<code> ghci> inc [quoter|$x|] = x + 1
 ghci> inc 2
 3
</code>```

and the following doesn't

```<code> ghci> let [quoter|$x|] = 1 in x
 error: Variable not in scope: x
</code>```

so is this a bug in GHCi?

答: This is now fixed in GHC 8.2 (see this commit).</p>

Body:
An example is worth a thousand words. Here is a pretty simple quasi quoter I just made up.

import Language.Haskell.TH.Quote
import Language.Haskell.TH.Syntax

quoter :: QuasiQuoter
quoter = QuasiQuoter { quotePat = parse }
  where
    parse :: String -> Q Pat
    parse ('$':x) = pure (VarP (mkName x))
    parse "_" = pure WildP
    parse _ = fail "Invalid pattern"

Then, using it in GHCi

ghci> :set -XQuasiQuotes
ghci> [quoter|_|] = 2
ghci> [quoter|$x|] = 2
ghci> x
error: Variable not in scope: x

I would have liked 2 to be bound to x. <s>So: is there any way to introduce variable patterns in custom quasi-quotes that we can use again?</s> Note that my actual use case is a fair bit more involved than the above - parse actual does some substantial work.

EDIT

The following works:

 ghci> inc [quoter|$x|] = x + 1
 ghci> inc 2
 3

and the following doesn't

 ghci> let [quoter|$x|] = 1 in x
 error: Variable not in scope: x

so is this a bug in GHCi?


问:
Browser-Sidebar for number conversion?
does anyone know a sidebar (or 'panel' like it's called in opera) that I can use for number conversions (decimal to hex and so on)? Currently I'm using this one but it's a bit too large to fit a narrow sidebar.</p>

答:
Since it's just a bit of JavaScript, one can roll it oneself:</p>

```<code><html>
<body>
  <form>
    <input name="dec" id="dec"
       placeholder="decimal"
       onBlur="document.getElementById('hex').value=
           parseInt(this.value,10).toString(16)"
       ></input>
    <br />
    <input name="hex" id="hex"
       placeholder="hex"
       onBlur="document.getElementById('dec').value=
           parseInt(this.value,16).toString(10)"
       ></input>
  </form>
</body>
</html>
</code>```

Title: Browser-Sidebar for number conversion?

Body:
Since it's just a bit of JavaScript, one can roll it oneself:

<html>
<body>
  <form>
    <input name="dec" id="dec"
       placeholder="decimal"
       onBlur="document.getElementById('hex').value=
           parseInt(this.value,10).toString(16)"
       ></input>
    <br />
    <input name="hex" id="hex"
       placeholder="hex"
       onBlur="document.getElementById('dec').value=
           parseInt(this.value,16).toString(10)"
       ></input>
  </form>
</body>
</html>


问:
Truly change a model attribute silently in Backbone.js?
Is there a way I can change attributes on a model without ever firing a change event? If you pass {"silent":true} right now, the next time an attribute is changed, the silent change event will be triggered. Can I change an attribute safely without the change event ever being triggered?

from change, Backbone 0.9.2:

```<code>// Silent changes become pending changes.
for (var attr in this._silent) this._pending[attr] = true;

// Silent changes are triggered.
var changes = _.extend({}, options.changes, this._silent);
this._silent = {};
for (var attr in changes) {
    this.trigger('change:' + attr, this, this.get(attr), options);
</code>```

答:
```<code>item.set(
        {
           sum: sum
          ,income: income
       },
       {silent: true}
    );
</code>```

since backbone 0.9.10

Body:
Is there a way I can change attributes on a model without ever firing a change event? If you pass {"silent":true} right now, the next time an attribute is changed, the silent change event will be triggered. Can I change an attribute safely without the change event ever being triggered?

from change, Backbone 0.9.2:

// Silent changes become pending changes.
for (var attr in this._silent) this._pending[attr] = true;

// Silent changes are triggered.
var changes = _.extend({}, options.changes, this._silent);
this._silent = {};
for (var attr in changes) {
    this.trigger('change:' + attr, this, this.get(attr), options);

Body:
item.set(
        {
           sum: sum
          ,income: income
       },
       {silent: true}
    );

since backbone 0.9.10