问:
ConstratintLayout: How to center a view according to another view, vertically
I have the following code

```<code><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"
    android:padding="16dp"
    tools:context="gr.teiath.cs.android.tipcalculator.MainActivity">

    <TextView
        android:id="@+id/AmountLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Amount"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
        app:layout_constraintEnd_toStartOf="@id/AmountTV"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/Amount"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:digits="0123456789"
        android:inputType="numberDecimal"
        android:maxLength="10"
        android:maxLines="1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/AmountLabel"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</code>```

Which results in this

I do not know if I am describing it correctly but, I want to center the Amount TextView according to the Amount EditText vertically. Right now, the TextView is aligned to the top of the EditText. I want to make it like this.

I added 10dp of layout_marginTop for this, but I don't think it's the way to do it.
Thanks in advance.

答:
Try this

```<code><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"
    android:padding="16dp">

    <TextView
        android:id="@+id/AmountLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Amount"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBaseline_toBaselineOf="@id/Amount"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/Amount"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:digits="0123456789"
        android:inputType="numberDecimal"
        android:maxLength="10"
        android:maxLines="1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/AmountLabel"
        app:layout_constraintTop_toTopOf="parent" />

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

OUTPUT

Body:
I have the following code

<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"
    android:padding="16dp"
    tools:context="gr.teiath.cs.android.tipcalculator.MainActivity">

    <TextView
        android:id="@+id/AmountLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Amount"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
        app:layout_constraintEnd_toStartOf="@id/AmountTV"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/Amount"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:digits="0123456789"
        android:inputType="numberDecimal"
        android:maxLength="10"
        android:maxLines="1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/AmountLabel"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Which results in this

I do not know if I am describing it correctly but, I want to center the Amount TextView according to the Amount EditText vertically. Right now, the TextView is aligned to the top of the EditText. I want to make it like this.

I added 10dp of layout_marginTop for this, but I don't think it's the way to do it.
Thanks in advance.

Body:
Try this

<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"
    android:padding="16dp">

    <TextView
        android:id="@+id/AmountLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Amount"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBaseline_toBaselineOf="@id/Amount"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/Amount"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:digits="0123456789"
        android:inputType="numberDecimal"
        android:maxLength="10"
        android:maxLines="1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/AmountLabel"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

OUTPUT


来源: stackexchange

问:
what is the method to check logging hash encrypted password matches with saved hashed password in the database
I use sha512.js file and for security purpose I send my password as a hash value with post request. Now I want to check with the saves hash password in the database.
When I check my browser It can be seen password as a hash value. Then in my php file I get the password value with post request. then I want to check it with database saved value.

my post request password value like - 7d4ad2ce44e568064beb480525a563daf85c676795f4083b7e177553af273ffecff41c2bbbe64428d9c0ca37744bcea4de218d356037337bcd41129bb1681b13

```<code>$email = $_POST['email'];
$passwordFromPost = $_POST['p'];

// $passwordFromPost = '7d4ad2ce44e568064beb480525a563daf85c676795f4083b7e177553af273ffecff41c2bbbe64428d9c0ca37744bcea4de218d356037337bcd41129bb1681b13';
</code>```

my database password is -:

```<code>$hashedPasswordFromDB = '$2y$11$2Nmsc11WWGZ1xEB8P3zWCezVv4QCe48BVQ8vJbXOkByUXIioWH.AS'

if (password_verify($passwordFromPost, $hashedPasswordFromDB)) {
    echo 'Password is valid!';
} else {
</code>```

how check post request hash value with db hash value.

答:
Do not hash the password in the client, send it in plain text in POST data using HTTPS. Sending a hash of the password just makes the hash the password.

With PHP use password_hash and password_verify, the pair are secure and easy to use.

More info: When saving a password verifier just using a hash function is not sufficient and just adding a salt does little to improve the security. Instead  use a function such as PBKDF2, Rfc2898DeriveBytes, Argon2, password_hash, Bcrypt or similar functions with about a 100ms duration. The point is to make the attacker spend substantial of time finding passwords by brute force.

ContentLicense: CC BY-SA 3.0

Body:
I use sha512.js file and for security purpose I send my password as a hash value with post request. Now I want to check with the saves hash password in the database.
When I check my browser It can be seen password as a hash value. Then in my php file I get the password value with post request. then I want to check it with database saved value.

my post request password value like - 7d4ad2ce44e568064beb480525a563daf85c676795f4083b7e177553af273ffecff41c2bbbe64428d9c0ca37744bcea4de218d356037337bcd41129bb1681b13

$email = $_POST['email'];
$passwordFromPost = $_POST['p'];

// $passwordFromPost = '7d4ad2ce44e568064beb480525a563daf85c676795f4083b7e177553af273ffecff41c2bbbe64428d9c0ca37744bcea4de218d356037337bcd41129bb1681b13';

my database password is -:

$hashedPasswordFromDB = '$2y$11$2Nmsc11WWGZ1xEB8P3zWCezVv4QCe48BVQ8vJbXOkByUXIioWH.AS'

if (password_verify($passwordFromPost, $hashedPasswordFromDB)) {
    echo 'Password is valid!';
} else {

how check post request hash value with db hash value.


问:
Python, Stop a Thread
I'm trying to create a class that pings an ip address and keeps a record for connected/ not connected times.

Since this class is a part of a GUI, I wish to stop this thread when asked by user.

Found some Q&As regrading this issue, but neither one actually causes thread to stop.

I'm trying to make a method, a part of this class that will stop self.run()

Here's my Pinger class:

```<code>class Pinger(threading.Thread):
    def __init__(self, address='', rate=1):
        threading.Thread.__init__(self)

        self.address = address
        self.ping_rate = rate
        self.ping_vector, self.last_ping = [], -1
        self.start_time, self.last_status = datetime.datetime.now(), []
        self.timestamp, self.time_vector = 0, [datetime.timedelta(0)] * 4

    def run(self):
            self.start_ping()

    def start_ping(self):
        self.timestamp = datetime.datetime.now()
        while True:
            ping_result = os.system('ping %s -n 1 >Null' % self.address)
            self.ping_vector.append(ping_result)

            if self.last_ping != ping_result:
                text = ['Reachable', 'Lost']
                print(str(self.timestamp)[:-4], self.address, text[ping_result])

            round_time_qouta = datetime.datetime.now() - self.timestamp
            self.timestamp = datetime.datetime.now()
            self.update_time_counter(ping_result, round_time_qouta)

            self.last_ping = ping_result
            time.sleep(self.ping_rate)

    def update_time_counter(self, ping_result=0, time_quota=datetime.timedelta(0)):
        """self.time_vector = [[cons.succ ping time],[cons.not_succ ping time],
        [max accum succ ping time],[max accum not_succ ping time] """

        p_vec = [0, 1]

        self.time_vector[p_vec[ping_result]] += time_quota
        if self.time_vector[p_vec[ping_result]].total_seconds() > self.time_vector[
            p_vec[ping_result] + 2].total_seconds():
            self.time_vector[p_vec[ping_result] + 2] = self.time_vector[p_vec[ping_result]]

        self.time_vector[p_vec[ping_result - 1]] = datetime.timedelta(0)

        self.last_status = [ping_result, self.chop_milisecond(self.time_vector[ping_result]),
                            self.chop_milisecond(self.time_vector[ping_result + 2]),
                            self.chop_milisecond(datetime.datetime.now() - self.start_time)]

        print(str(self.timestamp)[:-4], "State: " + ['Received', 'Lost'][ping_result],
              " Duration: " + self.last_status[1], " Max Duration: " + self.last_status[2],
              "Total time: " + self.last_status[3])

    def chop_milisecond(self, time):
        return str(time).split('.')[0]
</code>```

答:
I would code your class a little bit differently, to run as a daemon.

leave start_ping code out and use next code :

```<code>MyPinger = threading.Thread(target = self.start_ping, name="Pinger")
MyPinger.setDaemon(True)
MyPinger.start() # launch start_ping
</code>```

and may use _Thread_stop() to stop it , that's a little bit brute...:

```<code>if MyPinger.IsAlive():
   MyPinger._Thread__stop()
</code>```

Title: Python, Stop a Thread

Body:
I'm trying to create a class that pings an ip address and keeps a record for connected/ not connected times.

Since this class is a part of a GUI, I wish to stop this thread when asked by user.

Found some Q&As regrading this issue, but neither one actually causes thread to stop.

I'm trying to make a method, a part of this class that will stop self.run()

Here's my Pinger class:

class Pinger(threading.Thread):
    def __init__(self, address='', rate=1):
        threading.Thread.__init__(self)

        self.address = address
        self.ping_rate = rate
        self.ping_vector, self.last_ping = [], -1
        self.start_time, self.last_status = datetime.datetime.now(), []
        self.timestamp, self.time_vector = 0, [datetime.timedelta(0)] * 4

    def run(self):
            self.start_ping()

    def start_ping(self):
        self.timestamp = datetime.datetime.now()
        while True:
            ping_result = os.system('ping %s -n 1 >Null' % self.address)
            self.ping_vector.append(ping_result)

            if self.last_ping != ping_result:
                text = ['Reachable', 'Lost']
                print(str(self.timestamp)[:-4], self.address, text[ping_result])

            round_time_qouta = datetime.datetime.now() - self.timestamp
            self.timestamp = datetime.datetime.now()
            self.update_time_counter(ping_result, round_time_qouta)

            self.last_ping = ping_result
            time.sleep(self.ping_rate)

    def update_time_counter(self, ping_result=0, time_quota=datetime.timedelta(0)):
        """self.time_vector = [[cons.succ ping time],[cons.not_succ ping time],
        [max accum succ ping time],[max accum not_succ ping time] """

        p_vec = [0, 1]

        self.time_vector[p_vec[ping_result]] += time_quota
        if self.time_vector[p_vec[ping_result]].total_seconds() > self.time_vector[
            p_vec[ping_result] + 2].total_seconds():
            self.time_vector[p_vec[ping_result] + 2] = self.time_vector[p_vec[ping_result]]

        self.time_vector[p_vec[ping_result - 1]] = datetime.timedelta(0)

        self.last_status = [ping_result, self.chop_milisecond(self.time_vector[ping_result]),
                            self.chop_milisecond(self.time_vector[ping_result + 2]),
                            self.chop_milisecond(datetime.datetime.now() - self.start_time)]

        print(str(self.timestamp)[:-4], "State: " + ['Received', 'Lost'][ping_result],
              " Duration: " + self.last_status[1], " Max Duration: " + self.last_status[2],
              "Total time: " + self.last_status[3])

    def chop_milisecond(self, time):
        return str(time).split('.')[0]

Body:
I would code your class a little bit differently, to run as a daemon.

leave start_ping code out and use next code :

MyPinger = threading.Thread(target = self.start_ping, name="Pinger")
MyPinger.setDaemon(True)
MyPinger.start() # launch start_ping

and may use _Thread_stop() to stop it , that's a little bit brute...:

if MyPinger.IsAlive():
   MyPinger._Thread__stop()


问:
Declaration or Definition in C
From External Variables Wiki:

If neither the extern keyword nor an
  initialization value are present, the
  statement can be either a declaration
  or a definition. It is up to the
  compiler to analyse the modules of the
  program and decide.

I was not able to fully grasp the meaning of this statement with respect to C. For example, does it imply that:

```<code>int i;
</code>```

is not necessarily a declaration (as I have been assuming until now), but could be a definition as well (by definition of Definition & Declaration on the same webpage, no puns intended)?

In a nutshell, is the above statement:
a. just a declaration, or
b. declaration +  definition?

Reference: Variable declaration and definition

Summary of answers received:

```<code>                         Declaration    Definition    Tentative Definition   Initialized
int i;   (inside a block)    Yes           Yes                No                No
int i=5; (inside a block)    Yes           Yes                No               Yes(to 5)
int i;   (otherwise)         Yes            No               Yes               Yes(to 0)
extern int i;                Yes            No                No                No

All definitions are declarations but not vice-versa.
</code>```

答:
The C standard says that

A definition of an identifier is a declaration for that identifier that: for an object, causes storage to be reserved for that object (…)

Definitions encompass declarations, i.e., every definition is necessarily a declaration, so it doesn’t make sense to say that

```<code>int i;
</code>```

is not a declaration. It is a declaration which also happens to be a definition. Or, it is a definition, hence a declaration.

ContentLicense: CC BY-SA 2.5

Title: Declaration or Definition in C

Body:
From External Variables Wiki:

If neither the extern keyword nor an
  initialization value are present, the
  statement can be either a declaration
  or a definition. It is up to the
  compiler to analyse the modules of the
  program and decide.

I was not able to fully grasp the meaning of this statement with respect to C. For example, does it imply that:

int i;

is not necessarily a declaration (as I have been assuming until now), but could be a definition as well (by definition of Definition & Declaration on the same webpage, no puns intended)?

In a nutshell, is the above statement:
a. just a declaration, or
b. declaration +  definition?

Reference: Variable declaration and definition

Summary of answers received:

                         Declaration    Definition    Tentative Definition   Initialized
int i;   (inside a block)    Yes           Yes                No                No
int i=5; (inside a block)    Yes           Yes                No               Yes(to 5)
int i;   (otherwise)         Yes            No               Yes               Yes(to 0)
extern int i;                Yes            No                No                No

All definitions are declarations but not vice-versa.

Body:
The C standard says that

A definition of an identifier is a declaration for that identifier that: for an object, causes storage to be reserved for that object (…)

Definitions encompass declarations, i.e., every definition is necessarily a declaration, so it doesn’t make sense to say that

int i;

is not a declaration. It is a declaration which also happens to be a definition. Or, it is a definition, hence a declaration.


问:
PropertyGrid - Show properties of a specific Interface, not all properties
I am currently facing an (IMHO) strange behavior of the PropertyGrid:

I have an interface (ITest) that defines some properties. This interface will be implemented by a Component or a Panel (TestImpl). The other part is a Component (TestComponent) that has a public property of the interface type. A default implementation will be assigend to that property and it could be changed by the user to a more specific implementation. If I add this TestComponent to a Form, I would expect, that by expanding the public-interface-property, only the properties declared in the interface will be visible - instead all properties of the Panel or Component are visible...

```<code>public interface ITest
{
    string AAAAA { get; set; }
}

public class TestImpl: Panel, ITest
{
    public string AAAAA { get; set; }
}

public class TestComponent : Component
{
    [TypeConverter(typeof(ExpandableObjectConverter))]
    public ITest Obj { get; set; }
    public TestComponent()
    {
        Obj = new TestImpl();
    }
}

// To reproduce create a simple Form, add a PropertyGrid, create and assign the TestComponent
public partial class Form4 : Form
{
    public Form4()
    {
        InitializeComponent();

        var comp = new TestComponent();
        comp.Obj.AAAAA = "Some Text";

        propertyGrid1.SelectedObject = comp;
    }
}
</code>```

Is there a way to show only the interface-properties?

答:
PropertyGrid by default shows display name of all public properties of your control which are browsable. It uses TypeDescriptor of your object to ask about its metadata including its browsable properties and their display names.

To customize this behavior you need to register a new TypeDescriptionProvider for your object.

Example

In the following example, I've created a  MyPanel control which derives from Panel and implements IMyInterface. Then I created a custom MyTypeDescriptionProvider<T> and set MyTypeDescriptionProvider<IMyInterface> as TypeDescriptionProvider of my control.

This way, when you set an instance of MyPanel as SelectedObject of the PropertyGrid, only properties of IMyInterface will be shown in PropertyGrid.

```<code>using System;
using System.ComponentModel;
using System.Windows.Forms;

public interface IMyInterface
{
    string MyProperty1 { get; set; }
    string MyProperty2 { get; set; }
}

public class MyTypeDescriptionProvider<T> : TypeDescriptionProvider
{
    public MyTypeDescriptionProvider() : base(TypeDescriptor.GetProvider(typeof(T))) { }

    public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType,
        object instance)
    {
        return base.GetTypeDescriptor(typeof(T), instance);
    }
}

[TypeDescriptionProvider(typeof(MyTypeDescriptionProvider<IMyInterface>))]
public class MyPanel : Panel, IMyInterface
{
    public string MyProperty1 { get; set; }
    public string MyProperty2 { get; set; }
}
</code>```

Note: As an important note, keep in mind that such functionality is not useful for design-time at all. Because at design time, you need to show properties of the control in PropertyGrid in designer and you need to let the designer knows about those properties to be able to serialize values for them.

Body:
I am currently facing an (IMHO) strange behavior of the PropertyGrid:

I have an interface (ITest) that defines some properties. This interface will be implemented by a Component or a Panel (TestImpl). The other part is a Component (TestComponent) that has a public property of the interface type. A default implementation will be assigend to that property and it could be changed by the user to a more specific implementation. If I add this TestComponent to a Form, I would expect, that by expanding the public-interface-property, only the properties declared in the interface will be visible - instead all properties of the Panel or Component are visible...

public interface ITest
{
    string AAAAA { get; set; }
}

public class TestImpl: Panel, ITest
{
    public string AAAAA { get; set; }
}

public class TestComponent : Component
{
    [TypeConverter(typeof(ExpandableObjectConverter))]
    public ITest Obj { get; set; }
    public TestComponent()
    {
        Obj = new TestImpl();
    }
}

// To reproduce create a simple Form, add a PropertyGrid, create and assign the TestComponent
public partial class Form4 : Form
{
    public Form4()
    {
        InitializeComponent();

        var comp = new TestComponent();
        comp.Obj.AAAAA = "Some Text";

        propertyGrid1.SelectedObject = comp;
    }
}

Is there a way to show only the interface-properties?

Body:
PropertyGrid by default shows display name of all public properties of your control which are browsable. It uses TypeDescriptor of your object to ask about its metadata including its browsable properties and their display names.

To customize this behavior you need to register a new TypeDescriptionProvider for your object.

Example

In the following example, I've created a  MyPanel control which derives from Panel and implements IMyInterface. Then I created a custom MyTypeDescriptionProvider<T> and set MyTypeDescriptionProvider<IMyInterface> as TypeDescriptionProvider of my control.

This way, when you set an instance of MyPanel as SelectedObject of the PropertyGrid, only properties of IMyInterface will be shown in PropertyGrid.

using System;
using System.ComponentModel;
using System.Windows.Forms;

public interface IMyInterface
{
    string MyProperty1 { get; set; }
    string MyProperty2 { get; set; }
}

public class MyTypeDescriptionProvider<T> : TypeDescriptionProvider
{
    public MyTypeDescriptionProvider() : base(TypeDescriptor.GetProvider(typeof(T))) { }

    public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType,
        object instance)
    {
        return base.GetTypeDescriptor(typeof(T), instance);
    }
}

[TypeDescriptionProvider(typeof(MyTypeDescriptionProvider<IMyInterface>))]
public class MyPanel : Panel, IMyInterface
{
    public string MyProperty1 { get; set; }
    public string MyProperty2 { get; set; }
}

Note: As an important note, keep in mind that such functionality is not useful for design-time at all. Because at design time, you need to show properties of the control in PropertyGrid in designer and you need to let the designer knows about those properties to be able to serialize values for them.


问:
How can i update my table on server when i add new records in Mysql query browser on my locall pc?
I use Mysql query browser on my pc for data entry,appreciate that let me how can i update my table on server after enter new records in Mysql query browser? is there any way that we sync to table(on server and on client )and sending new records to server?

thanks

答: If you want to keep your local and remote MySQL databases in sync, the obvious solution would be to use the replication features built into MySQL.</p>


问:
How to create a custom connector for Presto and InfluxDB
I am trying to create a custom connector for Presto and InfluxDB in order to make it possible for Presto to run SQL queries on InfluxDB. Are there any examples of such a connector being available already?

```<code>Connectors are the source of all data for queries in Presto. Even if your data source doesn’t have underlying tables backing it, as long as you adapt your data source to the API expected by Presto, you can write queries against this data.
</code>```

The only documentation that I found for writing a connector is:
    https://prestodb.io/docs/current/develop/example-http.html

If anyone has other examples, can you please share it?

答:
There are multiple connectors in the presto source tree.

When you're connecting to a data source having JDBC driver (probably not your case), extending presto-base-jdbc driver gives you almost all you need. See for example https://github.com/trinodb/trino/tree/master/presto-postgresql

When you're connecting to a non-JDBC-enabled data source (or you need more that it's possible with presto-base-jdbc), you need to implement all the relevant connector interfaces. There isn't good documentation for this other than Java interfaces & source code, but you can follow examples e.g. https://github.com/trinodb/trino/tree/master/presto-cassandra, https://github.com/trinodb/trino/tree/master/presto-accumulo

Yet another option is Greg Leclercq's suggestion to implement a Thrift connector. See his answer for directions.

Body:
I am trying to create a custom connector for Presto and InfluxDB in order to make it possible for Presto to run SQL queries on InfluxDB. Are there any examples of such a connector being available already?

Connectors are the source of all data for queries in Presto. Even if your data source doesn’t have underlying tables backing it, as long as you adapt your data source to the API expected by Presto, you can write queries against this data.

The only documentation that I found for writing a connector is:
    https://prestodb.io/docs/current/develop/example-http.html

If anyone has other examples, can you please share it?

ContentLicense: CC BY-SA 4.0


问:
Reporting tools for embedding in web application
Salesforce has a built-in reporting tool which is good. I need something similar to the salesforce reporting tools to embed to our web-based application (java, xhtml). The reporting tool must be able to display flat data, drag and drop dataset fields, group, sort, summarize (sum, average, max, min).  Any recommendations?</p>

答:
Hope it can be still helpful for you or someone with the same request.

WebDataRocks, can be a good fit. It's free and, I'd say, easy in use. It's web based reporting tool, easy integrated and has all common Excel-like features, which are needed for pivoting: drag and drop dataset fields, grouping, sorting, summarizing( sum, average, max, min) etc.

You сan check out the demo (https://www.webdatarocks.com/demos/javascript-pivot-table-demo/) and deside if it fits you.
Good luck!


问:
How to use next value for MySQL trigger ?
I have created a sample table in MySQL with following query .

```<code>create table table_1 (
  arg1 bigint not null unique,
  arg2 bigint not null default 0,
  arg3 bigint not null default 0,
  agr4 bigint not null default 0,
  arg5 bigint not null default 0,
  constraint shdk_test foreign key(arg1) references arg1(id)
  on delete cascade on update restrict
);
</code>```

Now i am trying to run a trigger with following command

```<code>   insert into table_1(arg1, arg2, arg3, agr4, arg5) values(new.id,
   (next value for revision), (next value for revision), (next value for revision), (next value for revision));
</code>```

After running this trigger , i am getting error on next value for revision . I want to know whether next value for is supporting in MySQL ? It is supporting in DB2 or any alternative for MySQL ? please help .

答:
NEXT VALUE FOR and NEXTVAL are SQL variation commands for Transact-SQL and Oracle respectively. Other SQL databases, including MySQL, do not support that.

Digging over on Stack Exchange DBA I came across this post:
https://dba.stackexchange.com/questions/19019/mysql-get-next-unique-value-without-auto-increment/19020#19020

Or you could after the create table use an insert similar to this:

```<code>INSERT INTO table_1 SELECT arg2 = (SELECT MAX(arg2) + 1 FROM table_1);
</code>```

and do the same with the other arg columns. A procedure could make this more automatic and you could call it when inserting rows.

Body:
I have created a sample table in MySQL with following query .

create table table_1 (
  arg1 bigint not null unique,
  arg2 bigint not null default 0,
  arg3 bigint not null default 0,
  agr4 bigint not null default 0,
  arg5 bigint not null default 0,
  constraint shdk_test foreign key(arg1) references arg1(id)
  on delete cascade on update restrict
);

Now i am trying to run a trigger with following command

   insert into table_1(arg1, arg2, arg3, agr4, arg5) values(new.id,
   (next value for revision), (next value for revision), (next value for revision), (next value for revision));

After running this trigger , i am getting error on next value for revision . I want to know whether next value for is supporting in MySQL ? It is supporting in DB2 or any alternative for MySQL ? please help .

Body:
NEXT VALUE FOR and NEXTVAL are SQL variation commands for Transact-SQL and Oracle respectively. Other SQL databases, including MySQL, do not support that.

Digging over on Stack Exchange DBA I came across this post:
https://dba.stackexchange.com/questions/19019/mysql-get-next-unique-value-without-auto-increment/19020#19020

Or you could after the create table use an insert similar to this:

INSERT INTO table_1 SELECT arg2 = (SELECT MAX(arg2) + 1 FROM table_1);

and do the same with the other arg columns. A procedure could make this more automatic and you could call it when inserting rows.


问:
Why I cannot compile with -fPIE but can with -fPIC?
I have one interesting compilation problem.
At first, please see code to be compiled.

```<code>$ ls
Makefile main.c sub.c sub.h
$ gcc -v
...
gcc version 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC)
</code>```

```<code>## Makefile
%.o: CFLAGS+=-fPIE #[2]

main.so: main.o sub.o
    $(CC) -shared -fPIC -o $@ $^
</code>```

//main.c
#include "sub.h"

int main_func(void){
    sub_func();
    subsub_func();

    return 0;
}
```

<pre class="lang-c prettyprint-override"><code>//sub.h
#pragma once
void subsub_func(void);
void sub_func(void);
</code>```

//sub.c
#include "sub.h"
#include <stdio.h>
void subsub_func(void){
    printf("%s\n", __func__);
}
void sub_func(void){
    subsub_func();//[1]
    printf("%s\n", __func__);
}
```

<p>And I compile this and got a error as below</p>

<pre class="lang-sh prettyprint-override"><code>$ LANG=en make
cc -fPIE   -c -o main.o main.c
cc -fPIE   -c -o sub.o sub.c
cc -shared -fPIC -o main.so main.o sub.o
/usr/bin/ld: sub.o: relocation R_X86_64_PC32 against symbol `subsub_func' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: Bad value
collect2: error: ld returned 1 exit status
make: *** [main.so] Error 1
</code>```

And after this, I modified the code(removing a line [1]/using -fPIC instead of -PIE[2]) and then successfully compiled these.

$ make #[1]
cc -fPIE   -c -o main.o main.c
cc -fPIE   -c -o sub.o sub.c
cc -shared -fPIC -o main.so main.o sub.o
$ make #[2]
cc -fPIC   -c -o main.o main.c
cc -fPIC   -c -o sub.o sub.c
cc -shared -fPIC -o main.so main.o sub.o
```

Why did this phenomenon happened?

I have heard that calling a function within an object is done through PLT when it is compiled with -fPIC but done by jumping to the function directly when it si compiled with -fPIE.
I guessed that the function call mechanism with -fPIE refrains from relocation.
But I would like to know exact and accurate explanation of that.

Would you help me?

Thank you, all.

答:
The only code generation difference between -fPIC and -fPIE for the code shown is in the call from sub_func to subsub_func.  With -fPIC, that call goes through the PLT; with -fPIE, it's a direct call.  In assembly dumps (cc -S), that looks like this:

```<code>--- sub.s.pic   2017-12-07 08:10:00.308149431 -0500
+++ sub.s.pie   2017-12-07 08:10:08.408068650 -0500
@@ -34,7 +34,7 @@ sub_func:
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
-   call    subsub_func@PLT
+   call    subsub_func
    leaq    __func__.2258(%rip), %rsi
    leaq    .LC0(%rip), %rdi
    movl    $0, %eax
</code>```

In unlinked object files, it's a change of relocation type:

```<code>--- sub.o.dump.pic  2017-12-07 08:13:54.197775840 -0500
+++ sub.o.dump.pie  2017-12-07 08:13:54.197775840 -0500
@@ -22,7 +22,7 @@
   1f:  55                      push   %rbp
   20:  48 89 e5                mov    %rsp,%rbp
   23:  e8 00 00 00 00          callq  28 <sub_func+0x9>
-           24: R_X86_64_PLT32  subsub_func-0x4
+           24: R_X86_64_PC32   subsub_func-0x4
   28:  48 8d 35 00 00 00 00    lea    0x0(%rip),%rsi        # 2f <sub_func+0x10>
            2b: R_X86_64_PC32   .rodata+0x14
   2f:  48 8d 3d 00 00 00 00    lea    0x0(%rip),%rdi        # 36 <sub_func+0x17>
</code>```

And, on this architecture, when you link a shared library using cc -shared, the linker does not allow the input object files to contain R_X86_64_PC32 relocations targeting global symbols, thus the error you observed when you used -fPIE instead of -fPIC.

Now, you are probably wondering why direct calls within a shared library are not allowed.  In fact, they are allowed, but only when the callee is not a global.  For instance, if you declared subsub_func with static, then the call target would be resolved by the assembler and there would be no relocation at all in the object file, and if you declared it with __attribute__((visibility("hidden"))) then you would get an R_X86_64_PC32 relocation but the linker would allow it because the callee is no longer exported from the library.  But in both cases subsub_func would not be callable from outside the library anymore.

Now you're probably wondering what it is about global symbols that means you have to call them through the PLT from a shared library.  This has to do with an aspect of the ELF symbol resolution rules that you may find surprising: any global symbol in a shared library can be overridden by either the executable, or an earlier library in the link order.  Concretely, if we leave your sub.h and sub.c alone but make main.c read like this:

```<code>//main.c
#include "sub.h"
#include <stdio.h>

void subsub_func(void) {
    printf("%s (main)\n", __func__);
}

int main(void){
    sub_func();
    subsub_func();

    return 0;
}
</code>```

so it's now got the an official executable entry point in it but also a second definition of subsub_func, and we compile sub.c into a shared library and main.c into an executable that calls it, and run the whole thing, like this

```<code>$ cc -fPIC -c sub.c -o sub.o
$ cc -c main.c -o main.o
$ cc -shared -Wl,-soname,libsub.so.1 sub.o -o libsub.so.1
$ ln -s libsub.so.1 libsub.so
$ cc main.o -o main -L. -lsub
$ LD_LIBRARY_PATH=. ./main
</code>```

the output will be

```<code>subsub_func (main)
sub_func
subsub_func (main)
</code>```

That is, both the call from main to subsub_func, and the call from sub_func, within the library, to subsub_func, were resolved to the definition in the executable.  For that to be possible, the call from sub_func must go through the PLT.

You can change this behavior with an additional linker switch, -Bsymbolic.

```<code>$ cc -shared -Wl,-soname,libsub.so.1 -Wl,-Bsymbolic sub.o -o libsub.so.1
$ LD_LIBRARY_PATH=. ./main
subsub_func
sub_func
subsub_func (main)
</code>```

Now the call from sub_func is resolved to the definition within the library.  In this case, using -Bsymbolic allows sub.c to be compiled with -fPIE instead of -fPIC, but I don't recommend you do that.  There are other effects of using -fPIE instead of -fPIC, such as changing how access to thread-local storage needs to be done, and those cannot be worked around with -Bsymbolic.

Body:
I have one interesting compilation problem.
At first, please see code to be compiled.

$ ls
Makefile main.c sub.c sub.h
$ gcc -v
...
gcc version 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC)

## Makefile
%.o: CFLAGS+=-fPIE #[2]

main.so: main.o sub.o
    $(CC) -shared -fPIC -o $@ $^

//main.c
#include "sub.h"

int main_func(void){
    sub_func();
    subsub_func();

    return 0;
}

//sub.h
#pragma once
void subsub_func(void);
void sub_func(void);

//sub.c
#include "sub.h"
#include <stdio.h>
void subsub_func(void){
    printf("%s\n", __func__);
}
void sub_func(void){
    subsub_func();//[1]
    printf("%s\n", __func__);
}

And I compile this and got a error as below

$ LANG=en make
cc -fPIE   -c -o main.o main.c
cc -fPIE   -c -o sub.o sub.c
cc -shared -fPIC -o main.so main.o sub.o
/usr/bin/ld: sub.o: relocation R_X86_64_PC32 against symbol `subsub_func' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: Bad value
collect2: error: ld returned 1 exit status
make: *** [main.so] Error 1

And after this, I modified the code(removing a line [1]/using -fPIC instead of -PIE[2]) and then successfully compiled these.

$ make #[1]
cc -fPIE   -c -o main.o main.c
cc -fPIE   -c -o sub.o sub.c
cc -shared -fPIC -o main.so main.o sub.o
$ make #[2]
cc -fPIC   -c -o main.o main.c
cc -fPIC   -c -o sub.o sub.c
cc -shared -fPIC -o main.so main.o sub.o

Why did this phenomenon happened?

I have heard that calling a function within an object is done through PLT when it is compiled with -fPIC but done by jumping to the function directly when it si compiled with -fPIE.
I guessed that the function call mechanism with -fPIE refrains from relocation.
But I would like to know exact and accurate explanation of that.

Would you help me?

Thank you, all.

Body:
The only code generation difference between -fPIC and -fPIE for the code shown is in the call from sub_func to subsub_func.  With -fPIC, that call goes through the PLT; with -fPIE, it's a direct call.  In assembly dumps (cc -S), that looks like this:

--- sub.s.pic   2017-12-07 08:10:00.308149431 -0500
+++ sub.s.pie   2017-12-07 08:10:08.408068650 -0500
@@ -34,7 +34,7 @@ sub_func:
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
-   call    subsub_func@PLT
+   call    subsub_func
    leaq    __func__.2258(%rip), %rsi
    leaq    .LC0(%rip), %rdi
    movl    $0, %eax

In unlinked object files, it's a change of relocation type:

--- sub.o.dump.pic  2017-12-07 08:13:54.197775840 -0500
+++ sub.o.dump.pie  2017-12-07 08:13:54.197775840 -0500
@@ -22,7 +22,7 @@
   1f:  55                      push   %rbp
   20:  48 89 e5                mov    %rsp,%rbp
   23:  e8 00 00 00 00          callq  28 <sub_func+0x9>
-           24: R_X86_64_PLT32  subsub_func-0x4
+           24: R_X86_64_PC32   subsub_func-0x4
   28:  48 8d 35 00 00 00 00    lea    0x0(%rip),%rsi        # 2f <sub_func+0x10>
            2b: R_X86_64_PC32   .rodata+0x14
   2f:  48 8d 3d 00 00 00 00    lea    0x0(%rip),%rdi        # 36 <sub_func+0x17>

And, on this architecture, when you link a shared library using cc -shared, the linker does not allow the input object files to contain R_X86_64_PC32 relocations targeting global symbols, thus the error you observed when you used -fPIE instead of -fPIC.

Now, you are probably wondering why direct calls within a shared library are not allowed.  In fact, they are allowed, but only when the callee is not a global.  For instance, if you declared subsub_func with static, then the call target would be resolved by the assembler and there would be no relocation at all in the object file, and if you declared it with __attribute__((visibility("hidden"))) then you would get an R_X86_64_PC32 relocation but the linker would allow it because the callee is no longer exported from the library.  But in both cases subsub_func would not be callable from outside the library anymore.

Now you're probably wondering what it is about global symbols that means you have to call them through the PLT from a shared library.  This has to do with an aspect of the ELF symbol resolution rules that you may find surprising: any global symbol in a shared library can be overridden by either the executable, or an earlier library in the link order.  Concretely, if we leave your sub.h and sub.c alone but make main.c read like this:

//main.c
#include "sub.h"
#include <stdio.h>

void subsub_func(void) {
    printf("%s (main)\n", __func__);
}

int main(void){
    sub_func();
    subsub_func();

    return 0;
}

so it's now got the an official executable entry point in it but also a second definition of subsub_func, and we compile sub.c into a shared library and main.c into an executable that calls it, and run the whole thing, like this

$ cc -fPIC -c sub.c -o sub.o
$ cc -c main.c -o main.o
$ cc -shared -Wl,-soname,libsub.so.1 sub.o -o libsub.so.1
$ ln -s libsub.so.1 libsub.so
$ cc main.o -o main -L. -lsub
$ LD_LIBRARY_PATH=. ./main

the output will be

subsub_func (main)
sub_func
subsub_func (main)

That is, both the call from main to subsub_func, and the call from sub_func, within the library, to subsub_func, were resolved to the definition in the executable.  For that to be possible, the call from sub_func must go through the PLT.

You can change this behavior with an additional linker switch, -Bsymbolic.

$ cc -shared -Wl,-soname,libsub.so.1 -Wl,-Bsymbolic sub.o -o libsub.so.1
$ LD_LIBRARY_PATH=. ./main
subsub_func
sub_func
subsub_func (main)

Now the call from sub_func is resolved to the definition within the library.  In this case, using -Bsymbolic allows sub.c to be compiled with -fPIE instead of -fPIC, but I don't recommend you do that.  There are other effects of using -fPIE instead of -fPIC, such as changing how access to thread-local storage needs to be done, and those cannot be worked around with -Bsymbolic.


问:
How can I configure SpringBoot with Thymeleaf and use sec:authentication tag
Im using spring-boot 1.2.5 + thymeleaf + spring security for my application.

I need to display the username in my website, after doing some research seems that I should use code something like:

```<code><div sec:authentication="name">The value of the "name" property of
        the authentication object should appear here.</div>
</code>```

However I don't get Thymeleaf to parse that tag.  Please I need some help :(

答:
In Spring Boot, besides adding the compile dependency:

```<code>compile 'org.thymeleaf.extras:thymeleaf-extras-springsecurity3:'2.1.3.RELEASE'
</code>```

I had to add a bean for the dialect:

```<code>@Bean
IDialect springSecurityDialect() {
    new SpringSecurityDialect()
}
</code>```

Only then does Spring Boot's autoconfiguration pick up the dialect by asking the context for all the IDialect beans:

```<code>public ThymeleafDefaultConfiguration(
        Collection<ITemplateResolver> templateResolvers,
        ObjectProvider<Collection<IDialect>> dialectsProvider) {
    this.templateResolvers = templateResolvers;
    this.dialects = dialectsProvider.getIfAvailable();
}
</code>```

Body:
Im using spring-boot 1.2.5 + thymeleaf + spring security for my application.

I need to display the username in my website, after doing some research seems that I should use code something like:

The value of the "name" property of
        the authentication object should appear here.

However I don't get Thymeleaf to parse that tag.  Please I need some help :(

Body:
In Spring Boot, besides adding the compile dependency:

compile 'org.thymeleaf.extras:thymeleaf-extras-springsecurity3:'2.1.3.RELEASE'

I had to add a bean for the dialect:

@Bean
IDialect springSecurityDialect() {
    new SpringSecurityDialect()
}

Only then does Spring Boot's autoconfiguration pick up the dialect by asking the context for all the IDialect beans:

public ThymeleafDefaultConfiguration(
        Collection<ITemplateResolver> templateResolvers,
        ObjectProvider<Collection<IDialect>> dialectsProvider) {
    this.templateResolvers = templateResolvers;
    this.dialects = dialectsProvider.getIfAvailable();
}


问:
simpest way to get audio/video data from directshow
I compiled the DirectShow sample player (from the Windows SDK's "Samples\multimedia\directshow\players\dshowplayer" folder).

Everything works well but it renders directly to the screen and the audio goes directly to directsound.  I need to be able to grab the data and write out images to BMPs and write out the audio to .wav.

Am I using the wrong sample as a starting point?  If not, what is the easiest way to modify the sample so I can get access to the video and audio data?

Thanks!

答: You can insert a SampleGrabber filter before the renderer, and use the ISampleGrabberCB Interface to access the data. You can still render the video to the screen, and output the audio. If you don't want that, use a NullRenderer instead. See also this example on codeproject. </p>


问:
How can I use RxJS to generate a requestAnimationFrame loop?
My goal is to create an animation loop à la requestAnimationFrame so that I could do something like this:

```<code>animationObservable.subscribe(() =>
{
    // drawing code here
});
</code>```

I tried this code as a basic test:

```<code>let x = 0;

Rx.Observable
    .of(0)
    .repeat(Rx.Scheduler.animationFrame)
    .takeUntil(Rx.Observable.timer(1000))
    .subscribe(() => console.log(x++));
</code>```

Here is a JSFiddle but I'm not liable for any browser crashes from running this.

I expected this to log the numbers from 0 to approximately 60 (because that is my monitor's refresh rate) over 1 second. Instead, it rapidly logs numbers (much faster than requestAnimationFrame would), begins to cause the page to lag, and finally overflows the stack around 10000 and several seconds later.

Why does the animationFrame scheduler behave this way, and what is the correct way to run an animation loop with RxJS?

答:
This is how I use requestAnimationFrame with rxjs. I've seen a lot of developers using 0 instead of animationFrame.now(). It's much better to pass the time because you often need that in animations.

const { Observable, Scheduler } = Rx;

const requestAnimationFrame$ = Observable
  .defer(() => Observable
    .of(Scheduler.animationFrame.now(), Scheduler.animationFrame)
    .repeat()
    .map(start => Scheduler.animationFrame.now() - start)
  );

// Example usage
const duration$ = duration => requestAnimationFrame$
  .map(time => time / duration)
  .takeWhile(progress => progress < 1)
  .concat([1])

duration$(60000)
  .subscribe((i) => {
    clockPointer.style.transform = `rotate(${i * 360}deg)`;
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/@reactivex/rxjs@5.0.3/dist/global/Rx.js"></script>

<div style="border: 3px solid black; border-radius: 50%; width: 150px; height: 150px;">
  <div id="clockPointer" style="width: 2px; height: 50%; background: black; margin-left: 50%; padding-left: -1px; transform-origin: 50% 100%;"></div>
</div></code>```

Body:
My goal is to create an animation loop à la requestAnimationFrame so that I could do something like this:

animationObservable.subscribe(() =>
{
    // drawing code here
});

I tried this code as a basic test:

let x = 0;

Rx.Observable
    .of(0)
    .repeat(Rx.Scheduler.animationFrame)
    .takeUntil(Rx.Observable.timer(1000))
    .subscribe(() => console.log(x++));

Here is a JSFiddle but I'm not liable for any browser crashes from running this.

I expected this to log the numbers from 0 to approximately 60 (because that is my monitor's refresh rate) over 1 second. Instead, it rapidly logs numbers (much faster than requestAnimationFrame would), begins to cause the page to lag, and finally overflows the stack around 10000 and several seconds later.

Why does the animationFrame scheduler behave this way, and what is the correct way to run an animation loop with RxJS?

Body:
This is how I use requestAnimationFrame with rxjs. I've seen a lot of developers using 0 instead of animationFrame.now(). It's much better to pass the time because you often need that in animations.

const { Observable, Scheduler } = Rx;

const requestAnimationFrame$ = Observable
  .defer(() => Observable
    .of(Scheduler.animationFrame.now(), Scheduler.animationFrame)
    .repeat()
    .map(start => Scheduler.animationFrame.now() - start)
  );

// Example usage
const duration$ = duration => requestAnimationFrame$
  .map(time => time / duration)
  .takeWhile(progress => progress < 1)
  .concat([1])

duration$(60000)
  .subscribe((i) => {
    clockPointer.style.transform = `rotate(${i * 360}deg)`;
  });

<script src="https://unpkg.com/@reactivex/rxjs@5.0.3/dist/global/Rx.js"></script>

<div style="border: 3px solid black; border-radius: 50%; width: 150px; height: 150px;">
  <div id="clockPointer" style="width: 2px; height: 50%; background: black; margin-left: 50%; padding-left: -1px; transform-origin: 50% 100%;"></div>
</div>


问:
How to duplicate directory in git, tracking new files?
Is there a simple way to create a copy of a folder in a local repository, keeping track of exactly the same files (do not care about commit history, or untracked files)? </p>

<p>Folder contains a hierarchy of both tracked and untracked (but not ignored) files and directories. I basically want to recursively replicate the tracked structure. Is there a way apart of copying everything, then manually adding only the relevant files (there are a lot of them)? </p>

答:
If you want to have two separately same projects in git, follow this command lines:

```<code>$ mkdir "duplicated_project"
$ cd "your_project_path"
$ sudo cp -R * "duplicated_project_path/"
</code>```

Then you must add/define this duplicated project on git, so you can follow:

Adding an existing project to GitHub using the command line tutorial:

GitHub Reference

Or

You can duplicate your project in web ui:

i.e. if you are using from the Gitlab you can duplicate/export your project, such as bellow instruction:

In the left side in Setting tab --> select General --> expand Export project --> click on export.

Then  follow this command line:

```<code>$ git clone "duplicated/exported_project"
</code>```

[NOTE]:

In these mentioned approaches have not interfered commits.

Body:
Is there a simple way to create a copy of a folder in a local repository, keeping track of exactly the same files (do not care about commit history, or untracked files)?

Folder contains a hierarchy of both tracked and untracked (but not ignored) files and directories. I basically want to recursively replicate the tracked structure. Is there a way apart of copying everything, then manually adding only the relevant files (there are a lot of them)?

Body:
If you want to have two separately same projects in git, follow this command lines:

$ mkdir "duplicated_project"
$ cd "your_project_path"
$ sudo cp -R * "duplicated_project_path/"

Then you must add/define this duplicated project on git, so you can follow:

Adding an existing project to GitHub using the command line tutorial:

GitHub Reference

Or

You can duplicate your project in web ui:

i.e. if you are using from the Gitlab you can duplicate/export your project, such as bellow instruction:

In the left side in Setting tab --> select General --> expand Export project --> click on export.

Then  follow this command line:

$ git clone "duplicated/exported_project"

[NOTE]:

In these mentioned approaches have not interfered commits.


问:
Calculating ratio in R
If I have this data set:
    Name <- c("Bill", "Ben", "Lisa", "Maya")
     Xnum <- c(5, NA, 10, NA)
     Ynum <- c(10, 5, NA, NA)
     MyData <- data.frame(Name, Xnum, Ynum)

This gives me a data set of:

```<code> `print(MyData)
  Name Xnum Ynum
1 Bill    5   10
2  Ben   NA    5
3 Lisa   10   NA
4 Maya   NA   NA`
</code>```

Dividing X by Y will give me a ratio which I want. This is easy to do
    MyData$Ratio <- MyData$Xnum / MyData$Ynum

the problem is the values with NA's in them. In those cases I have the following requirement

```<code>`If Xnum == NA AND Ynum == NA
    Ratio = 1
Else if Xnum == NA AND Ynum >= 0
    Ratio = 1
Else if Xnum >= 0 AND Ynum == NA
    Ratio = 0
Else
    Ratio = Xnum / Ynum`
</code>```

I tried it as a function passing in Xnum and Ynum and returning ratio but it is not doing what I expect it to. The function is:

```<code>`determine_ratios <- function( PrevTotal, AllTotal ) {

    if ( (is.na(PrevTotal)) && (is.na(AllTotal)) ) {
        return(as.double(1.0))
    } else if ((PrevTotal  >= 0) && (is.na(AllTotal)) ) {
        return(as.double(1.0))
    } else if ((is.na(PrevTotal)) && (AllTotal >= 0) ) {
        return(as.double(0.0))
    } else {
        return(as.double(PrevTotal / AllTotal ))
    }
}`
</code>```

And I have called it as this:

```<code>`MyData$Ratios <- determine_ratios(MyData$Xnum, MyData$Ynum)`
</code>```

The output I get is this:

```<code>`print(MyData)
  Name Xnum Ynum Ratios
1 Bill    5   10    0.5
2  Ben   NA    5     NA
3 Lisa   10   NA     NA
4 Maya   NA   NA     NA`
</code>```

The expected output would be:

```<code>`print(MyData)
  Name Xnum Ynum Ratios
1 Bill    5   10    0.5
2  Ben   NA    5     1
3 Lisa   10   NA     0
4 Maya   NA   NA     1`
</code>```

Thanks

答:
Use case_when from the dplyr package:

```<code>library(dplyr)

MyData$Ratios <-
case_when(
    is.na(MyData$Xnum) & is.na(MyData$Ynum) ~ 1,
    is.na(MyData$Xnum) & MyData$Ynum >= 0 ~ 1,
    MyData$Xnum >= 0 & is.na(MyData$Ynum) ~ 0,
    TRUE ~ MyData$Xnum / MyData$Ynum
)
</code>```

Title: Calculating ratio in R

Body:
If I have this data set:
    Name <- c("Bill", "Ben", "Lisa", "Maya")
     Xnum <- c(5, NA, 10, NA)
     Ynum <- c(10, 5, NA, NA)
     MyData <- data.frame(Name, Xnum, Ynum)

This gives me a data set of:

 `print(MyData)
  Name Xnum Ynum
1 Bill    5   10
2  Ben   NA    5
3 Lisa   10   NA
4 Maya   NA   NA`

Dividing X by Y will give me a ratio which I want. This is easy to do
    MyData$Ratio <- MyData$Xnum / MyData$Ynum

the problem is the values with NA's in them. In those cases I have the following requirement

`If Xnum == NA AND Ynum == NA
    Ratio = 1
Else if Xnum == NA AND Ynum >= 0
    Ratio = 1
Else if Xnum >= 0 AND Ynum == NA
    Ratio = 0
Else
    Ratio = Xnum / Ynum`

I tried it as a function passing in Xnum and Ynum and returning ratio but it is not doing what I expect it to. The function is:

`determine_ratios <- function( PrevTotal, AllTotal ) {

    if ( (is.na(PrevTotal)) && (is.na(AllTotal)) ) {
        return(as.double(1.0))
    } else if ((PrevTotal  >= 0) && (is.na(AllTotal)) ) {
        return(as.double(1.0))
    } else if ((is.na(PrevTotal)) && (AllTotal >= 0) ) {
        return(as.double(0.0))
    } else {
        return(as.double(PrevTotal / AllTotal ))
    }
}`

And I have called it as this:

`MyData$Ratios <- determine_ratios(MyData$Xnum, MyData$Ynum)`

The output I get is this:

`print(MyData)
  Name Xnum Ynum Ratios
1 Bill    5   10    0.5
2  Ben   NA    5     NA
3 Lisa   10   NA     NA
4 Maya   NA   NA     NA`

The expected output would be:

`print(MyData)
  Name Xnum Ynum Ratios
1 Bill    5   10    0.5
2  Ben   NA    5     1
3 Lisa   10   NA     0
4 Maya   NA   NA     1`

Thanks

Body:
Use case_when from the dplyr package:

library(dplyr)

MyData$Ratios <-
case_when(
    is.na(MyData$Xnum) & is.na(MyData$Ynum) ~ 1,
    is.na(MyData$Xnum) & MyData$Ynum >= 0 ~ 1,
    MyData$Xnum >= 0 & is.na(MyData$Ynum) ~ 0,
    TRUE ~ MyData$Xnum / MyData$Ynum
)


问:
what happen when execute mvn install if there dont exist pom
I want to install pig-maven, I download it and run mvn install command, then it tell me an error:

```<code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-remote-resources-plugin:1.5:process (default) on project pig-main: Failed to resolve dependencies for one or more projects in the reactor. Reason: Missing:

[ERROR] ----------
[ERROR] 1) org.apache.hive:hive-exec:jar:core:0.14.0-SNAPSHOT`
</code>```

here is some relevant information in pom.xml:

```<code><repositories>
        <repository>
            <id>repo.apache.snapshots</id>
            <url>http://repository.apache.org/content/groups/snapshots-group/</url>
        </repository>
        <repository>
            <id>repo.jboss.org</id>
            <url>http://repository.jboss.com/nexus/content/groups/public/</url>
        </repository>
    </repositories>
    ...
    <hive.version>0.14.0-SNAPSHOT</hive.version>
    <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-exec</artifactId>
            <version>${hive.version}</version>
            <scope>compile</scope>
            <classifier>core</classifier>
     </dependency>
</code>```

in specified snapshot repository I find it has some information of target jar but havent jar and pom. So then what should I do to install pig. The relate data as below:

答: What you are trying to install is the last version on github, it's a snapshot version and uses snapshots dependencies. You may try follow the tutorial of PIG and install a stable version. </p>

Body:
I want to install pig-maven, I download it and run mvn install command, then it tell me an error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-remote-resources-plugin:1.5:process (default) on project pig-main: Failed to resolve dependencies for one or more projects in the reactor. Reason: Missing:

[ERROR] ----------
[ERROR] 1) org.apache.hive:hive-exec:jar:core:0.14.0-SNAPSHOT`

here is some relevant information in pom.xml:

<repositories>
        <repository>
            <id>repo.apache.snapshots</id>
            <url>http://repository.apache.org/content/groups/snapshots-group/</url>
        </repository>
        <repository>
            <id>repo.jboss.org</id>
            <url>http://repository.jboss.com/nexus/content/groups/public/</url>
        </repository>
    </repositories>
    ...
    <hive.version>0.14.0-SNAPSHOT</hive.version>
    <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-exec</artifactId>
            <version>${hive.version}</version>
            <scope>compile</scope>
            <classifier>core</classifier>
     </dependency>

in specified snapshot repository I find it has some information of target jar but havent jar and pom. So then what should I do to install pig. The relate data as below:


问:
How to set CSS properties with JQuery with slow motion?
I want to get fading effect in JQuery using .css(). I'm able to do this with the statement:

```<code>$("p").fadeTo("slow", 0.0);
</code>```

A similar effect I'm able to get with the statement:

```<code>$("p").css("visibility", "hidden");
</code>```

When using fadeTo(), I am able to specify the timing (like "slow", "fast", milliseconds) but I don't know how to specify the timing with .css()

Please let me know how can I achieve this. I am comfortable with CSS, I want to achieve this with .css()

答:
you can also try show and hide function that acheive same result do not need of seting visiblity property

```<code>$("#paragraph").hide("slow");
$("#paragraph").show("slow");
</code>```

you can aslo try out this option if you just want to hide element with effect , then try this oud

```<code>$(document).ready(function(){
    $("button").click(function(){
        $("#p1").slideUp(2000);
    });
});

<p id="p1">Hide me !!</p>
<button>Click me</button>
</code>```

this one just hide out element form visibility point of view , but element stays in your DOM.

you can do like this , you use animate to decrease opacity of element than in complete call back just set visiblity to hidden.

```<code><p id="hidep">
 data
  dfg;ljdfsgj
  sfdgfdsgdsfg
  fdsgdfs
</p>
</code>```

```<code> $( "#hidep" ).animate({
  opacity: 0.1
  }, {
    duration: 1000,
    complete: function() {
      $( this ).css("visibility", "hidden");
    }
  });
</code>```

check working demo at jsfiddle : https://jsfiddle.net/7a8nes56/1/

Body:
I want to get fading effect in JQuery using .css(). I'm able to do this with the statement:

$("p").fadeTo("slow", 0.0);

A similar effect I'm able to get with the statement:

$("p").css("visibility", "hidden");

When using fadeTo(), I am able to specify the timing (like "slow", "fast", milliseconds) but I don't know how to specify the timing with .css()

Please let me know how can I achieve this. I am comfortable with CSS, I want to achieve this with .css()

Body:
you can also try show and hide function that acheive same result do not need of seting visiblity property

$("#paragraph").hide("slow");
$("#paragraph").show("slow");

you can aslo try out this option if you just want to hide element with effect , then try this oud

$(document).ready(function(){
    $("button").click(function(){
        $("#p1").slideUp(2000);
    });
});

<p id="p1">Hide me !!</p>
<button>Click me</button>

this one just hide out element form visibility point of view , but element stays in your DOM.

you can do like this , you use animate to decrease opacity of element than in complete call back just set visiblity to hidden.

<p id="hidep">
 data
  dfg;ljdfsgj
  sfdgfdsgdsfg
  fdsgdfs
</p>

 $( "#hidep" ).animate({
  opacity: 0.1
  }, {
    duration: 1000,
    complete: function() {
      $( this ).css("visibility", "hidden");
    }
  });

check working demo at jsfiddle : https://jsfiddle.net/7a8nes56/1/


问:
I can't use new in C++ function to build

I want to new a space for a argument in this function.
</p>

```<code>void Binary::PreAndMid(Qnode* root, char temp1[], char temp2[], int m, int n, int j, int k) {
    if (n - m != k - j || m > n || j > k) {
        return;
    }
    else {
        root = new Qnode;  /*in other function the root is become null*/
        root->val = temp1[m];
        cout << root->val << endl;
        int f = Find(temp2, temp1[m]);
        if (f == -1) {
            return;
        }
        else {
            PreAndMid(root->LC, temp1, temp2, m + 1, m + f - j, j, f - 1);
            PreAndMid(root->RC, temp1, temp2, m + f - j + 1, n, f + 1, k);
        }
    }
}
</code>```

<p>
The result is that the root is null.
</p>

答:
The argument root is passed in as a copy of the pointer. Assigning a new value to this pointer will not carry over after returning from the function.

If you want to this, you would need to pass the pointer root by reference:
Qnode* &root, which will make sure both the code calling this function and the function itself use the same variable.

Body:
I want to new a space for a argument in this function.

void Binary::PreAndMid(Qnode* root, char temp1[], char temp2[], int m, int n, int j, int k) {
    if (n - m != k - j || m > n || j > k) {
        return;
    }
    else {
        root = new Qnode;  /*in other function the root is become null*/
        root->val = temp1[m];
        cout << root->val << endl;
        int f = Find(temp2, temp1[m]);
        if (f == -1) {
            return;
        }
        else {
            PreAndMid(root->LC, temp1, temp2, m + 1, m + f - j, j, f - 1);
            PreAndMid(root->RC, temp1, temp2, m + f - j + 1, n, f + 1, k);
        }
    }
}

The result is that the root is null.


问:
Use a ng-bootstrap internationalized datepicker in an input
I want to have a french datepicker in an input form.

Here is the ng-bootstrap example to have an "english" one:

```<code><form class="form-inline">
  <div class="form-group">
    <div class="input-group">
      <input class="form-control" placeholder="yyyy-mm-dd"
             name="dp" [(ngModel)]="model" ngbDatepicker #d="ngbDatepicker">
      <button class="input-group-addon" (click)="d.toggle()" type="button">
        <img src="img/calendar-icon.svg" style="width: 1.2rem; height: 1rem; cursor: pointer;"/>
      </button>
    </div>
  </div>
</form>
</code>```

Here they explained how to make a french one using <ngbd-datepicker-i18n></ngbd-datepicker-i18n> with a custom datepicker and here there is some more details on how to use it.

But what I want is to use the same thing that they used above, whith the template reference variable #d="ngbDatepicker" inside my input tag. Something like #d="myCustomNgbDatepicker".

Is it possible ? And if yes, how ?

答:
You have to make two things

a DateI18nFormater extends NgbDatepickerI18n

a DateParserFormatter extends NgbDateParserFormatter

in your module.ts

```<code>providers: [
        { provide: NgbDateParserFormatter, useClass: DateParserFormatter },
        I18n,
        { provide: NgbDatepickerI18n, useClass: DateI18nFormater }
    ]
</code>```

Body:
I want to have a french datepicker in an input form.

Here is the ng-bootstrap example to have an "english" one:

<form class="form-inline">

      <input class="form-control" placeholder="yyyy-mm-dd"
             name="dp" [(ngModel)]="model" ngbDatepicker #d="ngbDatepicker">
      <button class="input-group-addon" (click)="d.toggle()" type="button">

      </button>

</form>

Here they explained how to make a french one using <ngbd-datepicker-i18n></ngbd-datepicker-i18n> with a custom datepicker and here there is some more details on how to use it.

But what I want is to use the same thing that they used above, whith the template reference variable #d="ngbDatepicker" inside my input tag. Something like #d="myCustomNgbDatepicker".

Is it possible ? And if yes, how ?

Body:
You have to make two things

a DateI18nFormater extends NgbDatepickerI18n

a DateParserFormatter extends NgbDateParserFormatter

in your module.ts

providers: [
        { provide: NgbDateParserFormatter, useClass: DateParserFormatter },
        I18n,
        { provide: NgbDatepickerI18n, useClass: DateI18nFormater }
    ]


答:
For hide

```<code>$("p").fadeOut(1000); // This will hide the p element with an animation of 1 sec duration
</code>```

For show

```<code>$("p").fadeIn(1000);
</code>```

if you want use css with this, then for show

```<code> $('p').css({opacity: 0, visibility: "visible"}).animate({opacity: 1}, 1000); // show p
</code>```

For hide

```<code>$('p').css({opacity: 1, visibility: "hidden"}).animate({opacity: 0}, 1000); // hide p
</code>```

Title: How to set CSS properties with JQuery with slow motion?

Body:
For hide

$("p").fadeOut(1000); // This will hide the p element with an animation of 1 sec duration

For show

$("p").fadeIn(1000);

if you want use css with this, then for show

 $('p').css({opacity: 0, visibility: "visible"}).animate({opacity: 1}, 1000); // show p

For hide

$('p').css({opacity: 1, visibility: "hidden"}).animate({opacity: 0}, 1000); // hide p


问:
error C2514: 'BLOCK' : CLASS HAS NO CONSTRUCTOR
I get the error error C2514: 'BLOCK' : CLASS HAS NO CONSTRUCTOR  with a simple class like this:

BLOCK.h

```<code>#pragma once
#include "helpful.h"

class WORLD;

class BLOCK
{
    public:
        short int type;

        void Render();

        BLOCK();
        ~BLOCK(void);
};
</code>```

BLOCK.cpp

```<code>#include "BLOCK.h"
#include "WORLD.h"

BLOCK::BLOCK(void)
{
}
void BLOCK::Render()
{
}
BLOCK::~BLOCK(void)
{
}
</code>```

But the BLOCK class is defined, no?

答:
According to MSDN, error C2514 is raised when:

The class, structure, or union has no
  constructor with a parameter list that
  matches the parameters being used to
  instantiate it.

My guess is that you're not passing the right parameters to your class' constructor. The code that raised the error is obviously not part of what you have shown.

Body:
I get the error error C2514: 'BLOCK' : CLASS HAS NO CONSTRUCTOR  with a simple class like this:

BLOCK.h

#pragma once
#include "helpful.h"

class WORLD;

class BLOCK
{
    public:
        short int type;

        void Render();

        BLOCK();
        ~BLOCK(void);
};

BLOCK.cpp

#include "BLOCK.h"
#include "WORLD.h"

BLOCK::BLOCK(void)
{
}
void BLOCK::Render()
{
}
BLOCK::~BLOCK(void)
{
}

But the BLOCK class is defined, no?


问:
In jsTree, how can we have nodes initially selected after replacing tree?
In jsTree, I want to draw a new tree replacing the previous one and have nodes initially selected in the new tree.

In the code below, I confirmed that state : {opened : true} made the node initially opened and state : {disabled : true} made the node initially disabled, so I thought state : {selected : true} works too, but actually it is not.

Please note that specifying state : {selected : true} when calling $('#using_json').jstree({...}); does result in the node selected as described in https://www.jstree.com/docs/json/. Then, I wonder why state : {selected : true} does not work when I replace a existing tree with a new tree (while state : {opened : true} and state : {disabled : true} are working).

How can we achieve nodes to be initially selected after replacing tree?

$('#using_json').jstree({ 'core' : {
    data : [
      {
         text : 'Previous root node',
      }
    ]
} });

const newData = [
       {
         text : 'New root node (Initially opened)',
         state : {
           opened : true,       //'opened' takes effect after refresh
         },
         children : [
           { text : 'Child 1 (Initially disabled)',
             state : {
               disabled : true, //'disabled' takes effect after refresh
             }
           },
           { text : 'Child 2 (Intended to be selected initially but failing)',
             state : {
               selected : true  //'selected' does NOT take effect after refresh
             }
           }
         ]
      }
    ]

$('#using_json').jstree(true).settings.core.data = newData;
$('#using_json').jstree(true).refresh(true);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/themes/default/style.min.css" />
</head>
<body>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/jstree.min.js"></script>
  <div id="using_json"></div>
</body>
</html></code>```

答:
You could try using the select_node config property when you initialize the tree, which you could do just once. For this you need to add some IDs to your nodes so you can then reference the selected node:

$('#using_json').jstree({
  'core': {
    select_node: 'c2',
    data: [{
      text: 'Root node after Refresh (Opened)',
      state: {
        opened: true, //'opened' takes effect after refresh
      },
      children: [{
        text: 'Child 1 (Disabled)',
        id: 'c1',
        state: {
          disabled: true, //'disabled' takes effect after refresh
        }
      }, {
        text: 'Child 2 (Intended to be selected but failing)',
        id: 'c2',
        state: {
          selected: true //'selected' does NOT take effect after refresh
        }
      }]
    }]
  }
});

//$('#using_json').jstree(true).settings.select_node = 'c2';
//$('#using_json').jstree(true).refresh(true);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/themes/default/style.min.css" />
</head>
<body>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/jstree.min.js"></script>
  <div id="using_json"></div>
</body>
</html></code>```

Check out this answer also.

Alternative with refresh

Since OP needs to keep the initial code structure (init -> change config data -> refresh) an alternative solution would be to "force" selection by using the callback of the refresh event:

$('#using_json').jstree({
  'core': {
    data: [{
      text: 'Previous root node',
    }]
  }
});

const newData = [{
  text: 'New root node (Initially opened)',
  state: {
    opened: true, //'opened' takes effect after refresh
    selected: true
  },
  children: [{
    text: 'Child 1 (Initially disabled)',
    id: 'c1',
    state: {
      disabled: true, //'disabled' takes effect after refresh
    }
  }, {
    text: 'Child 2 (Intended to be selected initially but failing)',
    id: 'c2',
    state: {
      selected: true //'selected' does NOT take effect after refresh
    }
  }]
}];

$('#using_json').jstree().settings.core.data = newData;
//$('#using_json').jstree(true).settings.select_node = 'c2';
$('#using_json').jstree(true).refresh(true);
$('#using_json').on("refresh.jstree", function(e) {
  $('#using_json').jstree('select_node', 'c2');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/themes/default/style.min.css" />
</head>
<body>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/jstree.min.js"></script>
  <div id="using_json"></div>
</body>
</html></code>```

Body:
In jsTree, I want to draw a new tree replacing the previous one and have nodes initially selected in the new tree.

In the code below, I confirmed that state : {opened : true} made the node initially opened and state : {disabled : true} made the node initially disabled, so I thought state : {selected : true} works too, but actually it is not.

Please note that specifying state : {selected : true} when calling $('#using_json').jstree({...}); does result in the node selected as described in https://www.jstree.com/docs/json/. Then, I wonder why state : {selected : true} does not work when I replace a existing tree with a new tree (while state : {opened : true} and state : {disabled : true} are working).

How can we achieve nodes to be initially selected after replacing tree?

$('#using_json').jstree({ 'core' : {
    data : [
      {
         text : 'Previous root node',
      }
    ]
} });

const newData = [
       {
         text : 'New root node (Initially opened)',
         state : {
           opened : true,       //'opened' takes effect after refresh
         },
         children : [
           { text : 'Child 1 (Initially disabled)',
             state : {
               disabled : true, //'disabled' takes effect after refresh
             }
           },
           { text : 'Child 2 (Intended to be selected initially but failing)',
             state : {
               selected : true  //'selected' does NOT take effect after refresh
             }
           }
         ]
      }
    ]

$('#using_json').jstree(true).settings.core.data = newData;
$('#using_json').jstree(true).refresh(true);

<!DOCTYPE html>

  <meta charset="utf-8">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/themes/default/style.min.css" />

Body:
You could try using the select_node config property when you initialize the tree, which you could do just once. For this you need to add some IDs to your nodes so you can then reference the selected node:

$('#using_json').jstree({
  'core': {
    select_node: 'c2',
    data: [{
      text: 'Root node after Refresh (Opened)',
      state: {
        opened: true, //'opened' takes effect after refresh
      },
      children: [{
        text: 'Child 1 (Disabled)',
        id: 'c1',
        state: {
          disabled: true, //'disabled' takes effect after refresh
        }
      }, {
        text: 'Child 2 (Intended to be selected but failing)',
        id: 'c2',
        state: {
          selected: true //'selected' does NOT take effect after refresh
        }
      }]
    }]
  }
});

//$('#using_json').jstree(true).settings.select_node = 'c2';
//$('#using_json').jstree(true).refresh(true);

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/themes/default/style.min.css" />
</head>
<body>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/jstree.min.js"></script>
  <div id="using_json"></div>
</body>
</html>

Check out this answer also.

Alternative with refresh

Since OP needs to keep the initial code structure (init -> change config data -> refresh) an alternative solution would be to "force" selection by using the callback of the refresh event:

$('#using_json').jstree({
  'core': {
    data: [{
      text: 'Previous root node',
    }]
  }
});

const newData = [{
  text: 'New root node (Initially opened)',
  state: {
    opened: true, //'opened' takes effect after refresh
    selected: true
  },
  children: [{
    text: 'Child 1 (Initially disabled)',
    id: 'c1',
    state: {
      disabled: true, //'disabled' takes effect after refresh
    }
  }, {
    text: 'Child 2 (Intended to be selected initially but failing)',
    id: 'c2',
    state: {
      selected: true //'selected' does NOT take effect after refresh
    }
  }]
}];

$('#using_json').jstree().settings.core.data = newData;
//$('#using_json').jstree(true).settings.select_node = 'c2';
$('#using_json').jstree(true).refresh(true);
$('#using_json').on("refresh.jstree", function(e) {
  $('#using_json').jstree('select_node', 'c2');
});

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/themes/default/style.min.css" />
</head>
<body>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/jstree.min.js"></script>
  <div id="using_json"></div>
</body>
</html>


问:
Flask Server: Using a data in the same session
I have a python server using the flask framework.

My application is a chatbot that talks to the user and performs some calculations in a dataset provided by the user.

I am already able to upload this data to the server, but when I try to use the data it is not loaded anymore. So I need to use this data until the user disconnect from my server.

Reading the Flask Documentation, I found some information that can lead me to what I need. The Application Context

Am I in the right direction?

This is how I am uploading the file in the server:

```<code>@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
     # check if the post request has the file part
    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['file']
    # if user does not select file, browser also
    # submit a empty part without filename
    if file.filename == '':
        flash('No selected file')
        return redirect(request.url)
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        stream = io.StringIO(file.stream.read().decode("UTF8"), newline=None)
        csv_input = pd.read_csv(stream,sep=None,engine='python')
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        session['receive_count'] = session.get('receive_count', 0) + 1
        return render_template('index.html', async_mode=socketio.async_mode)

return render_template('index.html', async_mode=socketio.async_mode)
</code>```

答:
There are multiple solutions to your problem.

First thing is that the file variable here is local to the index()-function. If you want to use a variable you defined outside of the function (and it's not imported like request and session) you need to start the function with the line global file.

I would store the filename in session, then read the file again when you need the data. That way it will be local to the user, and you're not storing large amounts data in memory. Plus, if you use session.permanent = True it will be the stored for month for that "user" regardless of server and browser restarts.

Edit:
This answer originally stated that you can use the Flask g-object to store the global. However, the g-object is local to a request even though it lives in the application context. (i.e. data stored on the g-object is not accessible across requests, it's only accessible within the same request)

Body:
I have a python server using the flask framework.

My application is a chatbot that talks to the user and performs some calculations in a dataset provided by the user.

I am already able to upload this data to the server, but when I try to use the data it is not loaded anymore. So I need to use this data until the user disconnect from my server.

Reading the Flask Documentation, I found some information that can lead me to what I need. The Application Context

Am I in the right direction?

This is how I am uploading the file in the server:

@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
     # check if the post request has the file part
    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['file']
    # if user does not select file, browser also
    # submit a empty part without filename
    if file.filename == '':
        flash('No selected file')
        return redirect(request.url)
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        stream = io.StringIO(file.stream.read().decode("UTF8"), newline=None)
        csv_input = pd.read_csv(stream,sep=None,engine='python')
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        session['receive_count'] = session.get('receive_count', 0) + 1
        return render_template('index.html', async_mode=socketio.async_mode)

return render_template('index.html', async_mode=socketio.async_mode)


问:
In Hammerspoon how do I get the currently focused application name on startup?
I can get the application name after the user switches focus with the following code:

```<code>function applicationWatcher(appName, eventType, appObject)
  if (eventType == hs.application.watcher.activated) then
    print(appName)
  end
end

local appWatcher = hs.application.watcher.new(applicationWatcher)
</code>```

But I'd like this appName right after hammerspoon initializes.

答: See the hs.application.frontmostApplication() function: http://www.hammerspoon.org/docs/hs.application.html#frontmostApplication :)

Body:
I can get the application name after the user switches focus with the following code:

function applicationWatcher(appName, eventType, appObject)
  if (eventType == hs.application.watcher.activated) then
    print(appName)
  end
end

local appWatcher = hs.application.watcher.new(applicationWatcher)

But I'd like this appName right after hammerspoon initializes.


问:
Custom cell for UICollection view cell unable clear old data
I created a custom UICollection cell but the data sometimes appear in the wrong cell and no matter how much I refresh the UICollection view it refuses to change. I have done a print out to see if the data gotten from the array is wrong but it's not. Is there a way to clear the old data from the cell before inputting the next one. Any suggestion will be appreciated.

custom cell

```<code>class customAppointmentViewCell: UICollectionViewCell {

override init(frame: CGRect) {
    super.init(frame: frame)
    setupViews()
}

let thumbnailImageView: UIImageView = {
    let tniv = UIImageView()
    tniv.translatesAutoresizingMaskIntoConstraints = false
    tniv.backgroundColor = UIColor.clear
    tniv.contentMode = .scaleAspectFit
    return tniv
}()

let seperatorView: UIView = {
    let sv = UIView()
    sv.translatesAutoresizingMaskIntoConstraints = false
    sv.backgroundColor = UIColor(r: 11, g: 49, b: 68)
    return sv
}()

let clientNamePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 17)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let openingTimePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 12)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let closingTimePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 12)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let bookedBarberNamePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 12)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let servicePricePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 10)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .right
    return fnhp
}()

func setupViews(){
    addSubview(thumbnailImageView)
    addSubview(clientNamePlaceHolder)
    addSubview(openingTimePlaceHolder)
    addSubview(closingTimePlaceHolder)
    addSubview(bookedBarberNamePlaceHolder)
    addSubview(servicePricePlaceHolder)
    addSubview(seperatorView)
    backgroundColor = UIColor(r: 23, g: 69, b: 90)
    addContraintsWithFormat(format: "H:|-16-[v0(90)]|", views: thumbnailImageView)
    addContraintsWithFormat(format: "H:|-116-[v0][v1(50)]-10-|", views: clientNamePlaceHolder, servicePricePlaceHolder)
    addContraintsWithFormat(format: "H:|-116-[v0]-60-|", views: openingTimePlaceHolder)
    addContraintsWithFormat(format: "H:|-116-[v0]-60-|", views: closingTimePlaceHolder)
    addContraintsWithFormat(format: "H:|-116-[v0]-60-|", views: bookedBarberNamePlaceHolder)
    addContraintsWithFormat(format: "V:|-10-[v0(20)][v1(20)][v2(20)][v3(20)]-10-|", views: clientNamePlaceHolder, openingTimePlaceHolder,closingTimePlaceHolder, bookedBarberNamePlaceHolder)
    addContraintsWithFormat(format: "V:|-10-[v0(20)]|", views: servicePricePlaceHolder)
    addContraintsWithFormat(format: "V:|-10-[v0]-10-[v1(5)]|", views: thumbnailImageView,seperatorView)
    addContraintsWithFormat(format: "H:|[v0]|", views: seperatorView)

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}
</code>```

collection view

```<code>extension AppointmentsViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.appointments.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! customAppointmentViewCell
    //empty cell data
    //real data

    cell.openingTimePlaceHolder.text = ""
    if let opentime = self.appointments[safe: indexPath.row]?.bookingStartTimeString {
        cell.openingTimePlaceHolder.text = opentime
    } else {
        cell.openingTimePlaceHolder.text = ""
    }

    cell.closingTimePlaceHolder.text = ""
    if let closetime = self.appointments[safe: indexPath.row]?.bookingEndTimeString {
        cell.closingTimePlaceHolder.text = closetime
    } else {
        cell.closingTimePlaceHolder.text = ""
    }

    cell.bookedBarberNamePlaceHolder.text = ""
    if let barberName = self.appointments[safe: indexPath.row]?.bookedBarberName {
        cell.bookedBarberNamePlaceHolder.text = barberName
    } else {
        cell.bookedBarberNamePlaceHolder.text = ""
    }

    cell.servicePricePlaceHolder.text = ""
    if let servicepricee = self.appointments[safe: indexPath.row]?.bookedServicePrice {
        cell.servicePricePlaceHolder.text = servicepricee
    } else {
        cell.servicePricePlaceHolder.text = ""
    }

    cell.thumbnailImageView.image = UIImage()
    if let profileimagess = self.appointments[safe: indexPath.row]?.profileImage {
        cell.thumbnailImageView.image = profileimagess
    } else {
        cell.thumbnailImageView.image = UIImage()
    }

    cell.clientNamePlaceHolder.text = ""
    if let clientnamess = self.appointments[safe: indexPath.row]?.clientName {
        cell.clientNamePlaceHolder.text = clientnamess
    } else {
        cell.clientNamePlaceHolder.text = ""
    }

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectView.frame.width, height: 100)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if let uuidAvail = UserDefaults.standard.object(forKey: "theOriginalBarberShopUUID") as? String{
        if let bookIDDD = self.appointments[safe: indexPath.row]?.bookingUniqueID {
            let orderDetail = OrderDetailViewController()
            orderDetail.specificAppintment = self.appointments[indexPath.row]
            orderDetail.barberShopID = uuidAvail
            orderDetail.bookingUniqueIDDD = bookIDDD
            orderDetail.bookedBarberUUIDAX = self.appointments[indexPath.row].bookedBarberUUID
            orderDetail.appointmentsviewhold = self
            orderDetail.indexPathSelected = indexPath.row
            navigationController?.pushViewController(orderDetail, animated: true)
        }
    }
}
}
</code>```

thanks

答:
Do this in customAppointmentViewCell

```<code>override func prepareForReuse() {
    self. thumbnailImageView.image = UIImage()
    //add here other variable and set default value for all.
}
</code>```

prepareForReuse is called when a new cell will show on screen.

And Remove default value set code from your cellForRow as guided by Nikhil Manapure.

Hope this helps you.

Body:
I created a custom UICollection cell but the data sometimes appear in the wrong cell and no matter how much I refresh the UICollection view it refuses to change. I have done a print out to see if the data gotten from the array is wrong but it's not. Is there a way to clear the old data from the cell before inputting the next one. Any suggestion will be appreciated.

custom cell

class customAppointmentViewCell: UICollectionViewCell {

override init(frame: CGRect) {
    super.init(frame: frame)
    setupViews()
}

let thumbnailImageView: UIImageView = {
    let tniv = UIImageView()
    tniv.translatesAutoresizingMaskIntoConstraints = false
    tniv.backgroundColor = UIColor.clear
    tniv.contentMode = .scaleAspectFit
    return tniv
}()

let seperatorView: UIView = {
    let sv = UIView()
    sv.translatesAutoresizingMaskIntoConstraints = false
    sv.backgroundColor = UIColor(r: 11, g: 49, b: 68)
    return sv
}()

let clientNamePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 17)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let openingTimePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 12)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let closingTimePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 12)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let bookedBarberNamePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 12)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let servicePricePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 10)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .right
    return fnhp
}()

func setupViews(){
    addSubview(thumbnailImageView)
    addSubview(clientNamePlaceHolder)
    addSubview(openingTimePlaceHolder)
    addSubview(closingTimePlaceHolder)
    addSubview(bookedBarberNamePlaceHolder)
    addSubview(servicePricePlaceHolder)
    addSubview(seperatorView)
    backgroundColor = UIColor(r: 23, g: 69, b: 90)
    addContraintsWithFormat(format: "H:|-16-[v0(90)]|", views: thumbnailImageView)
    addContraintsWithFormat(format: "H:|-116-[v0][v1(50)]-10-|", views: clientNamePlaceHolder, servicePricePlaceHolder)
    addContraintsWithFormat(format: "H:|-116-[v0]-60-|", views: openingTimePlaceHolder)
    addContraintsWithFormat(format: "H:|-116-[v0]-60-|", views: closingTimePlaceHolder)
    addContraintsWithFormat(format: "H:|-116-[v0]-60-|", views: bookedBarberNamePlaceHolder)
    addContraintsWithFormat(format: "V:|-10-[v0(20)][v1(20)][v2(20)][v3(20)]-10-|", views: clientNamePlaceHolder, openingTimePlaceHolder,closingTimePlaceHolder, bookedBarberNamePlaceHolder)
    addContraintsWithFormat(format: "V:|-10-[v0(20)]|", views: servicePricePlaceHolder)
    addContraintsWithFormat(format: "V:|-10-[v0]-10-[v1(5)]|", views: thumbnailImageView,seperatorView)
    addContraintsWithFormat(format: "H:|[v0]|", views: seperatorView)

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}

collection view

extension AppointmentsViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.appointments.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! customAppointmentViewCell
    //empty cell data
    //real data

    cell.openingTimePlaceHolder.text = ""
    if let opentime = self.appointments[safe: indexPath.row]?.bookingStartTimeString {
        cell.openingTimePlaceHolder.text = opentime
    } else {
        cell.openingTimePlaceHolder.text = ""
    }

    cell.closingTimePlaceHolder.text = ""
    if let closetime = self.appointments[safe: indexPath.row]?.bookingEndTimeString {
        cell.closingTimePlaceHolder.text = closetime
    } else {
        cell.closingTimePlaceHolder.text = ""
    }

    cell.bookedBarberNamePlaceHolder.text = ""
    if let barberName = self.appointments[safe: indexPath.row]?.bookedBarberName {
        cell.bookedBarberNamePlaceHolder.text = barberName
    } else {
        cell.bookedBarberNamePlaceHolder.text = ""
    }

    cell.servicePricePlaceHolder.text = ""
    if let servicepricee = self.appointments[safe: indexPath.row]?.bookedServicePrice {
        cell.servicePricePlaceHolder.text = servicepricee
    } else {
        cell.servicePricePlaceHolder.text = ""
    }

    cell.thumbnailImageView.image = UIImage()
    if let profileimagess = self.appointments[safe: indexPath.row]?.profileImage {
        cell.thumbnailImageView.image = profileimagess
    } else {
        cell.thumbnailImageView.image = UIImage()
    }

    cell.clientNamePlaceHolder.text = ""
    if let clientnamess = self.appointments[safe: indexPath.row]?.clientName {
        cell.clientNamePlaceHolder.text = clientnamess
    } else {
        cell.clientNamePlaceHolder.text = ""
    }

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectView.frame.width, height: 100)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if let uuidAvail = UserDefaults.standard.object(forKey: "theOriginalBarberShopUUID") as? String{
        if let bookIDDD = self.appointments[safe: indexPath.row]?.bookingUniqueID {
            let orderDetail = OrderDetailViewController()
            orderDetail.specificAppintment = self.appointments[indexPath.row]
            orderDetail.barberShopID = uuidAvail
            orderDetail.bookingUniqueIDDD = bookIDDD
            orderDetail.bookedBarberUUIDAX = self.appointments[indexPath.row].bookedBarberUUID
            orderDetail.appointmentsviewhold = self
            orderDetail.indexPathSelected = indexPath.row
            navigationController?.pushViewController(orderDetail, animated: true)
        }
    }
}
}

thanks

Body:
Do this in customAppointmentViewCell

override func prepareForReuse() {
    self. thumbnailImageView.image = UIImage()
    //add here other variable and set default value for all.
}

prepareForReuse is called when a new cell will show on screen.

And Remove default value set code from your cellForRow as guided by Nikhil Manapure.

Hope this helps you.