问:
Toggle Button in Android
Can anyone help or share a link on how to implement this toggle button in android:

I've tried using this:

```<code><ToggleButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textOn="Active"
                android:textOff="Completed"/>
</code>```

but it's not having the desired output.

It has only one button and it changes when i click on it. What i want is two buttons side by side as shown in the picture above.

答:
Custom Implementation ----

Colors

```<code><color name = "background">#5cc0fa</color>
<color name = "white">#FFFFFF</color>
</code>```

XML layout

```<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"
>

<LinearLayout
    android:id="@+id/linear_layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/background"
    android:orientation="horizontal"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_all"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:textColor="@color/white"
        android:background="@color/background"
        android:text="All" />

    <Button
        android:id="@+id/btn_done"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:textColor="@color/background"
        android:background="@color/white"
        android:text="Done" />

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

Inside Activity

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {

int var = 0;
Button btnAll;
Button btnDone;
LinearLayout linearLayout;

public void toggle() {
    if(var == 0) {
        var = 1;
        btnAll.setBackgroundColor(getResources().getColor(R.color.white));
        btnAll.setTextColor(getResources().getColor(R.color.background));
        btnDone.setBackgroundColor(getResources().getColor(R.color.background));
        btnDone.setTextColor(getResources().getColor(R.color.white));
    } else {
        var = 0;
        btnAll.setBackgroundColor(getResources().getColor(R.color.background));
        btnAll.setTextColor(getResources().getColor(R.color.white));
        btnDone.setBackgroundColor(getResources().getColor(R.color.white));
        btnDone.setTextColor(getResources().getColor(R.color.background));
    }
}

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

    linearLayout = findViewById(R.id.linear_layout);
    btnAll = findViewById(R.id.btn_all);
    btnDone = findViewById(R.id.btn_done);

    linearLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            toggle();
        }
    });

    btnAll.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            toggle();
        }
    });

    btnDone.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            toggle();
        }
    });
}
}
</code>```

Title: Toggle Button in Android

Body:
Can anyone help or share a link on how to implement this toggle button in android:

I've tried using this:

<ToggleButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textOn="Active"
                android:textOff="Completed"/>

but it's not having the desired output.

It has only one button and it changes when i click on it. What i want is two buttons side by side as shown in the picture above.

Body:
Custom Implementation ----

Colors

<color name = "background">#5cc0fa</color>
<color name = "white">#FFFFFF</color>

XML layout

<?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"
>

<LinearLayout
    android:id="@+id/linear_layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/background"
    android:orientation="horizontal"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_all"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:textColor="@color/white"
        android:background="@color/background"
        android:text="All" />

    <Button
        android:id="@+id/btn_done"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:textColor="@color/background"
        android:background="@color/white"
        android:text="Done" />

</LinearLayout>
</android.support.constraint.ConstraintLayout>

Inside Activity

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {

int var = 0;
Button btnAll;
Button btnDone;
LinearLayout linearLayout;

public void toggle() {
    if(var == 0) {
        var = 1;
        btnAll.setBackgroundColor(getResources().getColor(R.color.white));
        btnAll.setTextColor(getResources().getColor(R.color.background));
        btnDone.setBackgroundColor(getResources().getColor(R.color.background));
        btnDone.setTextColor(getResources().getColor(R.color.white));
    } else {
        var = 0;
        btnAll.setBackgroundColor(getResources().getColor(R.color.background));
        btnAll.setTextColor(getResources().getColor(R.color.white));
        btnDone.setBackgroundColor(getResources().getColor(R.color.white));
        btnDone.setTextColor(getResources().getColor(R.color.background));
    }
}

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

    linearLayout = findViewById(R.id.linear_layout);
    btnAll = findViewById(R.id.btn_all);
    btnDone = findViewById(R.id.btn_done);

    linearLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            toggle();
        }
    });

    btnAll.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            toggle();
        }
    });

    btnDone.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            toggle();
        }
    });
}
}


来源: stackexchange

问:
Property not exist in edit User API in Symfony 4
I created the User entity and this is one of the properties of this:

```<code>/**
 * @ORM\Column(type="string", length=50, nullable=true)
 *
 * @Assert\Length(max="50")
 * @Assert\NotNull()
 */
private $firstName;
</code>```

In Api Controller when i want to validate the user or submit form for edit user i will get the error.

the controller:

```<code>public function edit(Request $request, ValidatorInterface $validator)
{
    $user = $this->getUser();
    $validator->validate($this->getUser()); # i get error here
}
</code>```

the error is:

Property \"firstName\" does not exist in class
  \"Proxies\__CG__\App\Entity\User\""

but I have the firstName and I can use getter and setter for that.

答:
You may try this way.</p>

```<code>$user = $this->getUser();
$repository = $this->getDoctrine()->getRepository(YourEntity::class);
$userEntity = $repository->find($user->getId());

$validator->validate($userEntity);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I created the User entity and this is one of the properties of this:

/**
 * @ORM\Column(type="string", length=50, nullable=true)
 *
 * @Assert\Length(max="50")
 * @Assert\NotNull()
 */
private $firstName;

In Api Controller when i want to validate the user or submit form for edit user i will get the error.

the controller:

public function edit(Request $request, ValidatorInterface $validator)
{
    $user = $this->getUser();
    $validator->validate($this->getUser()); # i get error here
}

the error is:

Property \"firstName\" does not exist in class
  \"Proxies\__CG__\App\Entity\User\""

but I have the firstName and I can use getter and setter for that.

Body:
You may try this way.

$user = $this->getUser();
$repository = $this->getDoctrine()->getRepository(YourEntity::class);
$userEntity = $repository->find($user->getId());

$validator->validate($userEntity);


问:
Nuxt + Netlify Forms custom success page not found
I have a simple Form in my Nuxt Project - hosting on Netlify and use the Netlify Forms feature - docs here https://www.netlify.com/docs/form-handling/

```<code>  <form
    action="/confirm" name="request" method="post" data-netlify="true" netlify-honeypot="bot-field"
  >
    <p class="hidden">
      <label>Don’t fill this out if you're human: <input name="bot-field" ></label>
    </p>
    <v-text-field
      label="Name"
      name="name"
    />
    ...
    <v-btn
      :disabled="!valid"
      type="submit"
    >send
    </v-btn>
  </form>
</code>```

If I browse to https://mddomain.com/confirm it works fine.

If I submit the form on the first time I come to the /confirm page but Netlify doesn't safe the data. If i try it again I got this Error Mesage:

Page Not Found
  Looks like you've followed a broken link or entered a URL that doesn't exist on this site.

Back to our site

What's wrong with my code?

答: Check that nuxt.config.js has mode: 'universal' and NOT mode: 'spa'.

Body:
I have a simple Form in my Nuxt Project - hosting on Netlify and use the Netlify Forms feature - docs here https://www.netlify.com/docs/form-handling/

  <form
    action="/confirm" name="request" method="post" data-netlify="true" netlify-honeypot="bot-field"
  >

      Don’t fill this out if you're human: <input name="bot-field" >

    <v-text-field
      label="Name"
      name="name"
    />
    ...
    <v-btn
      :disabled="!valid"
      type="submit"
    >send
    </v-btn>
  </form>

If I browse to https://mddomain.com/confirm it works fine.

If I submit the form on the first time I come to the /confirm page but Netlify doesn't safe the data. If i try it again I got this Error Mesage:

Page Not Found
  Looks like you've followed a broken link or entered a URL that doesn't exist on this site.

Back to our site

What's wrong with my code?


问:
Expect script called from bash script not returning control when completed
I am calling the expect script from bash script inside for loop using multithreading in it. The expect script does ssh login and call python script using nohup command for restarting host.
But, after completing the restart, the control not returned to the bash script.

Shell script code:

```<code>for host in ${hosts[@]};
do
  ./b.exp $id $pswd $host &
done
wait
echo "Completed"
</code>```

Expect script code:

```<code>set timeout -1
spawn ssh <server login>
send "nohup /loc/c.py $host\r"
send -- "exit\r"
expect eof
</code>```

I am expecting after all the hosts restart completion, the script should print "Completed".
But, it is not printing anything and I need to manually exit the execution.

Could someone please tell what wrong I am doing here?

答:
nohup doesn't detach the terminal, you want to send

```<code> nohup /loc/c.py $host &
</code>```

where the & to run the job in the background is the significant change.

(Properly speaking $host should be quoted, too, but if you are sure it contains a single token without whitespace or wildcard characters, this should not matter. Similarly "${hosts[@]}" should have double quotes, but again, under the given conditions, this should be fine without quotes.)

Body:
I am calling the expect script from bash script inside for loop using multithreading in it. The expect script does ssh login and call python script using nohup command for restarting host.
But, after completing the restart, the control not returned to the bash script.

Shell script code:

for host in ${hosts[@]};
do
  ./b.exp $id $pswd $host &
done
wait
echo "Completed"

Expect script code:

set timeout -1
spawn ssh <server login>
send "nohup /loc/c.py $host\r"
send -- "exit\r"
expect eof

I am expecting after all the hosts restart completion, the script should print "Completed".
But, it is not printing anything and I need to manually exit the execution.

Could someone please tell what wrong I am doing here?

Body:
nohup doesn't detach the terminal, you want to send

 nohup /loc/c.py $host &

where the & to run the job in the background is the significant change.

(Properly speaking $host should be quoted, too, but if you are sure it contains a single token without whitespace or wildcard characters, this should not matter. Similarly "${hosts[@]}" should have double quotes, but again, under the given conditions, this should be fine without quotes.)


问:
Super-simple before insert trigger (2 rows) does not work when inserting values into a table
I'm building a trigger which raises an application error if the length of a string is not 16.

```<code>CREATE OR REPLACE TRIGGER lunghezza_CF
before INSERT OR UPDATE ON Persona
FOR each ROW
BEGIN
    IF LENGTH(:NEW.CF) <> 16 THEN
        RAISE_APPLICATION_ERROR(-20002, 'CF length must be 16');
    END IF;
END;
</code>```

The table Persona is composed as follows:

```<code>CF char(16) primary key
...
</code>```

If i write the following statement

```<code>insert into Persona(CF) values('ABC12')
</code>```

For what reason 'ABC12' gets inserted into the table? For some reason my trigger does not work properly, but it seems to be ok...

(Note that LENGTH(string) is an Oracle "built-in" function)

答:
The problem is that you're using the char data type which is blank padded to the length defined and therefore always exactly as long as its definition. You can use trim() to remove blanks.

```<code>CREATE OR REPLACE TRIGGER lunghezza_CF
before INSERT OR UPDATE ON Persona
FOR each ROW
BEGIN
    IF LENGTH(TRIM(:NEW.CF)) <> 16 THEN
        RAISE_APPLICATION_ERROR(-20002, 'CF length must be 16');
    END IF;
END;
</code>```

db<>fiddle

But instead of a trigger, you could also simply use a check constraint for this.

```<code>ALTER TABLE persona
            ADD CHECK (length(trim(cf)) = 16);
</code>```

db<>fiddle

Note, that trim() removes trailing and leading blanks. If you want to count leading blanks you can use rtrim() instead, which just removes trailing blanks.

Body:
I'm building a trigger which raises an application error if the length of a string is not 16.

CREATE OR REPLACE TRIGGER lunghezza_CF
before INSERT OR UPDATE ON Persona
FOR each ROW
BEGIN
    IF LENGTH(:NEW.CF) <> 16 THEN
        RAISE_APPLICATION_ERROR(-20002, 'CF length must be 16');
    END IF;
END;

The table Persona is composed as follows:

CF char(16) primary key
...

If i write the following statement

insert into Persona(CF) values('ABC12')

For what reason 'ABC12' gets inserted into the table? For some reason my trigger does not work properly, but it seems to be ok...

(Note that LENGTH(string) is an Oracle "built-in" function)

Body:
The problem is that you're using the char data type which is blank padded to the length defined and therefore always exactly as long as its definition. You can use trim() to remove blanks.

CREATE OR REPLACE TRIGGER lunghezza_CF
before INSERT OR UPDATE ON Persona
FOR each ROW
BEGIN
    IF LENGTH(TRIM(:NEW.CF)) <> 16 THEN
        RAISE_APPLICATION_ERROR(-20002, 'CF length must be 16');
    END IF;
END;

db<>fiddle

But instead of a trigger, you could also simply use a check constraint for this.

ALTER TABLE persona
            ADD CHECK (length(trim(cf)) = 16);

db<>fiddle

Note, that trim() removes trailing and leading blanks. If you want to count leading blanks you can use rtrim() instead, which just removes trailing blanks.


问:
How to change CPU ID
How do I change my cpu id I know how to get it yet I have no clue how to change it I really need help. Im using this code:</p>

```<code>private string getCPUID()
{
    string cpuInfo = "";
    ManagementClass managClass = new ManagementClass("win32_processor");
    ManagementObjectCollection managCollec = managClass.GetInstances();

    foreach (ManagementObject managObj in managCollec)
    {
        if (cpuInfo == "")
        {
            //Get only the first CPU's ID
            cpuInfo = managObj.Properties["processorID"].Value.ToString();
            break;
        }
    }

    return cpuInfo;
}
</code>```

答:
Per MSDN:

https://learn.microsoft.com/en-us/windows/desktop/cimwin32prov/win32-processor

ProcessorId

Data type: string

Access type: Read-only

This value comes from the Processor ID member of the Processor Information structure in the SMBIOS information.

There's no way to do this from c# code.  The use cases I know for this involve using some sort of VM or Hypervisor solution  that lets you emulate different harware.  This is sometimes helpful for things like a VPN client that enforces  being on physical hardware and not a VM.

Title: How to change CPU ID

Body:
How do I change my cpu id I know how to get it yet I have no clue how to change it I really need help. Im using this code:

private string getCPUID()
{
    string cpuInfo = "";
    ManagementClass managClass = new ManagementClass("win32_processor");
    ManagementObjectCollection managCollec = managClass.GetInstances();

    foreach (ManagementObject managObj in managCollec)
    {
        if (cpuInfo == "")
        {
            //Get only the first CPU's ID
            cpuInfo = managObj.Properties["processorID"].Value.ToString();
            break;
        }
    }

    return cpuInfo;
}


问:
multiple ruby version on my macOS will auto switch version
pre: in my mac, I install rvm and rbenv both set a separate version.

and I look up "brew info ruby" is another version. in the terminal I use "ruby -v" is 2.3.7 is another version that I never set.

last time i use rvm to set default and current version to 2.5.3 it useful. then current that's wasn't work. how I to correct this issue...

brew info ruby => 2.6.3

rvm default and current 2.5.3

rbenv global and local 2.5.3

in terminal $ ruby -v 2.3.7 that's never set

答:
Choose only one of them. You really can not have rbenv and rvm at same time. With rvm, it overrides the 'gem' command, so that would make rbenv useless.

Try this with rbenv:

```<code>echo 'eval "$(rbenv init -)"' >> ~/.bash_profile
</code>```

Then:

```<code>rbenv global 2.5.3
</code>```

Body:
Choose only one of them. You really can not have rbenv and rvm at same time. With rvm, it overrides the 'gem' command, so that would make rbenv useless.

Try this with rbenv:

echo 'eval "$(rbenv init -)"' >> ~/.bash_profile

Then:

rbenv global 2.5.3


问:
How i can get the distance and duration between current location and destination location using Google Maps
I need to calculate the distance between two locations current location of a user and destination location I have the latitude and longitude of the destination.</p>

答:
Unfortunately this question doesn't belong directly to Android though to a Google Map library usable in Android so you may refer here for full details and implementation process:

https://developers.google.com/maps/documentation/distance-matrix/intro


问:
How to use Attributes to control the serialization of a property in C#
I would like to control how a particular class serializes it's data... for example:

```<code>    [TimeSeriesSerialization(TimeSeriesSerializationType.Dates)]
    public TimeSeries DailyValues { get; set; }

    [TimeSeriesSerialization(TimeSeriesSerializationType.Normal)]
    public TimeSeries IntraDayValues { get; set; }
</code>```

In my example here, I have a class called TimeSeries that has a List of DateTimes and a List of decimals... when I serialize it I want to do two things... create a JSON string that is a set of time/value pairs... for example:

```<code>{"2018-01-30T09:30:01":9958.2289,"2018-01-30T09:30:02":9958.2284,...}
</code>```

But I would also like to have the option to serialize this class as Date values (without the time)... as so:

```<code>{"2018-01-30":9958.2289,"2018-01-31":9958.2284,...}
</code>```

Or as only values:

```<code>[9958.2289,9958.2284,...]
</code>```

Any help?

```<code>public enum TimeSeriesSerializationType
{
    Times,
    Dates,
    ValuesOnly,
}

public class TimeSeries
{
    public List<DateTime> Times = new List<DateTime>();
    public List<decimal> Values = new List<decimal>();

    public void Add(DateTime time, decimal value)
    {
        Times.Add(time);
        Values.Add(value);
    }

    public string Serialize(TimeSeriesSerializationType timeSeriesSerializationType)
    {
        switch (timeSeriesSerializationType)
        {
            case TimeSeriesSerializationType.Dates:
                {
                    var data = new Dictionary<DateTime, decimal>();
                    for (var i = 0; i < Times.Count; i++)
                    {
                        if (!data.ContainsKey(Times[i])) // duplicate dates???
                            data.Add(Times[i], Values[i]);
                    }
                    var isoDateTimeConverter = new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd" };
                    var json = JsonConvert.SerializeObject(data, Formatting.None, isoDateTimeConverter);
                    return json;
                }
            case TimeSeriesSerializationType.ValuesOnly:
                {
                    var json = JsonConvert.SerializeObject(Values, Formatting.None);
                    return json;
                }
            default:
                {
                    var data = new Dictionary<DateTime, decimal>();
                    for (var i = 0; i < Times.Count; i++)
                    {
                        if (!data.ContainsKey(Times[i])) // duplicate times???
                            data.Add(Times[i], Values[i]);
                    }
                    var isoDateTimeConverter = new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz" };
                    var json = JsonConvert.SerializeObject(data, Formatting.None, isoDateTimeConverter);
                    return json;
                }
        }
    }

    public void Deserialize(string str)
    {
        if (string.IsNullOrEmpty(str)) return;
        var data = JsonConvert.DeserializeObject<Dictionary<DateTime, decimal>>(str);
        if (data.Count <= 0) return;
        foreach (var d in data)
            this.Add(d.Key, d.Value);
    }
}
</code>```

答:
I think you already have most of what you need.

What's missing is the attribute itself.

You'd define it like this (you can read more about the AttributeUsage-Attribute here):

```<code>[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
class TimeSeriesSerializationAttribute : Attribute
{
    public TimeSeriesSerializationType SerializationType { get; }

    public TimeSeriesSerializationAttribute(TimeSeriesSerializationType timeSeriesSerializationType)
    {
        SerializationType = timeSeriesSerializationType;
    }
}
</code>```

Now you can add those above your properties just like you already wrote.

Time for the evaluation part. You can use something like this to read all the properties and use them to serialize your TimeSeries.

By the way if the attribute you get turns out as null, the attribute just isn't set. You can either skip the property entirely or use a default SerializationType, whatever you need/want.

```<code>public static void SerializeToSomewhere(YourClassWithTimeSeries instance) {
    // get all public, instance properties
    IEnumerable<PropertyInfo> allProps = typeof(YourClassWithTimeSeries).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    // only take TimeSeries-properties
    IEnumerable<PropertyInfo> timeSeriesProps = allProps.Where(p => p.PropertyType == typeof(TimeSeries));

    foreach (PropertyInfo property in timeSeriesProps)
    {
        // get the attribute
        TimeSeriesSerializationAttribute attribute = property.GetCustomAttribute<TimeSeriesSerializationAttribute>();
        if (attribute == null) continue; // or do something else like use a default SerializationType

        // get the value
        TimeSeries value = (TimeSeries)property.GetValue(instance, null);

        // serialize using the type from the attribute
        string serializedValue = value.Serialize(attribute.SerializationType);
        // Do whatever with the serialized value (for example save it to a file or whatever)
    }
}
</code>```

Hope this helps you. There are also plenty of attribute tutorials and docs if you need additional information. I'll also try to answer questions you might have so feel free to ask.

Edit:

Small thing to add. In your code your TimeSeries-class exposes the public fields Times and Values. You shouldn't do that.
Instead of doing this:

```<code>public List<DateTime> Times = new List<DateTime>();
public List<decimal> Values = new List<decimal>();
</code>```

You should do this. It stops you from accidentally assigning it again from within or outside the class.

```<code>public List<DateTime> Times { get; } = new List<DateTime>();
public List<decimal> Values { get; } = new List<decimal>();
</code>```

Body:
I would like to control how a particular class serializes it's data... for example:

    [TimeSeriesSerialization(TimeSeriesSerializationType.Dates)]
    public TimeSeries DailyValues { get; set; }

    [TimeSeriesSerialization(TimeSeriesSerializationType.Normal)]
    public TimeSeries IntraDayValues { get; set; }

In my example here, I have a class called TimeSeries that has a List of DateTimes and a List of decimals... when I serialize it I want to do two things... create a JSON string that is a set of time/value pairs... for example:

{"2018-01-30T09:30:01":9958.2289,"2018-01-30T09:30:02":9958.2284,...}

But I would also like to have the option to serialize this class as Date values (without the time)... as so:

{"2018-01-30":9958.2289,"2018-01-31":9958.2284,...}

Or as only values:

[9958.2289,9958.2284,...]

Any help?

public enum TimeSeriesSerializationType
{
    Times,
    Dates,
    ValuesOnly,
}

public class TimeSeries
{
    public List<DateTime> Times = new List<DateTime>();
    public List<decimal> Values = new List<decimal>();

    public void Add(DateTime time, decimal value)
    {
        Times.Add(time);
        Values.Add(value);
    }

    public string Serialize(TimeSeriesSerializationType timeSeriesSerializationType)
    {
        switch (timeSeriesSerializationType)
        {
            case TimeSeriesSerializationType.Dates:
                {
                    var data = new Dictionary<DateTime, decimal>();
                    for (var i = 0; i < Times.Count; i++)
                    {
                        if (!data.ContainsKey(Times[i])) // duplicate dates???
                            data.Add(Times[i], Values[i]);
                    }
                    var isoDateTimeConverter = new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd" };
                    var json = JsonConvert.SerializeObject(data, Formatting.None, isoDateTimeConverter);
                    return json;
                }
            case TimeSeriesSerializationType.ValuesOnly:
                {
                    var json = JsonConvert.SerializeObject(Values, Formatting.None);
                    return json;
                }
            default:
                {
                    var data = new Dictionary<DateTime, decimal>();
                    for (var i = 0; i < Times.Count; i++)
                    {
                        if (!data.ContainsKey(Times[i])) // duplicate times???
                            data.Add(Times[i], Values[i]);
                    }
                    var isoDateTimeConverter = new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz" };
                    var json = JsonConvert.SerializeObject(data, Formatting.None, isoDateTimeConverter);
                    return json;
                }
        }
    }

    public void Deserialize(string str)
    {
        if (string.IsNullOrEmpty(str)) return;
        var data = JsonConvert.DeserializeObject<Dictionary<DateTime, decimal>>(str);
        if (data.Count <= 0) return;
        foreach (var d in data)
            this.Add(d.Key, d.Value);
    }
}

Body:
I think you already have most of what you need.

What's missing is the attribute itself.

You'd define it like this (you can read more about the AttributeUsage-Attribute here):

[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
class TimeSeriesSerializationAttribute : Attribute
{
    public TimeSeriesSerializationType SerializationType { get; }

    public TimeSeriesSerializationAttribute(TimeSeriesSerializationType timeSeriesSerializationType)
    {
        SerializationType = timeSeriesSerializationType;
    }
}

Now you can add those above your properties just like you already wrote.

Time for the evaluation part. You can use something like this to read all the properties and use them to serialize your TimeSeries.

By the way if the attribute you get turns out as null, the attribute just isn't set. You can either skip the property entirely or use a default SerializationType, whatever you need/want.

public static void SerializeToSomewhere(YourClassWithTimeSeries instance) {
    // get all public, instance properties
    IEnumerable<PropertyInfo> allProps = typeof(YourClassWithTimeSeries).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    // only take TimeSeries-properties
    IEnumerable<PropertyInfo> timeSeriesProps = allProps.Where(p => p.PropertyType == typeof(TimeSeries));

    foreach (PropertyInfo property in timeSeriesProps)
    {
        // get the attribute
        TimeSeriesSerializationAttribute attribute = property.GetCustomAttribute<TimeSeriesSerializationAttribute>();
        if (attribute == null) continue; // or do something else like use a default SerializationType

        // get the value
        TimeSeries value = (TimeSeries)property.GetValue(instance, null);

        // serialize using the type from the attribute
        string serializedValue = value.Serialize(attribute.SerializationType);
        // Do whatever with the serialized value (for example save it to a file or whatever)
    }
}

Hope this helps you. There are also plenty of attribute tutorials and docs if you need additional information. I'll also try to answer questions you might have so feel free to ask.

Edit:

Small thing to add. In your code your TimeSeries-class exposes the public fields Times and Values. You shouldn't do that.
Instead of doing this:

public List<DateTime> Times = new List<DateTime>();
public List<decimal> Values = new List<decimal>();

You should do this. It stops you from accidentally assigning it again from within or outside the class.

public List<DateTime> Times { get; } = new List<DateTime>();
public List<decimal> Values { get; } = new List<decimal>();


问:
How to fix form data in array that is not submitting properly
I'm building an admin form that allows other teams to update aspects of their own data so they don't have to call me to do it for them.

They update the data via checkboxes or text fields. There is also a requirement that they be able to edit multiple rows at once. So the form required them to select which rows they will be updating or have updated. so far so good.

My problem is thus: If the first record has one checkbox selected and the second record has 3 boxes checked, when the form is submitted and the data echoed back out, the first record shows 3 values and the second record shows 1 indicating that record 1 has somehow taken the values from record 2 for itself.  I know that's not the case but can't figure out why that data is not staying with record 2.

I've beat around this and searched and found numerous examples that should work but they are just using a single text field and not checkboxes.  So, I'm hoping someone here can help me sort it out.

```<code><?php
    if(isset($_POST['updateRecord'])) {
        // echo "Update Record Outer Check<br>";
        if ((strtolower($_POST['updateRecord']) == "update")) {
            foreach ($_POST['update'] as $key => $update) {
                $id = $_POST['id'][$key];
                $regOK = (
                    isset($_POST['regOK'][$key]) ?
                    $_POST['regOK'][$key] : false
                );
                $paidOK = (
                    isset($_POST['paidOK'][$key]) ?
                    $_POST['paidOK'][$key] : false
                );
                $ebdOK = (
                isset($_POST['ebdOK'][$key]) ?
                    $_POST['ebdOK'][$key] : false
                );
                $appOK = (
                isset($_POST['appOK'][$key]) ?
                    $_POST['appOK'][$key] : false
                );
                echo "RECORD ID: ".$id."<br>";
                echo " REG: ".$regOK."<br>";
                echo "PAID: ".$paidOK."<br>";
                echo " EBD: ".$ebdOK."<br>";
                echo " APP: ".$appOK."<br><br>";
            }
        }
    }
    echo "<br><br>";
?>
<style type="text/css">
    th,td {text-align:center;}
</style>
<form action="" method="post" name="theForm">
    <table cellpadding="2" cellspacing="0" class="resultsTable">
        <tr>
            <th>REG</th>
            <th>PAID</th>
            <th>EBD</th>
            <th>APP</th>
            <th>Update Record</th>
        </tr>
        <tr>
            <td><input type="checkbox" name="regOK[]" id="regOK" value="1" checked></td>
            <td><input type="checkbox" name="paidOK[]" id="paidOK" value="1"></td>
            <td><input type="checkbox" name="ebdOK[]" id="ebdOK" value="1"></td>
            <td><input type="checkbox" name="appOK[]" id="appOK" value="1"></td>
            <td>
                <input type="checkbox" class="test" name="update[]" id="update" value="1">
                <input type="hidden" name="updateRecord[]" id="updateRecord" value="update">
                <input type="hidden" name="id[]" id="id" value="1"  />
            </td>
        </tr>
        <tr>
            <td><input type="checkbox" name="regOK[]" id="regOK" value="1" checked></td>
            <td><input type="checkbox" name="paidOK[]" id="paidOK" value="1"></td>
            <td><input type="checkbox" name="ebdOK[]" id="ebdOK" value="1"></td>
            <td><input type="checkbox" name="appOK[]" id="appOK" value="1"></td>
            <td>
                <input type="checkbox" class="test" name="update[]" id="update" value="2">
                <input type="hidden" name="updateRecord[]" id="updateRecord" value="update">
                <input type="hidden" name="id[]" id="id" value="2"  />
            </td>
        </tr>
        <tr>
            <td><input type="checkbox" name="regOK[]" id="regOK" value="1"></td>
            <td><input type="checkbox" name="paidOK[]" id="paidOK" value="1"></td>
            <td><input type="checkbox" name="ebdOK[]" id="ebdOK" value="1"></td>
            <td><input type="checkbox" name="appOK[]" id="appOK" value="1"></td>
            <td>
                <input type="checkbox" name="update[]" id="update" value="3">
                <input type="hidden" name="updateRecord" id="updateRecord" value="update">
                <input type="hidden" name="id[]" id="id" value="3"  />
            </td>
        </tr>
        <tr><td colspan="5" ><input type="submit" name="updateFormData" id="updateFormData" value="Update All Records"></td></tr>
    </table>
</form>
</code>```

The first two checkboxes are checked. Leave row 1 alone and check the second checkbox for record 2, select the update checkbox for the first two rows and then submit the form.  What I expect to see is:

RECORD ID: 1
REG: 1
PAID:
EBD:
APP:

RECORD ID: 2
REG: 1
PAID: 1
EBD:
APP:

What I'm getting in this example is:
RECORD ID: 1
REG: 1
PAID: 1
EBD:
APP:

RECORD ID: 2
REG: 1
PAID:
EBD:
APP:

You can see where the first record shows the data from row two.

答:
Bug in your code is indexing, handling form with index will solve it </p>

```<code><?php
    if(isset($_POST['updateRecord'])) {
        // echo "Update Record Outer Check<br>";
        if ((strtolower($_POST['updateRecord']) == "update")) {
            foreach ($_POST['update'] as $key => $update) {
                $id = $_POST['id'][$key];
                $regOK = (
                    isset($_POST['regOK'][$key]) ?
                    $_POST['regOK'][$key] : false
                );
                $paidOK = (
                    isset($_POST['paidOK'][$key]) ?
                    $_POST['paidOK'][$key] : false
                );
                $ebdOK = (
                isset($_POST['ebdOK'][$key]) ?
                    $_POST['ebdOK'][$key] : false
                );
                $appOK = (
                isset($_POST['appOK'][$key]) ?
                    $_POST['appOK'][$key] : false
                );
                echo "RECORD ID: ".$id."<br>";
                echo " REG: ".$regOK."<br>";
                echo "PAID: ".$paidOK."<br>";
                echo " EBD: ".$ebdOK."<br>";
                echo " APP: ".$appOK."<br><br>";
            }
        }
    }
    echo "<br><br>";
?>
<style type="text/css">
    th,td {text-align:center;}
</style>
<form action="" method="post" name="theForm">
    <table cellpadding="2" cellspacing="0" class="resultsTable">
        <tr>
            <th>REG</th>
            <th>PAID</th>
            <th>EBD</th>
            <th>APP</th>
            <th>Update Record</th>
        </tr>
        <tr>
            <td><input type="checkbox" name="regOK[]" id="regOK" value="1" checked></td>
            <td><input type="checkbox" name="paidOK[]" id="paidOK" value="1"></td>
            <td><input type="checkbox" name="ebdOK[]" id="ebdOK" value="1"></td>
            <td><input type="checkbox" name="appOK[]" id="appOK" value="1"></td>
            <td>
                <input type="checkbox" class="test" name="update[]" id="update" value="1">
                <input type="hidden" name="updateRecord[]" id="updateRecord" value="update">
                <input type="hidden" name="id[]" id="id" value="1"  />
            </td>
        </tr>
        <tr>
            <td><input type="checkbox" name="regOK[1]" id="regOK" value="1" checked></td>
            <td><input type="checkbox" name="paidOK[1]" id="paidOK" value="1"></td>
            <td><input type="checkbox" name="ebdOK[1]" id="ebdOK" value="1"></td>
            <td><input type="checkbox" name="appOK[1]" id="appOK" value="1"></td>
            <td>
                <input type="checkbox" class="test" name="update[1]" id="update" value="2">
                <input type="hidden" name="updateRecord[1]" id="updateRecord" value="update">
                <input type="hidden" name="id[]" id="id" value="2"  />
            </td>
        </tr>
        <tr>
            <td><input type="checkbox" name="regOK[2]" id="regOK" value="1"></td>
            <td><input type="checkbox" name="paidOK[2]" id="paidOK" value="1"></td>
            <td><input type="checkbox" name="ebdOK[2]" id="ebdOK" value="1"></td>
            <td><input type="checkbox" name="appOK[2]" id="appOK" value="1"></td>
            <td>
                <input type="checkbox" name="update[2]" id="update" value="3">
                <input type="hidden" name="updateRecord" id="updateRecord" value="update">
                <input type="hidden" name="id[]" id="id" value="3"  />
            </td>
        </tr>
        <tr><td colspan="5" ><input type="submit" name="updateFormData" id="updateFormData" value="Update All Records"></td></tr>
    </table>
</form>
</code>```

Body:
I'm building an admin form that allows other teams to update aspects of their own data so they don't have to call me to do it for them.

They update the data via checkboxes or text fields. There is also a requirement that they be able to edit multiple rows at once. So the form required them to select which rows they will be updating or have updated. so far so good.

My problem is thus: If the first record has one checkbox selected and the second record has 3 boxes checked, when the form is submitted and the data echoed back out, the first record shows 3 values and the second record shows 1 indicating that record 1 has somehow taken the values from record 2 for itself.  I know that's not the case but can't figure out why that data is not staying with record 2.

I've beat around this and searched and found numerous examples that should work but they are just using a single text field and not checkboxes.  So, I'm hoping someone here can help me sort it out.

<?php
    if(isset($_POST['updateRecord'])) {
        // echo "Update Record Outer Check
";
        if ((strtolower($_POST['updateRecord']) == "update")) {
            foreach ($_POST['update'] as $key => $update) {
                $id = $_POST['id'][$key];
                $regOK = (
                    isset($_POST['regOK'][$key]) ?
                    $_POST['regOK'][$key] : false
                );
                $paidOK = (
                    isset($_POST['paidOK'][$key]) ?
                    $_POST['paidOK'][$key] : false
                );
                $ebdOK = (
                isset($_POST['ebdOK'][$key]) ?
                    $_POST['ebdOK'][$key] : false
                );
                $appOK = (
                isset($_POST['appOK'][$key]) ?
                    $_POST['appOK'][$key] : false
                );
                echo "RECORD ID: ".$id."
";
                echo " REG: ".$regOK."
";
                echo "PAID: ".$paidOK."
";
                echo " EBD: ".$ebdOK."
";
                echo " APP: ".$appOK."

";
            }
        }
    }
    echo "

";
?>

<form action="" method="post" name="theForm">

            REG
            PAID
            EBD
            APP
            Update Record

            <input type="checkbox" name="regOK[]" id="regOK" value="1" checked>
            <input type="checkbox" name="paidOK[]" id="paidOK" value="1">
            <input type="checkbox" name="ebdOK[]" id="ebdOK" value="1">
            <input type="checkbox" name="appOK[]" id="appOK" value="1">

                <input type="checkbox" class="test" name="update[]" id="update" value="1">
                <input type="hidden" name="updateRecord[]" id="updateRecord" value="update">
                <input type="hidden" name="id[]" id="id" value="1"  />

            <input type="checkbox" name="regOK[]" id="regOK" value="1" checked>
            <input type="checkbox" name="paidOK[]" id="paidOK" value="1">
            <input type="checkbox" name="ebdOK[]" id="ebdOK" value="1">
            <input type="checkbox" name="appOK[]" id="appOK" value="1">

                <input type="checkbox" class="test" name="update[]" id="update" value="2">
                <input type="hidden" name="updateRecord[]" id="updateRecord" value="update">
                <input type="hidden" name="id[]" id="id" value="2"  />

            <input type="checkbox" name="regOK[]" id="regOK" value="1">
            <input type="checkbox" name="paidOK[]" id="paidOK" value="1">
            <input type="checkbox" name="ebdOK[]" id="ebdOK" value="1">
            <input type="checkbox" name="appOK[]" id="appOK" value="1">

                <input type="checkbox" name="update[]" id="update" value="3">
                <input type="hidden" name="updateRecord" id="updateRecord" value="update">
                <input type="hidden" name="id[]" id="id" value="3"  />

<input type="submit" name="updateFormData" id="updateFormData" value="Update All Records">

</form>

The first two checkboxes are checked. Leave row 1 alone and check the second checkbox for record 2, select the update checkbox for the first two rows and then submit the form.  What I expect to see is:

RECORD ID: 1
REG: 1
PAID:
EBD:
APP:

RECORD ID: 2
REG: 1
PAID: 1
EBD:
APP:

What I'm getting in this example is:
RECORD ID: 1
REG: 1
PAID: 1
EBD:
APP:

RECORD ID: 2
REG: 1
PAID:
EBD:
APP:

You can see where the first record shows the data from row two.

Body:
Bug in your code is indexing, handling form with index will solve it

<?php
    if(isset($_POST['updateRecord'])) {
        // echo "Update Record Outer Check<br>";
        if ((strtolower($_POST['updateRecord']) == "update")) {
            foreach ($_POST['update'] as $key => $update) {
                $id = $_POST['id'][$key];
                $regOK = (
                    isset($_POST['regOK'][$key]) ?
                    $_POST['regOK'][$key] : false
                );
                $paidOK = (
                    isset($_POST['paidOK'][$key]) ?
                    $_POST['paidOK'][$key] : false
                );
                $ebdOK = (
                isset($_POST['ebdOK'][$key]) ?
                    $_POST['ebdOK'][$key] : false
                );
                $appOK = (
                isset($_POST['appOK'][$key]) ?
                    $_POST['appOK'][$key] : false
                );
                echo "RECORD ID: ".$id."<br>";
                echo " REG: ".$regOK."<br>";
                echo "PAID: ".$paidOK."<br>";
                echo " EBD: ".$ebdOK."<br>";
                echo " APP: ".$appOK."<br><br>";
            }
        }
    }
    echo "<br><br>";
?>
<style type="text/css">
    th,td {text-align:center;}
</style>
<form action="" method="post" name="theForm">
    <table cellpadding="2" cellspacing="0" class="resultsTable">
        <tr>
            <th>REG</th>
            <th>PAID</th>
            <th>EBD</th>
            <th>APP</th>
            <th>Update Record</th>
        </tr>
        <tr>
            <td><input type="checkbox" name="regOK[]" id="regOK" value="1" checked></td>
            <td><input type="checkbox" name="paidOK[]" id="paidOK" value="1"></td>
            <td><input type="checkbox" name="ebdOK[]" id="ebdOK" value="1"></td>
            <td><input type="checkbox" name="appOK[]" id="appOK" value="1"></td>
            <td>
                <input type="checkbox" class="test" name="update[]" id="update" value="1">
                <input type="hidden" name="updateRecord[]" id="updateRecord" value="update">
                <input type="hidden" name="id[]" id="id" value="1"  />
            </td>
        </tr>
        <tr>
            <td><input type="checkbox" name="regOK[1]" id="regOK" value="1" checked></td>
            <td><input type="checkbox" name="paidOK[1]" id="paidOK" value="1"></td>
            <td><input type="checkbox" name="ebdOK[1]" id="ebdOK" value="1"></td>
            <td><input type="checkbox" name="appOK[1]" id="appOK" value="1"></td>
            <td>
                <input type="checkbox" class="test" name="update[1]" id="update" value="2">
                <input type="hidden" name="updateRecord[1]" id="updateRecord" value="update">
                <input type="hidden" name="id[]" id="id" value="2"  />
            </td>
        </tr>
        <tr>
            <td><input type="checkbox" name="regOK[2]" id="regOK" value="1"></td>
            <td><input type="checkbox" name="paidOK[2]" id="paidOK" value="1"></td>
            <td><input type="checkbox" name="ebdOK[2]" id="ebdOK" value="1"></td>
            <td><input type="checkbox" name="appOK[2]" id="appOK" value="1"></td>
            <td>
                <input type="checkbox" name="update[2]" id="update" value="3">
                <input type="hidden" name="updateRecord" id="updateRecord" value="update">
                <input type="hidden" name="id[]" id="id" value="3"  />
            </td>
        </tr>
        <tr><td colspan="5" ><input type="submit" name="updateFormData" id="updateFormData" value="Update All Records"></td></tr>
    </table>
</form>


问:
How do I remove the padding inside a div that has a propery of display and a value of inline-block
How do I remove the padding from inside of a div with the display set to "inline-block".

Below is the html and css.

.showExpCusWrap {
  background-color: #A8D3FF;
  display: inline-block;
  border: 1px solid #004F9D;
  padding: 0px 10px;
  font-family: Tahoma;
}

.showExpCusWrap label {
  font-size: 0.9em;
  margin: 0px;
  padding: 0px;
}

.showExpCusWrap input[type="date"] {
  margin: 0px;
  padding: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="showExpCusWrap">
  <label for="showExpFrom">From</label>
  <input type="date" name="showExpFrom" id="showExpFrom">
  <label for="showExpTo">To</label>
  <input type="date" name="showExpTo" id="showExpTo">
  <input type="button" name="showExpCus" id="showExpCus" value="Show" class="exp-button-small">
</div></code>```

This is how it looks. Notice the top and bottom padding inside.

I have checked the broswer default styling. It does not set any padding. So, how to remove those? I want all the elements inside the div to appear without any spacing from top or bottom.

答:
While editing your question, I realized that there's no problem.

Here's a snippet of all the code that you sent.

.showExpCusWrap {
  background-color: #A8D3FF;
  display: inline-block;
  border: 1px solid #004F9D;
  padding: 0px 10px;
  font-family: Tahoma;
}
.showExpCusWrap label {
  font-size: 0.9em;
  margin: 0px;
  padding: 0px;
}
.showExpCusWrap input[type="date"]{
  margin: 0px;
  padding: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="showExpCusWrap">
      <label for="showExpFrom">From</label>
      <input type="date" name="showExpFrom" id="showExpFrom">
      <label for="showExpTo">To</label>
      <input type="date" name="showExpTo" id="showExpTo">
      <input type="button" name="showExpCus" id="showExpCus" value="Show" class="exp-button-small">
    </div></code>```

Body:
How do I remove the padding from inside of a div with the display set to "inline-block".

Below is the html and css.

.showExpCusWrap {
  background-color: #A8D3FF;
  display: inline-block;
  border: 1px solid #004F9D;
  padding: 0px 10px;
  font-family: Tahoma;
}

.showExpCusWrap label {
  font-size: 0.9em;
  margin: 0px;
  padding: 0px;
}

.showExpCusWrap input[type="date"] {
  margin: 0px;
  padding: 0px;
}

  From
  <input type="date" name="showExpFrom" id="showExpFrom">
  To
  <input type="date" name="showExpTo" id="showExpTo">
  <input type="button" name="showExpCus" id="showExpCus" value="Show" class="exp-button-small">

This is how it looks. Notice the top and bottom padding inside.

I have checked the broswer default styling. It does not set any padding. So, how to remove those? I want all the elements inside the div to appear without any spacing from top or bottom.

Body:
While editing your question, I realized that there's no problem.

Here's a snippet of all the code that you sent.

.showExpCusWrap {
  background-color: #A8D3FF;
  display: inline-block;
  border: 1px solid #004F9D;
  padding: 0px 10px;
  font-family: Tahoma;
}
.showExpCusWrap label {
  font-size: 0.9em;
  margin: 0px;
  padding: 0px;
}
.showExpCusWrap input[type="date"]{
  margin: 0px;
  padding: 0px;
}

<div class="showExpCusWrap">
      <label for="showExpFrom">From</label>
      <input type="date" name="showExpFrom" id="showExpFrom">
      <label for="showExpTo">To</label>
      <input type="date" name="showExpTo" id="showExpTo">
      <input type="button" name="showExpCus" id="showExpCus" value="Show" class="exp-button-small">
    </div>


问:
Insert a row only if doesn't exist without getting its id
I followed this tutorial with 'INSERT IGNORE' first and 'INSERT ... ON DUPLICATE KEY UPDATE' then. But it doesn't work.
I'm using NodeJS to get some data from an API, and store these data into a mySQL database. Before storing data, I want to know if this row already exists.
The ID is AUTO_INCREMENT and I d'ont know this one. Instead of using async/await or promises in NodeJS, I wanted to treat this point with mySQL without knowing the ID.

I tried this one but it adds a new row with a new ID instead of another row already exists:

```<code>INSERT INTO test (nom, date, heure) VALUES ('123456', '2018-08-23', '10:45:00') ON DUPLICATE KEY UPDATE nom='123456', date='2018-08-23', heure='10:45:00';
</code>```

After that, I tested this one, same result:

```<code>INSERT IGNORE INTO test (nom, date, heure) VALUES ('123456', '2018-08-23', '10:45:00')
</code>```

Thanks for your help!

答:
Set a unique index for the 3 columns:

```<code>ALTER TABLE test ADD UNIQUE un_index(nom, date, heure);
</code>```

Then execute:

```<code>INSERT IGNORE INTO test (nom, date, heure) VALUES ('123456', '2018-08-23', '10:45:00');
</code>```

If the 3 values already exist, the row will not be inserted.

Body:
I followed this tutorial with 'INSERT IGNORE' first and 'INSERT ... ON DUPLICATE KEY UPDATE' then. But it doesn't work.
I'm using NodeJS to get some data from an API, and store these data into a mySQL database. Before storing data, I want to know if this row already exists.
The ID is AUTO_INCREMENT and I d'ont know this one. Instead of using async/await or promises in NodeJS, I wanted to treat this point with mySQL without knowing the ID.

I tried this one but it adds a new row with a new ID instead of another row already exists:

INSERT INTO test (nom, date, heure) VALUES ('123456', '2018-08-23', '10:45:00') ON DUPLICATE KEY UPDATE nom='123456', date='2018-08-23', heure='10:45:00';

After that, I tested this one, same result:

INSERT IGNORE INTO test (nom, date, heure) VALUES ('123456', '2018-08-23', '10:45:00')

Thanks for your help!

Body:
Set a unique index for the 3 columns:

ALTER TABLE test ADD UNIQUE un_index(nom, date, heure);

Then execute:

INSERT IGNORE INTO test (nom, date, heure) VALUES ('123456', '2018-08-23', '10:45:00');

If the 3 values already exist, the row will not be inserted.


问:
Set a form's action attribute when submitting?
How do I change a form's action attribute right after clicking the submit button?  </p>

答: Attach to the submit button click event and change the action attribute in the event handler.

ContentLicense: CC BY-SA 3.0


答:
With some research, i found a better way with the new Material Design. We need to use the MaterialButtonToggleGroup which is provided in the Android material library:

```<code><com.google.android.material.button.MaterialButtonToggleGroup
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:singleSelection="true"
    app:checkedButton="@id/active">

<com.google.android.material.button.MaterialButton
        android:id="@+id/active"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Active"
        style="@style/Widget.MaterialComponents.Button.OutlinedButton"/>

<com.google.android.material.button.MaterialButton
        android:id="@+id/completed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Completed"
        style="@style/Widget.MaterialComponents.Button.OutlinedButton"/>
</com.google.android.material.button.MaterialButtonToggleGroup>
</code>```

Hope this helps other persons as well...

Title: Toggle Button in Android

Body:
Can anyone help or share a link on how to implement this toggle button in android:

I've tried using this:

<ToggleButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textOn="Active"
                android:textOff="Completed"/>

but it's not having the desired output.

It has only one button and it changes when i click on it. What i want is two buttons side by side as shown in the picture above.

Body:
With some research, i found a better way with the new Material Design. We need to use the MaterialButtonToggleGroup which is provided in the Android material library:

<com.google.android.material.button.MaterialButtonToggleGroup
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:singleSelection="true"
    app:checkedButton="@id/active">

<com.google.android.material.button.MaterialButton
        android:id="@+id/active"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Active"
        style="@style/Widget.MaterialComponents.Button.OutlinedButton"/>

<com.google.android.material.button.MaterialButton
        android:id="@+id/completed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Completed"
        style="@style/Widget.MaterialComponents.Button.OutlinedButton"/>
</com.google.android.material.button.MaterialButtonToggleGroup>

Hope this helps other persons as well...


问:
Android Studio 3.1: mixing versions can lead to runtime crashes
Have recently upgraded to Android Studio 3.1, and at the same time I'm trying the Android P preview.

I'm getting the following error on compiling:

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 28.0.0-alpha1, 26.1.0. Examples include com.android.support:animated-vector-drawable:28.0.0-alpha1 and com.android.support:support-media-compat:26.1.0 less... (Ctrl+F1)
  There are some combinations of libraries, or tools and libraries, that are incompatible, or can lead to bugs. One such incompatibility is compiling with a version of the Android support libraries that is not the latest version (or in particular, a version lower than your targetSdkVersion).

But I cannot see any instance of 26.1.0 anywhere.  All I have in my gradle is:

```<code>implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
implementation 'com.android.support:design:28.0.0-alpha1'
</code>```

I've tried clearing caches, rebuilding app, etc.  But error remains.

答:
In my case I resolved it by adding this below the error line.</p>

```<code>implementation 'com.android.support:support-media-compat:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
</code>```

Body:
Have recently upgraded to Android Studio 3.1, and at the same time I'm trying the Android P preview.

I'm getting the following error on compiling:

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 28.0.0-alpha1, 26.1.0. Examples include com.android.support:animated-vector-drawable:28.0.0-alpha1 and com.android.support:support-media-compat:26.1.0 less... (Ctrl+F1)
  There are some combinations of libraries, or tools and libraries, that are incompatible, or can lead to bugs. One such incompatibility is compiling with a version of the Android support libraries that is not the latest version (or in particular, a version lower than your targetSdkVersion).

But I cannot see any instance of 26.1.0 anywhere.  All I have in my gradle is:

implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
implementation 'com.android.support:design:28.0.0-alpha1'

I've tried clearing caches, rebuilding app, etc.  But error remains.

Body:
In my case I resolved it by adding this below the error line.

implementation 'com.android.support:support-media-compat:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'


问:
ExpressJS app which receives around 70 requests per second - slow Cassandra performance
This is not a question related to a code, but more to a server performance and things that I should check. So I have a ExpressJS server which is connected to a cassandra db (1 seed node and 2 nodes on 1 cluster, so in total 3 nodes). The API is running on the same server as the cassandra db seed node. I have in total 3 servers in local network.

So the structure looks like this -

server 1 running API and seed cassandra node.
server 2 running cassandra node.
server 3 running cassandra node.

Each server has 8GM of ram and 2.5Ghz CPU.

By default there are around 70 requests coming in each second which does the following -

1) Calls a function which reads the data from a table from the cassandra (using materialized view).
2) Reads another table from cassandra db (using materialized view).
3) Posts data to the third table in cassandra.

The 2nd function that is called is quite similar, it does 1 read using materialized view and 1 post.

The proportional difference between the function called each second is around 30 times function 1 is called (which does 2 reads and 1 post), and around 40 times function 2 is called (which does 1 read and 1 post).

Everything would be great, but the latency of the requests are jumping from time to time, sometimes it takes around 10ms, but every 5 - 10 seconds it goes up to 3-30 seconds. Also cassandra seems to be unstable - during the period when there are 3-30 second request times, the cassandra seem to time out on some of the requests.

What would be the first thing that I should check? Do I need additional nodes and how can I figure out if I have enough nodes for the amount of data being sent in to cassandra db? Should I separate API from cassandra nodes - thus hold API server on a separate server, e.g., server 4?

答:
Materialized views are great for reads operations, but they come with the expense of writes; you'll need to account for some overhead required to execute its magic:

materialized view will require additional resources to track updates on its sources; this will get worse when you interact with multiple materialized views, as in the first scenario that you propose.

If the data of the post is written in the same source of the materialized view, this will depend on the complexity of the primary key used in the table, as explained here.

The first option that I would explore is to denormalize and create a separate table for the first function, so you will do one read, instead of two.

There is a lot of speculation in my answer, as there are a lot of unknowns on the structure and your table schema; you may get a better insight if you enable tracing, on our case we have gotten good results with openzipkin as explained by TLP


问:
Sequelize update
I'm trying to update a model in Sequelize using the following code:

```<code>exports.updateItem = function(item) {
    return new Promise((fulfill, reject) => {
        models.TimesheetItem.update(item,{where: {id: item.id}})
                            .then(fulfill)
                            .catch(console.dir);
     });
};
</code>```

Where item is the result of doing models.TimeSheetItem.find()

The call never executes the .then and instead passes an empty object to the .catch.

I've looked over the documentation and it seems that this is the way to update a row, but I can't get it to work. What am I doing wrong?

Thank you!

答:
```<code>{ error: type "where" does not exist}
</code>```

Just an update to the solution, Sequelize now gives the  error above when you include the 'where' option(as shown below). So take it out and it should work perfectly.

```<code>exports.updateItem = function(item){
    models.TimesheetItem.update(item, { id: item.id  }).then((result) => {
        // here result will be [ 1 ], if the id column is unique in your table
        // the problem is that you can't return updated instance, you would have to retrieve it from database once again
        return result;
    }).catch(e => {
        console.log(e);
    });
};
</code>```

Title: Sequelize update

Body:
I'm trying to update a model in Sequelize using the following code:

exports.updateItem = function(item) {
    return new Promise((fulfill, reject) => {
        models.TimesheetItem.update(item,{where: {id: item.id}})
                            .then(fulfill)
                            .catch(console.dir);
     });
};

Where item is the result of doing models.TimeSheetItem.find()

The call never executes the .then and instead passes an empty object to the .catch.

I've looked over the documentation and it seems that this is the way to update a row, but I can't get it to work. What am I doing wrong?

Thank you!

Body:
{ error: type "where" does not exist}

Just an update to the solution, Sequelize now gives the  error above when you include the 'where' option(as shown below). So take it out and it should work perfectly.

exports.updateItem = function(item){
    models.TimesheetItem.update(item, { id: item.id  }).then((result) => {
        // here result will be [ 1 ], if the id column is unique in your table
        // the problem is that you can't return updated instance, you would have to retrieve it from database once again
        return result;
    }).catch(e => {
        console.log(e);
    });
};


问:
How to add comments to a specific post?
I am very new to rails and I don't know much about where my problem lies. Just started a few days ago and right now I am trying to add comments to a specific post. Well, technically these are not comments but more of logs added to a certain request when other people have interacted with the request like Request A has log B, log C, log D so its basically the same as a comment sytem.

I already can create the logs and display them but my main problem is showing the right logs for the right request. My logs already have the correct request id but I don't know how to get the specific logs to display for the specific request

This is my historys_controller.rb

```<code>class HistorysController < ActionController::Base
  before_action :require_login

  def index
    @historys = History.where(job_order: 1)
  end

  def require_login
    unless session['user_credentials_id']
      redirect_to '/'
    end
  end
end
</code>```

It is still set as 1 as a temporary placeholder and trying something like

```<code>History.where(job_order: @job_order.id)
</code>```

and

```<code>History.where(job_order: params [:id])
</code>```

does not work so what should I put there?

EDIT

history.rb

```<code>class History < ApplicationRecord
    belongs_to :job_order, polymorphic: true
    belongs_to :actor, class_name: "User"
end
</code>```

routes.rb

```<code>Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  root 'user_sessions#new'

  get '/sign_in', to: 'user_sessions#new', as: :sign_in
  get '/signup' => 'users#signup', as: 'signup_user'
  delete '/sign_out', to: 'user_sessions#destroy', as: :sign_out
  post '/register' => 'users#register', as: 'register_user'

  get '/users/activate/:id' => 'users#activate', as: 'activate_user'
  get '/users/deactivate/:id' => 'users#deactivate', as: 'deactivate_user'

  get '/job_order_tracking_system' => 'job_orders#dashboard', as: 'job_order_tracking_system'
  get '/job_orders/approve_job_order/:id' => 'job_orders#approve_job_order', as: 'approve_job_order'
  get '/job_orders/reject_job_order/:id' => 'job_orders#reject_job_order', as: 'reject_job_order'
  get '/job_orders/start_job_order/:id' => 'job_orders#start_job_order', as: 'start_job_order'
  get '/job_orders/done_job_order/:id' => 'job_orders#done_job_order', as: 'done_job_order'
  get '/job_orders/cancel_job_order/:id' => 'job_orders#cancel_job_order', as: 'cancel_job_order'

  resources :job_orders do
    resources :historys
  end
  resources :users
  resources :offices
  resources :user_sessions, only: [:create, :destroy]
  resources :notifications do
    collection do
      post :mark_as_read
    end
  end
  # resources :historys
end

</code>```

答:
you want the histories for a specific job order?

Do

```<code>class JobOrder < ApplicationRecord
  has_many :histories
end
</code>```

Then you can get all the related histories with

```<code>@job_order.histories
</code>```

And in your view you can do somthing like...

```<code><% @job_order.histories.each do |history| %>
  <%= history.name %>
  <%= history.comment %>
  <br/>
<% end %>
</code>```

Incidentally, use the correct spelling for the plural of "history"... your controller should be HistoriesController Rails is smarter than you realise.

Title: How to add comments to a specific post?

Body:
I am very new to rails and I don't know much about where my problem lies. Just started a few days ago and right now I am trying to add comments to a specific post. Well, technically these are not comments but more of logs added to a certain request when other people have interacted with the request like Request A has log B, log C, log D so its basically the same as a comment sytem.

I already can create the logs and display them but my main problem is showing the right logs for the right request. My logs already have the correct request id but I don't know how to get the specific logs to display for the specific request

This is my historys_controller.rb

class HistorysController < ActionController::Base
  before_action :require_login

  def index
    @historys = History.where(job_order: 1)
  end

  def require_login
    unless session['user_credentials_id']
      redirect_to '/'
    end
  end
end

It is still set as 1 as a temporary placeholder and trying something like

History.where(job_order: @job_order.id)

and

History.where(job_order: params [:id])

does not work so what should I put there?

EDIT

history.rb

class History < ApplicationRecord
    belongs_to :job_order, polymorphic: true
    belongs_to :actor, class_name: "User"
end

routes.rb

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  root 'user_sessions#new'

  get '/sign_in', to: 'user_sessions#new', as: :sign_in
  get '/signup' => 'users#signup', as: 'signup_user'
  delete '/sign_out', to: 'user_sessions#destroy', as: :sign_out
  post '/register' => 'users#register', as: 'register_user'

  get '/users/activate/:id' => 'users#activate', as: 'activate_user'
  get '/users/deactivate/:id' => 'users#deactivate', as: 'deactivate_user'

  get '/job_order_tracking_system' => 'job_orders#dashboard', as: 'job_order_tracking_system'
  get '/job_orders/approve_job_order/:id' => 'job_orders#approve_job_order', as: 'approve_job_order'
  get '/job_orders/reject_job_order/:id' => 'job_orders#reject_job_order', as: 'reject_job_order'
  get '/job_orders/start_job_order/:id' => 'job_orders#start_job_order', as: 'start_job_order'
  get '/job_orders/done_job_order/:id' => 'job_orders#done_job_order', as: 'done_job_order'
  get '/job_orders/cancel_job_order/:id' => 'job_orders#cancel_job_order', as: 'cancel_job_order'

  resources :job_orders do
    resources :historys
  end
  resources :users
  resources :offices
  resources :user_sessions, only: [:create, :destroy]
  resources :notifications do
    collection do
      post :mark_as_read
    end
  end
  # resources :historys
end

Body:
you want the histories for a specific job order?

Do

class JobOrder < ApplicationRecord
  has_many :histories
end

Then you can get all the related histories with

@job_order.histories

And in your view you can do somthing like...

<% @job_order.histories.each do |history| %>
  <%= history.name %>
  <%= history.comment %>
  <br/>
<% end %>

Incidentally, use the correct spelling for the plural of "history"... your controller should be HistoriesController Rails is smarter than you realise.


问:
Is there a way to access API response data before the response has completed?
Some APIs don't have pagination implemented. Is there a way to access the partial response and access available objects before the API call has completed? For example if the response is json and the data that has already been received is:

{"objectarray": [
   {"Name": "test1"},
   {"Name": "test2"},
   {"Name":
```

The first 2 elements are already loaded and can parsed. Why wait for the whole response to complete?
I guess there some problems with this approach. Please share thoughts.

答:
I've written a code sample that does what I need. Is there a better way to do it? Please share thoughts.</p>

```<code>     WebClient client = new WebClient();
     Stream str = client.OpenRead(<url>);
     using (JsonTextReader reader = new JsonTextReader(new StreamReader(str)))
     {
        while (reader.Read())
        {
           if (reader.TokenType == JsonToken.StartArray)
           {
              while (reader.Read())
              {
                 if (reader.TokenType == JsonToken.StartObject)
                 {
                     var jsonObject = JObject.Load(reader);
                     var deserialized = jsonObject.ToObject<T>();
                 }
              }
           }
        }
     }
</code>```

Body:
Some APIs don't have pagination implemented. Is there a way to access the partial response and access available objects before the API call has completed? For example if the response is json and the data that has already been received is:

{"objectarray": [
   {"Name": "test1"},
   {"Name": "test2"},
   {"Name":

The first 2 elements are already loaded and can parsed. Why wait for the whole response to complete?
I guess there some problems with this approach. Please share thoughts.

Body:
I've written a code sample that does what I need. Is there a better way to do it? Please share thoughts.

     WebClient client = new WebClient();
     Stream str = client.OpenRead(<url>);
     using (JsonTextReader reader = new JsonTextReader(new StreamReader(str)))
     {
        while (reader.Read())
        {
           if (reader.TokenType == JsonToken.StartArray)
           {
              while (reader.Read())
              {
                 if (reader.TokenType == JsonToken.StartObject)
                 {
                     var jsonObject = JObject.Load(reader);
                     var deserialized = jsonObject.ToObject<T>();
                 }
              }
           }
        }
     }


问:
docker-machine create - Error creating machine: Error running provisioning: ssh command error
I'm following the docker get started docs, and I got stuck at the beginning of part 4 (https://docs.docker.com/get-started/part4/).

I'm on Windows 10, and I'm supposed to set up a couple of local VMs. I've created the virtual switch named "myswitch", but when I run

```<code>docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm1
</code>```

it gives me the following error

```<code>c:\srv> docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm4
Running pre-create checks...
Creating machine...
(myvm4) Copying C:\Users\bjorn\.docker\machine\cache\boot2docker.iso to C:\Users\bjorn\.docker\machine\machines\myvm4\boot2docker.iso...
(myvm4) Creating SSH key...
(myvm4) Creating VM...
(myvm4) Using switch "myswitch"
(myvm4) Creating VHD
(myvm4) Starting VM...
(myvm4) Waiting for host to start...
Waiting for machine to be running, this may take a few minutes...
Detecting operating system of created instance...
Waiting for SSH to be available...
Detecting the provisioner...
Provisioning with boot2docker...
Copying certs to the local machine directory...
Copying certs to the remote machine...
Error creating machine: Error running provisioning: ssh command error:
command : printf '%s' '-----BEGIN CERTIFICATE-----
MIICzjCCAbagAwIBAgIRAKtTNS/nB+OzHZ7r0PuiTpkwDQYJKoZIhvcNAQELBQAw
EDEOMAwGA1UEChMFYmpvcm4wHhcNMTkwNjAxMTY1NTAwWhcNMjIwNTE2MTY1NTAw
WjAQMQ4wDAYDVQQKEwViam9ybjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
ggEBAJ4wTk7sUwVwzTvPVbTiL/pTEWxRFWFO6gxU1BuNXIk1fzLpT7wMy/R48md1
DdGgkAUH/FgnjyKY9YnIpvlLt+HpuZjBxBRWYGJZDkV2QzvLb6dOLgev3i/7/vN+
1OWrr3OkfDCyXsSF1r2/6mMtk3wNtWiV4vdqjM7XEFrfWN6vLDCxGXqN5S0U94D+
vCbZuh1w51M3ZTvdC8D9nA0PVoh2detHsNGXdv7AuunYBmWGahr8OZT45RhtYksx
nXyU3HjjUyugscsuQp3y9Iwo4qP1eoWX+qJXuXlc7gznKHNx1D+nr9qRanEj3YUF
JspjEJc4H6J6TqVn+u/JfjrH6ZsCAwEAAaMjMCEwDgYDVR0PAQH/BAQDAgKsMA8G
A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBABFHjhI+OkVNdwM2qLL6
1wA7aeaLUi8GXUXjXjOxS3Vr7IZIejmvoAt/R6IpCmwFt2lL73JT7LB2cIR8hIVF
ZoQdTi1LBPyS2x0pKi5PHGN6O5UEVN0Y2aLkgpFxUZhtgqHTkeOaEPdWY6NHGWYR
8THT6LTT1cto/bqq07L5I+SsYwq/V+5JJhajqGLaoRonle4IUoDZTus4qaSbxcv/
ZO4rUW/w5Krn+QT31ku5pblAhGiNWtTQsP7+fQnfHT01PM0Hh1hBukAjRY2lImEo
URTKDR96IC3P2XFymXBcqHhZv13EKQQN5A8honxs10KxixlYhXTCg3W27L2FwzkU
WGo=
-----END CERTIFICATE-----
' | sudo tee /var/lib/boot2docker/ca.pem
err     : exit status 1
output  : bash: -c: line 0: unexpected EOF while looking for matching `''
bash: -c: line 1: syntax error: unexpected end of file
</code>```

I'm running in a elevated command shell (I've also tried using powershell as administrator, with exactly the same result).

docker-machine ls gives the following result (myvm1 and -2 are from my first attempt):

```<code>c:\srv> docker-machine ls
NAME    ACTIVE   DRIVER   STATE     URL                        SWARM   DOCKER    ERRORS
myvm1   -        hyperv                                                Unknown
myvm2   -        hyperv                                                Unknown
myvm3   -        hyperv   Running   tcp://192.168.1.140:2376           Unknown   Unable to query docker version: Get https://192.168.1.140:2376/v1.15/version: dial tcp 192.168.1.140:2376: connectex: No connection could be made because the target machine actively refused it.
myvm4   -        hyperv   Running   tcp://192.168.1.141:2376           Unknown   Unable to query docker version: Get https://192.168.1.141:2376/v1.15/version: dial tcp 192.168.1.141:2376: connectex: No connection could be made because the target machine actively refused it.
</code>```

I can't continue with the next step in the tutorial:

```<code>c:\srv> docker-machine ssh myvm3 "docker swarm init --advertise-addr 192.168.1.140"
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
exit status 1
</code>```

Any suggestions?

答:
Are you running Docker Toolbox or Docker on windows ?

If its Docker on windows, I see the docker-machine create is misdirected to generate certs at "/var/lib/boot2docker/ca.pem". This is a boot2docker specific location.I am inclined to believe that either there is some vestige of Docker Toolbox left behind in your system or you need to clear the following env variables.

DOCKER_TLS_VERIFY

DOCKER_CERT_PATH

DOCKER_HOST

DOCKER_TOOLBOX_INSTALL_PATH

Docker init will fail for not finding the socket at unix:///var/run/docker.sock,  which is expected since docker daemon is not up there.

Body:
I'm following the docker get started docs, and I got stuck at the beginning of part 4 (https://docs.docker.com/get-started/part4/).

I'm on Windows 10, and I'm supposed to set up a couple of local VMs. I've created the virtual switch named "myswitch", but when I run

docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm1

it gives me the following error

c:\srv> docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm4
Running pre-create checks...
Creating machine...
(myvm4) Copying C:\Users\bjorn\.docker\machine\cache\boot2docker.iso to C:\Users\bjorn\.docker\machine\machines\myvm4\boot2docker.iso...
(myvm4) Creating SSH key...
(myvm4) Creating VM...
(myvm4) Using switch "myswitch"
(myvm4) Creating VHD
(myvm4) Starting VM...
(myvm4) Waiting for host to start...
Waiting for machine to be running, this may take a few minutes...
Detecting operating system of created instance...
Waiting for SSH to be available...
Detecting the provisioner...
Provisioning with boot2docker...
Copying certs to the local machine directory...
Copying certs to the remote machine...
Error creating machine: Error running provisioning: ssh command error:
command : printf '%s' '-----BEGIN CERTIFICATE-----
MIICzjCCAbagAwIBAgIRAKtTNS/nB+OzHZ7r0PuiTpkwDQYJKoZIhvcNAQELBQAw
EDEOMAwGA1UEChMFYmpvcm4wHhcNMTkwNjAxMTY1NTAwWhcNMjIwNTE2MTY1NTAw
WjAQMQ4wDAYDVQQKEwViam9ybjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
ggEBAJ4wTk7sUwVwzTvPVbTiL/pTEWxRFWFO6gxU1BuNXIk1fzLpT7wMy/R48md1
DdGgkAUH/FgnjyKY9YnIpvlLt+HpuZjBxBRWYGJZDkV2QzvLb6dOLgev3i/7/vN+
1OWrr3OkfDCyXsSF1r2/6mMtk3wNtWiV4vdqjM7XEFrfWN6vLDCxGXqN5S0U94D+
vCbZuh1w51M3ZTvdC8D9nA0PVoh2detHsNGXdv7AuunYBmWGahr8OZT45RhtYksx
nXyU3HjjUyugscsuQp3y9Iwo4qP1eoWX+qJXuXlc7gznKHNx1D+nr9qRanEj3YUF
JspjEJc4H6J6TqVn+u/JfjrH6ZsCAwEAAaMjMCEwDgYDVR0PAQH/BAQDAgKsMA8G
A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBABFHjhI+OkVNdwM2qLL6
1wA7aeaLUi8GXUXjXjOxS3Vr7IZIejmvoAt/R6IpCmwFt2lL73JT7LB2cIR8hIVF
ZoQdTi1LBPyS2x0pKi5PHGN6O5UEVN0Y2aLkgpFxUZhtgqHTkeOaEPdWY6NHGWYR
8THT6LTT1cto/bqq07L5I+SsYwq/V+5JJhajqGLaoRonle4IUoDZTus4qaSbxcv/
ZO4rUW/w5Krn+QT31ku5pblAhGiNWtTQsP7+fQnfHT01PM0Hh1hBukAjRY2lImEo
URTKDR96IC3P2XFymXBcqHhZv13EKQQN5A8honxs10KxixlYhXTCg3W27L2FwzkU
WGo=
-----END CERTIFICATE-----
' | sudo tee /var/lib/boot2docker/ca.pem
err     : exit status 1
output  : bash: -c: line 0: unexpected EOF while looking for matching `''
bash: -c: line 1: syntax error: unexpected end of file

I'm running in a elevated command shell (I've also tried using powershell as administrator, with exactly the same result).

docker-machine ls gives the following result (myvm1 and -2 are from my first attempt):

c:\srv> docker-machine ls
NAME    ACTIVE   DRIVER   STATE     URL                        SWARM   DOCKER    ERRORS
myvm1   -        hyperv                                                Unknown
myvm2   -        hyperv                                                Unknown
myvm3   -        hyperv   Running   tcp://192.168.1.140:2376           Unknown   Unable to query docker version: Get https://192.168.1.140:2376/v1.15/version: dial tcp 192.168.1.140:2376: connectex: No connection could be made because the target machine actively refused it.
myvm4   -        hyperv   Running   tcp://192.168.1.141:2376           Unknown   Unable to query docker version: Get https://192.168.1.141:2376/v1.15/version: dial tcp 192.168.1.141:2376: connectex: No connection could be made because the target machine actively refused it.

I can't continue with the next step in the tutorial:

c:\srv> docker-machine ssh myvm3 "docker swarm init --advertise-addr 192.168.1.140"
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
exit status 1

Any suggestions?


问:
How To Navigate To Another Page With ngRoute
My Index.html

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

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
<script src="client/delljson.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

<body ng-app="myApp" ng-controller="myCtrl" style="background-color:orange;">

<h1><marquee width="40%" direction="right" >Resume</marquee></h1>

<a href='#!/main'>Press</a>

<div ng-view>

</div>

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

My Main.html

```<code><div class="row">
   <div class="col-md-4">
        <h2><u>Personal Information</u></h2>
        <p>{{deljson.personalInformation.name}}</p>
        <p>{{deljson.personalInformation.dob}}</p>
        <p>{{deljson.personalInformation.fatherName}}</p>
        <p>{{deljson.personalInformation.gender}}</p>
        <p>{{deljson.personalInformation.nationality}}</p>
        <p>{{deljson.personalInformation.maritalStatus}}</p>
   </div>
<div class="col-md-4">
    <h3><u>Educational Information</u></h3>
    <h4><u>SSLC</u></h4>
    <p>{{deljson.educationInformation.sslc.institueName}}</p>
    <p>{{deljson.educationInformation.sslc.studyBoard}}</p>
    <p>{{deljson.educationInformation.sslc.percentage}}</p>
    <p>{{deljson.educationInformation.sslc.yearOfPassedout}}</p>
    <h4><u>HSC</u></h4>
    <p>{{deljson.educationInformation.hsc.institueName}}</p>
    <p>{{deljson.educationInformation.hsc.studyBoard}}</p>
    <p>{{deljson.educationInformation.hsc.percentage}}</p>
    <p>{{deljson.educationInformation.hsc.yearOfPassedout}}</p>
    <h4><u>UG</u></h4>
    <p>{{deljson.educationInformation.ug.institueName}}</p>
    <p>{{deljson.educationInformation.ug.studyBoard}}</p>
    <p>{{deljson.educationInformation.ug.percentage}}</p>
    <p>{{deljson.educationInformation.ug.yearOfPassedout}}</p>
</div>
<div class="col-md-4">
    <h3><u>Work Experience</u></h3>
    <p>{{deljson.experience.previousExperience.companyName}}</p>
    <p>{{deljson.experience.previousExperience.Position}}</p>
    <p>{{deljson.experience.previousExperience.period}}</p>
    <p>{{deljson.experience.previousExperience.responsibility}}</p>
</div>
</div>
</code>```

My Js and Json File

```<code>var app = angular.module('myApp', ['ngRoute']);

app.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/main', {
        templateUrl : 'main.html',
        controller : 'first'
    })
   }]);

app.controller('first', ['$scope', '$locationProvider', function($scope){
    $location.path("/main.html" );
}]);

app.controller('myCtrl', function($scope) {
$scope.deljson = {
    "personalInformation": {
        "name": "Raaj Kumar",
        "dob": "13/5/1994",
        "fatherName": "Suresh",
        "gender": "Male",
        "nationality": "Indian",
        "maritalStatus": "Single"
    },
    "educationInformation": {
        "sslc": {
            "institueName": "G.K.S.V.V.J.C",
            "studyBoard": "CBSE",
            "percentage": "45%",
            "yearOfPassedout": "2009"
        },
        "hsc": {
            "institueName": "S.V.M.H.S.S",
            "studyBoard": "Matriculation",
            "percentage": "55%",
            "yearOfPassedout": "2011"
        },
        "ug": {
            "institueName": "S.T. Peter'S Engineering College",
            "course": "B.Tech (It)",
            "percentage": "59%",
            "yearOfPassedout": "2016"
        }
    },
    "experience": {
        "previousExperience": {
            "companyName": "Purple Soft Technology",
            "Position": "SEO Analyst",
            "period": "2018-19",
            "responsibility": "SEO"
        }
    },
    "personalSkills": [
        "Gaming"
    ],
    "technicalSkills": [
        "Digital Marketing",
        "HTML",
        "CSS",
        "JS"
    ]
}
});
</code>```

The Objective is to make a anchor text and link the main ,html to it and when clicked it should display the main.html in my ng-view.

I tried many methods watching the you tube but its not working out. the ng-view is displaying a template but its not displaying an template url.

答:
I have solved the problem, but there was numerous errors in the code (missing doctype, divs without end tags and so on), so I have recoded a lot of it. I have taken out the $locationprovider, IMO its not so great a feature, people cant bookmark the page,(unless you make a lot of changes in ie. HTACCESS). So I dont like it.
I have also updated angularjs to 1.7.8.

If you want to use locationprovider, please note that there was some changes to it when upgrading to 1.7.8.

INDEX.HTML

```<code><!DOCTYPE html>
<html ng-app="myApp">
  <meta charset="utf-8" />
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular-route.js"></script>
  <script src="/client/delljson.js"></script>
  <link
    rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"
  />
  <link
    rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"
  />

  <body ng-controller="myCtrl" style="background-color:orange;">
    <h1><marquee width="40%" direction="right">Resume</marquee></h1>
    <a href="#!/main">Press</a>
    <ng-view></ng-view>
  </body>
</html>
</code>```

AngularJS

```<code>var app = angular.module('myApp', ['ngRoute']);
app.controller('first', function($scope){
 });
app.config(function($routeProvider) {
    $routeProvider.when('/main', {
        templateUrl : 'main.html',
        controller:'first'
    }).
    otherwise({
        redirectTo: '/'
     });
   });
app.controller('myCtrl', function($scope) {
$scope.deljson = {
    "personalInformation": {
        "name": "Raaj Kumar",
        "dob": "13/5/1994",
        "fatherName": "Suresh",
        "gender": "Male",
        "nationality": "Indian",
        "maritalStatus": "Single"
    },
    "educationInformation": {
        "sslc": {
            "institueName": "G.K.S.V.V.J.C",
            "studyBoard": "CBSE",
            "percentage": "45%",
            "yearOfPassedout": "2009"
        },
        "hsc": {
            "institueName": "S.V.M.H.S.S",
            "studyBoard": "Matriculation",
            "percentage": "55%",
            "yearOfPassedout": "2011"
        },
        "ug": {
            "institueName": "S.T. Peter'S Engineering College",
            "course": "B.Tech (It)",
            "percentage": "59%",
            "yearOfPassedout": "2016"
        }
    },
    "experience": {
        "previousExperience": {
            "companyName": "Purple Soft Technology",
            "Position": "SEO Analyst",
            "period": "2018-19",
            "responsibility": "SEO"
        }
    },
    "personalSkills": [
        "Gaming"
    ],
    "technicalSkills": [
        "Digital Marketing",
        "HTML",
        "CSS",
        "JS"
    ]
}
});
</code>```

Body:
My Index.html

<!DOCTYPE html>

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

<marquee width="40%" direction="right" >Resume</marquee>

Press

My Main.html

Personal Information

{{deljson.personalInformation.name}}

{{deljson.personalInformation.dob}}

{{deljson.personalInformation.fatherName}}

{{deljson.personalInformation.gender}}

{{deljson.personalInformation.nationality}}

{{deljson.personalInformation.maritalStatus}}

Educational Information

SSLC

{{deljson.educationInformation.sslc.institueName}}

{{deljson.educationInformation.sslc.studyBoard}}

{{deljson.educationInformation.sslc.percentage}}

{{deljson.educationInformation.sslc.yearOfPassedout}}

HSC

{{deljson.educationInformation.hsc.institueName}}

{{deljson.educationInformation.hsc.studyBoard}}

{{deljson.educationInformation.hsc.percentage}}

{{deljson.educationInformation.hsc.yearOfPassedout}}

UG

{{deljson.educationInformation.ug.institueName}}

{{deljson.educationInformation.ug.studyBoard}}

{{deljson.educationInformation.ug.percentage}}

{{deljson.educationInformation.ug.yearOfPassedout}}

Work Experience

{{deljson.experience.previousExperience.companyName}}

{{deljson.experience.previousExperience.Position}}

{{deljson.experience.previousExperience.period}}

{{deljson.experience.previousExperience.responsibility}}

My Js and Json File

var app = angular.module('myApp', ['ngRoute']);

app.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/main', {
        templateUrl : 'main.html',
        controller : 'first'
    })
   }]);

app.controller('first', ['$scope', '$locationProvider', function($scope){
    $location.path("/main.html" );
}]);

app.controller('myCtrl', function($scope) {
$scope.deljson = {
    "personalInformation": {
        "name": "Raaj Kumar",
        "dob": "13/5/1994",
        "fatherName": "Suresh",
        "gender": "Male",
        "nationality": "Indian",
        "maritalStatus": "Single"
    },
    "educationInformation": {
        "sslc": {
            "institueName": "G.K.S.V.V.J.C",
            "studyBoard": "CBSE",
            "percentage": "45%",
            "yearOfPassedout": "2009"
        },
        "hsc": {
            "institueName": "S.V.M.H.S.S",
            "studyBoard": "Matriculation",
            "percentage": "55%",
            "yearOfPassedout": "2011"
        },
        "ug": {
            "institueName": "S.T. Peter'S Engineering College",
            "course": "B.Tech (It)",
            "percentage": "59%",
            "yearOfPassedout": "2016"
        }
    },
    "experience": {
        "previousExperience": {
            "companyName": "Purple Soft Technology",
            "Position": "SEO Analyst",
            "period": "2018-19",
            "responsibility": "SEO"
        }
    },
    "personalSkills": [
        "Gaming"
    ],
    "technicalSkills": [
        "Digital Marketing",
        "HTML",
        "CSS",
        "JS"
    ]
}
});

The Objective is to make a anchor text and link the main ,html to it and when clicked it should display the main.html in my ng-view.

I tried many methods watching the you tube but its not working out. the ng-view is displaying a template but its not displaying an template url.

Body:
I have solved the problem, but there was numerous errors in the code (missing doctype, divs without end tags and so on), so I have recoded a lot of it. I have taken out the $locationprovider, IMO its not so great a feature, people cant bookmark the page,(unless you make a lot of changes in ie. HTACCESS). So I dont like it.
I have also updated angularjs to 1.7.8.

If you want to use locationprovider, please note that there was some changes to it when upgrading to 1.7.8.

INDEX.HTML

<!DOCTYPE html>
<html ng-app="myApp">
  <meta charset="utf-8" />
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular-route.js"></script>
  <script src="/client/delljson.js"></script>
  <link
    rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"
  />
  <link
    rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"
  />

  <body ng-controller="myCtrl" style="background-color:orange;">
    <h1><marquee width="40%" direction="right">Resume</marquee></h1>
    <a href="#!/main">Press</a>
    <ng-view></ng-view>
  </body>
</html>

AngularJS

var app = angular.module('myApp', ['ngRoute']);
app.controller('first', function($scope){
 });
app.config(function($routeProvider) {
    $routeProvider.when('/main', {
        templateUrl : 'main.html',
        controller:'first'
    }).
    otherwise({
        redirectTo: '/'
     });
   });
app.controller('myCtrl', function($scope) {
$scope.deljson = {
    "personalInformation": {
        "name": "Raaj Kumar",
        "dob": "13/5/1994",
        "fatherName": "Suresh",
        "gender": "Male",
        "nationality": "Indian",
        "maritalStatus": "Single"
    },
    "educationInformation": {
        "sslc": {
            "institueName": "G.K.S.V.V.J.C",
            "studyBoard": "CBSE",
            "percentage": "45%",
            "yearOfPassedout": "2009"
        },
        "hsc": {
            "institueName": "S.V.M.H.S.S",
            "studyBoard": "Matriculation",
            "percentage": "55%",
            "yearOfPassedout": "2011"
        },
        "ug": {
            "institueName": "S.T. Peter'S Engineering College",
            "course": "B.Tech (It)",
            "percentage": "59%",
            "yearOfPassedout": "2016"
        }
    },
    "experience": {
        "previousExperience": {
            "companyName": "Purple Soft Technology",
            "Position": "SEO Analyst",
            "period": "2018-19",
            "responsibility": "SEO"
        }
    },
    "personalSkills": [
        "Gaming"
    ],
    "technicalSkills": [
        "Digital Marketing",
        "HTML",
        "CSS",
        "JS"
    ]
}
});


问:
How to convert an app/apk as system/user app, including split-apk apps

Background

Without root, I know that it's possible to install a single, normal APK using Intent (here).

Given root, I know that it's possible to install it using this .

This will install the app like a normal installation process, as a user-app.

There is also a way to install a split apk app (here), though for some reason I didn't succeed using it.

The problem

I want to know how to convert and/or install an app to be a system-installed-app, and back to be a user-app.

This includes both APK files of apps that aren't yet installed, and of apps that are already installed.

What I've found

I've found some very old ways to convert an existing app (or installing a new one) into a system app (here, for example or here), saying (in short) I should just move the APK file into /system/app/ path.

Thing is, this might have worked in the past, but now it's not. I think the reason for this is that the apps on /system/app/ exist in a different way now: each app has a folder with some files inside of it.

As for converting back to user app, I can't find it. Same goes for installing a split apk app to system app and convert it back to user app.

In fact, there are apps on the Play store (such as this one) that I remember that could convert other apps into system apps just fine (using root) - now can't do anything.

The questions

When did the method of installing/converting an app to system app worked? How come it doesn't work anymore?

What should be done installing/converting an app to system app, and back to user app, on both old and new Android versions?

Is the same thing possible for split-apk apps (example: AirBnb app) , or at least installed ones?

答:
As I know the procedure which define system app has changed over the time.
The Privileged Permission Whitelisting AOSP documentation may help you:

Privileged applications are system applications located in the
  /system/priv-app directory on the system image. Historically, device
  implementers had little control over which signature|privileged
  permissions could be granted to privileged apps. Starting in Android
  8.0, implementors can explicitly whitelist privileged apps in the system configuration XML files in the /etc/permissions directory. Apps
  not explicitly listed in these XML files are not granted privileged
  permissions.


问:
ORA-00988: missing or invalid password(s)
I'm trying to change an oracle password:

```<code>alter user FOO identified by 'BAR';
</code>```

and I'm getting the following back:

```<code>Error starting at line 120 in command:
alter user FOO identified by 'BAR'
Error report:
SQL Error: ORA-00988: missing or invalid password(s)
00988. 00000 -  "missing or invalid password(s)"
</code>```

What's going on?

答: alter user davidl identified by "newpassword" replace "oldpassword";</p>

Body:
I'm trying to change an oracle password:

alter user FOO identified by 'BAR';

and I'm getting the following back:

Error starting at line 120 in command:
alter user FOO identified by 'BAR'
Error report:
SQL Error: ORA-00988: missing or invalid password(s)
00988. 00000 -  "missing or invalid password(s)"

What's going on?