问:
Device not applicable for the "main.dart" configuration ,
I use Android Studio as my IDE in coding Flutter. I was able to create 2 projects before this and it worked absolutely fine. I had to clone a repo from Github. The IDE said to get config. I did that then this happened.

I already installed sdk .

My android devices android version is 7.0

Flutter Doctor result:

```<code>[√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.18363.720], locale en-US)
    • Flutter version 1.12.13+hotfix.8 at C:\src\flutter\flutter
    • Framework revision 0b8abb4724 (6 weeks ago), 2020-02-11 11:44:36 -0800
    • Engine revision e1e6ced81d
    • Dart version 2.7.0

[X] Android toolchain - develop for Android devices
    X Unable to locate Android SDK.
      Install Android Studio from: https://developer.android.com/studio/index.html
      On first launch it will assist you in installing the Android SDK components.
      (or visit https://flutter.dev/setup/#android-setup for detailed instructions).
      If the Android SDK has been installed to a custom location, set ANDROID_HOME to that location.
      You may also want to add it to your PATH environment variable.

[√] Android Studio (version 3.6)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin version 44.0.2
    • Dart plugin version 192.7761
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)

[!] Android Studio
    • Android Studio at C:\Program
    X Flutter plugin not installed; this adds Flutter specific functionality.
    X Dart plugin not installed; this adds Dart specific functionality.
    X android-studio-dir = C:\Program
    X Android Studio not found at C:\Program
    • Try updating or re-installing Android Studio.
    • Consider removing your android-studio-dir setting by running:
      flutter config --android-studio-dir=

[!] VS Code
    • VS Code at C:\Users\Tamim Mostafa\AppData\Local\Programs\Microsoft VS Code
    X Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[!] Connected device
    ! No devices available

! Doctor found issues in 4 categories.
</code>```

I also tried changing the directory an using folder with no white space. I moved the Sdk folder to D:\Android\Sdk. flutter doctor -v:

```<code>[√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.18363.720], locale en-US)
    • Flutter version 1.12.13+hotfix.8 at C:\src\flutter\flutter
    • Framework revision 0b8abb4724 (6 weeks ago), 2020-02-11 11:44:36 -0800
    • Engine revision e1e6ced81d
    • Dart version 2.7.0

[X] Android toolchain - develop for Android devices
    X ANDROID_HOME = D:\Android\Sdk
      but Android SDK not found at this location.

[√] Android Studio (version 3.6)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin version 44.0.2
    • Dart plugin version 192.7761
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)

[!] Android Studio
    • Android Studio at C:\Program
    X Flutter plugin not installed; this adds Flutter specific functionality.
    X Dart plugin not installed; this adds Dart specific functionality.
    X android-studio-dir = C:\Program
    X Android Studio not found at C:\Program
    • Try updating or re-installing Android Studio.
    • Consider removing your android-studio-dir setting by running:
      flutter config --android-studio-dir=

[!] VS Code
    • VS Code at C:\Users\Tamim Mostafa\AppData\Local\Programs\Microsoft VS Code
    X Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[!] Connected device
    ! No devices available

! Doctor found issues in 4 categories.
</code>```

答:
It solved my problem:

Make sure Flutter plugin is installed in android studio, you can install the plugin from file > setting > plugin

choose flutter SDK path from File > setting> Language & Framework > flutter.

Body:
I use Android Studio as my IDE in coding Flutter. I was able to create 2 projects before this and it worked absolutely fine. I had to clone a repo from Github. The IDE said to get config. I did that then this happened.

I already installed sdk .

My android devices android version is 7.0

Flutter Doctor result:

[√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.18363.720], locale en-US)
    • Flutter version 1.12.13+hotfix.8 at C:\src\flutter\flutter
    • Framework revision 0b8abb4724 (6 weeks ago), 2020-02-11 11:44:36 -0800
    • Engine revision e1e6ced81d
    • Dart version 2.7.0

[X] Android toolchain - develop for Android devices
    X Unable to locate Android SDK.
      Install Android Studio from: https://developer.android.com/studio/index.html
      On first launch it will assist you in installing the Android SDK components.
      (or visit https://flutter.dev/setup/#android-setup for detailed instructions).
      If the Android SDK has been installed to a custom location, set ANDROID_HOME to that location.
      You may also want to add it to your PATH environment variable.

[√] Android Studio (version 3.6)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin version 44.0.2
    • Dart plugin version 192.7761
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)

[!] Android Studio
    • Android Studio at C:\Program
    X Flutter plugin not installed; this adds Flutter specific functionality.
    X Dart plugin not installed; this adds Dart specific functionality.
    X android-studio-dir = C:\Program
    X Android Studio not found at C:\Program
    • Try updating or re-installing Android Studio.
    • Consider removing your android-studio-dir setting by running:
      flutter config --android-studio-dir=

[!] VS Code
    • VS Code at C:\Users\Tamim Mostafa\AppData\Local\Programs\Microsoft VS Code
    X Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[!] Connected device
    ! No devices available

! Doctor found issues in 4 categories.

I also tried changing the directory an using folder with no white space. I moved the Sdk folder to D:\Android\Sdk. flutter doctor -v:

[√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.18363.720], locale en-US)
    • Flutter version 1.12.13+hotfix.8 at C:\src\flutter\flutter
    • Framework revision 0b8abb4724 (6 weeks ago), 2020-02-11 11:44:36 -0800
    • Engine revision e1e6ced81d
    • Dart version 2.7.0

[X] Android toolchain - develop for Android devices
    X ANDROID_HOME = D:\Android\Sdk
      but Android SDK not found at this location.

[√] Android Studio (version 3.6)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin version 44.0.2
    • Dart plugin version 192.7761
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)

[!] Android Studio
    • Android Studio at C:\Program
    X Flutter plugin not installed; this adds Flutter specific functionality.
    X Dart plugin not installed; this adds Dart specific functionality.
    X android-studio-dir = C:\Program
    X Android Studio not found at C:\Program
    • Try updating or re-installing Android Studio.
    • Consider removing your android-studio-dir setting by running:
      flutter config --android-studio-dir=

[!] VS Code
    • VS Code at C:\Users\Tamim Mostafa\AppData\Local\Programs\Microsoft VS Code
    X Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[!] Connected device
    ! No devices available

! Doctor found issues in 4 categories.


来源: stackexchange

问:
PHP braces { } replace <?php ?>?
I've seen in someones source code they load template.tpl and inside is ...value="{$phcode}"...
does {$phcode} replace <?php $phcode ?>

I don't find any reference in php manual.

答: I'm pretty sure that's the Smarty PHP templating engine. It can do stuff like that, it makes templating easier with the integrated php execution.</p>

ContentLicense: CC BY-SA 3.0

Title: PHP braces { } replace <?php ?>?


问:
CoR vs simple if else and matrix based functional calls where the chain is request dependent

I have used Handlers mapping along with if else conditional construct to handle chains which are request dependent.

```<code>Request r(TYPE1, ACTIVE);
std::vector<TYPE, STATUS> mapping;
mapping[TYPE1][PENDING] = myHandlerA();
// ... and so on
mapping[r.type()][r.status()]();

void myHandlerA(Request& r) {
  if(condition4(r))
  Handler4(r);

  else if(condition5(r))
  Handler5(r);

  else if(condition6(r))
  Handler6(r);

  else if(condition7(r))
  Handler7()
}
</code>```

How do I do it using CoR when the chain is dependent on the request ? Is my approach a good design ?

Is this case applicable to CoR ? Can someone provide a snippet, if yes.

How does one identify applicability of CoR vs a simple mapping based coupled with if else ?

答:
Would be easier to answer seeing CoR handler interface:

```<code>class BaseHandler {
public:
    void setNext(BaseHandler* next){ m_next = next; }
    void handle(Request r){
        handleImpl(r);
        if(m_next!=nullptr) {
            m_next->handle(r);
        }
    };
    virtual ~BaseHandler(){ if (m_next) delete m_next; }
protected:
    BaseHandler* m_next;
    virtual void handleImpl(Request r) = 0;
};
</code>```

(Changed order of answers for more logical output)

2. Your myHandlerA consists of multiple if-else statements, so just one of Handler4-Handler7 is used.

CoR is dedicated rather to perform multiple handlers in concrete order.

1. (First read description, then go to snippets)
You can create factory method to produce you handler suitable for your request.

```<code>class Request {
    public:
    int type;
};

class Handler1: public BaseHandler{
    void handleImpl (Request r) override {
        cout << "Handler1" << endl;
    }
};

class Handler2: public BaseHandler{
    void handleImpl (Request r) override {
        cout << "Handler2" << endl;
    }
};

class MyFactory {
public:
    BaseHandler* getHandler(const Request& r){
        if (r.type==1){
            return new Handler1;
        }
        if (r.type==2){
            return new Handler2;
        }
    }
};

int main(){
    Request r;
    r.type=1;
    MyFactory myFactory;
    BaseHandler* handler = myFactory.getHandler(r);
    handler->handle(r);
    delete handler;
}
</code>```

OR

You can create CoR handler (see above) that sets its m_next to proper handler depending on request type.

That way you may apply CoR in your solution.

```<code>class RequestTypeHandler: public BaseHandler{
    void handleImpl (Request r) override {
        cout << "RequestTypeHandler" << endl;
        if (r.type==1){
            cout << "Select Handler1" << endl;
            m_next = new Handler1;
        }
        if (r.type==2){
            cout << "Select Handler2" << endl;
            m_next = new Handler2;
        }
    }
};

int main(){
    Request r;
    r.type=1;
    RequestTypeHandler handler;
    handler.handle(r);
}
</code>```

As said in answer for 1., CoR is dedicated rather to order of handlers, not just one, like in case of mapping.

Also, I'd suggest great page with Design Patterns: https://refactoring.guru

ContentLicense: CC BY-SA 4.0

Body:
I have used Handlers mapping along with if else conditional construct to handle chains which are request dependent.

Request r(TYPE1, ACTIVE);
std::vector<TYPE, STATUS> mapping;
mapping[TYPE1][PENDING] = myHandlerA();
// ... and so on
mapping[r.type()][r.status()]();

void myHandlerA(Request& r) {
  if(condition4(r))
  Handler4(r);

  else if(condition5(r))
  Handler5(r);

  else if(condition6(r))
  Handler6(r);

  else if(condition7(r))
  Handler7()
}

How do I do it using CoR when the chain is dependent on the request ? Is my approach a good design ?

Is this case applicable to CoR ? Can someone provide a snippet, if yes.

How does one identify applicability of CoR vs a simple mapping based coupled with if else ?

Body:
Would be easier to answer seeing CoR handler interface:

class BaseHandler {
public:
    void setNext(BaseHandler* next){ m_next = next; }
    void handle(Request r){
        handleImpl(r);
        if(m_next!=nullptr) {
            m_next->handle(r);
        }
    };
    virtual ~BaseHandler(){ if (m_next) delete m_next; }
protected:
    BaseHandler* m_next;
    virtual void handleImpl(Request r) = 0;
};

(Changed order of answers for more logical output)

2. Your myHandlerA consists of multiple if-else statements, so just one of Handler4-Handler7 is used.

CoR is dedicated rather to perform multiple handlers in concrete order.

1. (First read description, then go to snippets)
You can create factory method to produce you handler suitable for your request.

class Request {
    public:
    int type;
};

class Handler1: public BaseHandler{
    void handleImpl (Request r) override {
        cout << "Handler1" << endl;
    }
};

class Handler2: public BaseHandler{
    void handleImpl (Request r) override {
        cout << "Handler2" << endl;
    }
};

class MyFactory {
public:
    BaseHandler* getHandler(const Request& r){
        if (r.type==1){
            return new Handler1;
        }
        if (r.type==2){
            return new Handler2;
        }
    }
};

int main(){
    Request r;
    r.type=1;
    MyFactory myFactory;
    BaseHandler* handler = myFactory.getHandler(r);
    handler->handle(r);
    delete handler;
}

OR

You can create CoR handler (see above) that sets its m_next to proper handler depending on request type.

That way you may apply CoR in your solution.

class RequestTypeHandler: public BaseHandler{
    void handleImpl (Request r) override {
        cout << "RequestTypeHandler" << endl;
        if (r.type==1){
            cout << "Select Handler1" << endl;
            m_next = new Handler1;
        }
        if (r.type==2){
            cout << "Select Handler2" << endl;
            m_next = new Handler2;
        }
    }
};

int main(){
    Request r;
    r.type=1;
    RequestTypeHandler handler;
    handler.handle(r);
}

As said in answer for 1., CoR is dedicated rather to order of handlers, not just one, like in case of mapping.

Also, I'd suggest great page with Design Patterns: https://refactoring.guru


问:
hive external table on avro timestamp field returning as long
I have avro data which has a  single column timestamp column and now i am trying to create external hive table on top of the avro files .Data gets saved in avro as long and i expect the avro logical type to handle the conversion back to timestamp when i query the hive table. But that is not happening at its simply returning the long value back . How can i get this working as expected?

PS : I am using spark 2.3 and databricks com.databrospark-avro_2.11

```<code>    <dependency>
        <groupId>com.databricks</groupId>
        <artifactId>spark-avro_2.11</artifactId>
        <version>4.0.0</version>
    </dependency>
</code>```

STEP1  : Store the timestamp value to avro

```<code>val startTs=java.sql.Timestamp.valueOf("2020-05-11 14:17:57.188")
val df=Seq(startTs).toDF
df.write.avro("/test")
val avroDf=spark.read.avro("/test")
avroDf.show(false)

+-------------+
|value        |
+-------------+
|1589221077188|
+-------------+

AVSC file  generated using avro-tools from the avro data files
test.avsc
{
  "type" : "record",
  "name" : "topLevelRecord",
  "fields" : [ {
    "name" : "value",
    "type" :  "long", "logicalType": "timestamp-millis"
  } ]
}

hdfs dfs -copyFromLocal -f test.avsc /tmp/test.avsc
</code>```

STEP 2 : CREATE EXTERNAL HIVE TABLE  on AVRO data

```<code>DROP TABLE IF EXISTS test_a;

CREATE EXTERNAL TABLE  test_a
STORED AS AVRO
LOCATION '/tenants/gwm/idr/tmp/test'
TBLPROPERTIES ('avro.schema.url'='/tmp/test.avsc');

msck repair table test_a;
select * from  test_a;

+----------------+--+
|  test_a.value  |
+----------------+--+
| 1589221077188  |
+----------------+--+
</code>```

Instead of this long value i am trying to get the timestamp value.

答:
From the Avro specification:

A timestamp-millis logical type annotates an Avro long, where the long stores the number of milliseconds from the unix epoch, 1 January 1970 00:00:00.000 UTC.

Maybe this link could help you

Creating a Proper avro schema for timestamp record

Another way could be query the long value from hive or store your timestamp as string value from your Spark app:

```<code>SELECT CONCAT(FROM_UNIXTIME(CAST(SUBSTR(CAST(1589221077188 AS STRING),1,10) AS BIGINT)),'.', SUBSTR(CAST(1589221077188 AS STRING),11,13)) AS timestamp;

SELECT CONCAT(FROM_UNIXTIME(CAST(SUBSTR(CAST(time AS STRING),1,10) AS BIGINT)),'.', SUBSTR(CAST(time AS STRING),11,13)) AS timestamp;
</code>```

```<code>"2020-05-11 14:17:57.188"
</code>```

I Hope this helps.

Body:
I have avro data which has a  single column timestamp column and now i am trying to create external hive table on top of the avro files .Data gets saved in avro as long and i expect the avro logical type to handle the conversion back to timestamp when i query the hive table. But that is not happening at its simply returning the long value back . How can i get this working as expected?

PS : I am using spark 2.3 and databricks com.databrospark-avro_2.11

    <dependency>
        <groupId>com.databricks</groupId>
        <artifactId>spark-avro_2.11</artifactId>
        <version>4.0.0</version>
    </dependency>

STEP1  : Store the timestamp value to avro

val startTs=java.sql.Timestamp.valueOf("2020-05-11 14:17:57.188")
val df=Seq(startTs).toDF
df.write.avro("/test")
val avroDf=spark.read.avro("/test")
avroDf.show(false)

+-------------+
|value        |
+-------------+
|1589221077188|
+-------------+

AVSC file  generated using avro-tools from the avro data files
test.avsc
{
  "type" : "record",
  "name" : "topLevelRecord",
  "fields" : [ {
    "name" : "value",
    "type" :  "long", "logicalType": "timestamp-millis"
  } ]
}

hdfs dfs -copyFromLocal -f test.avsc /tmp/test.avsc

STEP 2 : CREATE EXTERNAL HIVE TABLE  on AVRO data

DROP TABLE IF EXISTS test_a;

CREATE EXTERNAL TABLE  test_a
STORED AS AVRO
LOCATION '/tenants/gwm/idr/tmp/test'
TBLPROPERTIES ('avro.schema.url'='/tmp/test.avsc');

msck repair table test_a;
select * from  test_a;

+----------------+--+
|  test_a.value  |
+----------------+--+
| 1589221077188  |
+----------------+--+

Instead of this long value i am trying to get the timestamp value.

Body:
From the Avro specification:

A timestamp-millis logical type annotates an Avro long, where the long stores the number of milliseconds from the unix epoch, 1 January 1970 00:00:00.000 UTC.

Maybe this link could help you

Creating a Proper avro schema for timestamp record

Another way could be query the long value from hive or store your timestamp as string value from your Spark app:

SELECT CONCAT(FROM_UNIXTIME(CAST(SUBSTR(CAST(1589221077188 AS STRING),1,10) AS BIGINT)),'.', SUBSTR(CAST(1589221077188 AS STRING),11,13)) AS timestamp;

SELECT CONCAT(FROM_UNIXTIME(CAST(SUBSTR(CAST(time AS STRING),1,10) AS BIGINT)),'.', SUBSTR(CAST(time AS STRING),11,13)) AS timestamp;

"2020-05-11 14:17:57.188"

I Hope this helps.


问:
How to create by default two columns for every features (One Hot Encoding)?
My feature engineering runs for different documents. For some documents some features do not exist and followingly the sublist consists only of the same values such as the third sublist [0,0,0,0,0]. One hot encoding of this sublist leads to only one column, while the feature lists of other documents are transformed to two columns. Is there any possibility to tell ohe also to create two columns if it consits only of one and the same value and insert the column in the right spot? The main problem is that my feature dataframe of different documents consists in the end of a different number of columns, which make them not comparable.

```<code>import pandas as pd
feature = [[0,0,1,0,0], [1,1,1,0,1], [0,0,0,0,0], [1,0,1,1,1], [1,1,0,1,1], [1,0,1,1,1], [0,1,0,0,0]]

df = pd.DataFrame(feature[0])
df_features_final  = pd.get_dummies(df[0])

for feature in feature[1:]:
    df = pd.DataFrame(feature)
    df_enc = pd.get_dummies(df[0])
    print(df_enc)
    df_features_final = pd.concat([df_features_final, df_enc], axis = 1, join ='inner')

print(df_features_final)
</code>```

The result is the following dataframe. As you can see in the changing columntitles, after column 5 does not follow a 1:

```<code>   0  1  0  1  0  0  1  0  1  0  1  0  1
0  1  0  0  1  1  0  1  0  1  0  1  1  0
1  1  0  0  1  1  1  0  0  1  1  0  0  1
2  0  1  0  1  1  0  1  1  0  0  1  1  0
3  1  0  1  0  1  0  1  0  1  0  1  1  0
4  1  0  0  1  1  0  1  0  1  0  1  1  0

</code>```

答:
I don't notice the functionality you want in pandas atleast. But, in TensorFlow, we do have

```<code>tf.one_hot(
    indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None
)
</code>```

Set depth to 2.

Body:
My feature engineering runs for different documents. For some documents some features do not exist and followingly the sublist consists only of the same values such as the third sublist [0,0,0,0,0]. One hot encoding of this sublist leads to only one column, while the feature lists of other documents are transformed to two columns. Is there any possibility to tell ohe also to create two columns if it consits only of one and the same value and insert the column in the right spot? The main problem is that my feature dataframe of different documents consists in the end of a different number of columns, which make them not comparable.

import pandas as pd
feature = [[0,0,1,0,0], [1,1,1,0,1], [0,0,0,0,0], [1,0,1,1,1], [1,1,0,1,1], [1,0,1,1,1], [0,1,0,0,0]]

df = pd.DataFrame(feature[0])
df_features_final  = pd.get_dummies(df[0])

for feature in feature[1:]:
    df = pd.DataFrame(feature)
    df_enc = pd.get_dummies(df[0])
    print(df_enc)
    df_features_final = pd.concat([df_features_final, df_enc], axis = 1, join ='inner')

print(df_features_final)

The result is the following dataframe. As you can see in the changing columntitles, after column 5 does not follow a 1:

   0  1  0  1  0  0  1  0  1  0  1  0  1
0  1  0  0  1  1  0  1  0  1  0  1  1  0
1  1  0  0  1  1  1  0  0  1  1  0  0  1
2  0  1  0  1  1  0  1  1  0  0  1  1  0
3  1  0  1  0  1  0  1  0  1  0  1  1  0
4  1  0  0  1  1  0  1  0  1  0  1  1  0

Body:
I don't notice the functionality you want in pandas atleast. But, in TensorFlow, we do have

tf.one_hot(
    indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None
)

Set depth to 2.


问:
Django - can't access admin login page
Here's the issue - I've created my project, migrated to the database django had created, and when I run the server, everything is peachy. Then I add /admin/ to my search line and it gets me to the login window.

At this point I open another command prompt window, get to the folder with my project and create a superuser. Then I try to log in using the superuser credentials, but to no avail - This site can't be reached. 127.0.0.1 refused to connect

Now, what's interesting is that when I run the server again, it won't even let me access the admin login site. I tried different browsers, I tried remigrating, and I tried creating new superusers (with the server both running and shut down) - and got the same result.

Eventually, it is only when I delete the superuser that I can access the admin page again. But if I create a new superuser, the story repeats itself.

I'm at my wits end, really. Any thoughts?

答:
Django's development server runs on port 8000 by default.

If you use a database other than the default sqlite3 database and the database server is running on the same port on which the development server runs then that might be the issue.

Try running the development server or the database server on different port. You can run the development server on different port using the following command:-

python manage.py runserver 127.0.0.1:8001

If the above solution didn't solved the problem then, try to create a superuser when the development server is not running and then restart the server and try logging in.

Title: Django - can't access admin login page


问:
Is it possible to disable dragging on a sub-element of cdkDrag?
I am using Angular CDK drag-drop from Angular Material (see documentation here). I was wondering if it is possible to disable dragging on a sub-element of cdkDrag. The problem is it is impossible to select what is written in an input of the draggable element using the mouse.

So, what I want to do is to disable dragging on all the input which are under the element which has the cdkDrag directive.

I have tried using:

cdkDragHandle: that would put the dragging on a specific element, not what I want to do here

cdkDragDisabled: that would disable dragging the whole element, not what I want to do here

Here is what my code looks like:

            <mat-form-field>
                <mat-label>Input 1</mat-label>
                <input matInput type="text">
            </mat-form-field>
            <mat-form-field>
                <mat-label>Input 2</mat-label>
                <input matInput type="number">
            </mat-form-field>

```

Thanks in advance for your help and time.

答:
Here's a simple workaround:

app.component.css

.display-none {
  display: none;
}
```

<p>app.component.html</p>

<pre class="lang-html prettyprint-override"><code><div cdkDropList (cdkDropListDropped)="drop($event)">
    <div *ngFor="let element of array" cdkDrag>
        <div>
            <mat-form-field>
                <mat-label>Input 1</mat-label>
                <input matInput type="text" cdkDrag cdkDragPreviewClass="display-none">
            </mat-form-field>
            <mat-form-field>
                <mat-label>Input 2</mat-label>
                <input matInput type="number" cdkDrag cdkDragPreviewClass="display-none">
            </mat-form-field>
        </div>
    </div>
</div>
</code>```

Just add cdkDrag cdkDragPreviewClass="display-none" to your input elements. That should help you.

Body:
I am using Angular CDK drag-drop from Angular Material (see documentation here). I was wondering if it is possible to disable dragging on a sub-element of cdkDrag. The problem is it is impossible to select what is written in an input of the draggable element using the mouse.

So, what I want to do is to disable dragging on all the input which are under the element which has the cdkDrag directive.

I have tried using:

cdkDragHandle: that would put the dragging on a specific element, not what I want to do here

cdkDragDisabled: that would disable dragging the whole element, not what I want to do here

Here is what my code looks like:

            <mat-form-field>
                <mat-label>Input 1</mat-label>
                <input matInput type="text">
            </mat-form-field>
            <mat-form-field>
                <mat-label>Input 2</mat-label>
                <input matInput type="number">
            </mat-form-field>

Thanks in advance for your help and time.

Body:
Here's a simple workaround:

app.component.css

.display-none {
  display: none;
}

app.component.html

<div cdkDropList (cdkDropListDropped)="drop($event)">
    <div *ngFor="let element of array" cdkDrag>
        <div>
            <mat-form-field>
                <mat-label>Input 1</mat-label>
                <input matInput type="text" cdkDrag cdkDragPreviewClass="display-none">
            </mat-form-field>
            <mat-form-field>
                <mat-label>Input 2</mat-label>
                <input matInput type="number" cdkDrag cdkDragPreviewClass="display-none">
            </mat-form-field>
        </div>
    </div>
</div>

Just add cdkDrag cdkDragPreviewClass="display-none" to your input elements. That should help you.


问:
Getting Screen Overflow when populating Column in flutter
I know that we can use a ListView or Expanded instead of column in such case , but when I use ListView instead of Column , I get a runtime exception for the below code .
The TextFields in the column overflow when the keyboard opens after focusing an input .

```<code>class _AddAchievementDialog extends State<AddAchievementDialog> {
  String title, description, longDescription, linksString, id;

  List<String> links;

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(
        "Add",
        textAlign: TextAlign.center,
      ),
      shape: RoundedRectangleBorder(),
      contentPadding: EdgeInsets.all(10),
      content: Container(
        padding: EdgeInsets.all(10),
        height: 350,
        child: Column(
          children: <Widget>[
            TextField(
              decoration: InputDecoration(labelText: 'Title'),
            ),
            TextField(
              keyboardType: TextInputType.multiline,
              maxLines: 2,
              decoration: InputDecoration(labelText: 'Description'),
            ),
            TextField(
              keyboardType: TextInputType.multiline,
              maxLines: 3,
              decoration: InputDecoration(labelText: 'Long Description'),
            ),
            TextField(
              decoration:
                  InputDecoration(labelText: 'Links (seperated by comma) '),
            ),
          ],
        ),
      ),
      actions: <Widget>[
        RaisedButton(
          child: Text("Submit"),
        )
      ],
    );
  }
}
</code>```

答:
You have to wrap the Column-Widget inside aScrollView- Widget and adjust some flagsit.

```<code>ListView(
  physics: NeverScrollableScrollPhysics(),
  shrinkWrap: true,
  children: <Widget>[
     Text();
  ]
);
</code>```

With those set, you prevent your Widget from showing the overflow- error; furthermore, with the physics set, you prevent the listview from showing the overscroll-ui inside the listview.

Body:
I know that we can use a ListView or Expanded instead of column in such case , but when I use ListView instead of Column , I get a runtime exception for the below code .
The TextFields in the column overflow when the keyboard opens after focusing an input .

class _AddAchievementDialog extends State<AddAchievementDialog> {
  String title, description, longDescription, linksString, id;

  List<String> links;

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(
        "Add",
        textAlign: TextAlign.center,
      ),
      shape: RoundedRectangleBorder(),
      contentPadding: EdgeInsets.all(10),
      content: Container(
        padding: EdgeInsets.all(10),
        height: 350,
        child: Column(
          children: <Widget>[
            TextField(
              decoration: InputDecoration(labelText: 'Title'),
            ),
            TextField(
              keyboardType: TextInputType.multiline,
              maxLines: 2,
              decoration: InputDecoration(labelText: 'Description'),
            ),
            TextField(
              keyboardType: TextInputType.multiline,
              maxLines: 3,
              decoration: InputDecoration(labelText: 'Long Description'),
            ),
            TextField(
              decoration:
                  InputDecoration(labelText: 'Links (seperated by comma) '),
            ),
          ],
        ),
      ),
      actions: <Widget>[
        RaisedButton(
          child: Text("Submit"),
        )
      ],
    );
  }
}

Body:
You have to wrap the Column-Widget inside aScrollView- Widget and adjust some flagsit.

ListView(
  physics: NeverScrollableScrollPhysics(),
  shrinkWrap: true,
  children: <Widget>[
     Text();
  ]
);

With those set, you prevent your Widget from showing the overflow- error; furthermore, with the physics set, you prevent the listview from showing the overscroll-ui inside the listview.


问:
MySQL query with multiple inner joins on same table
I have two tables : tblBooks and tblBookMeta

tblBookMeta holds the genres of the books, and there could be more than one.

Using this query I get all the results as shown.

```<code>SELECT * FROM tblBooks as B inner join tblBookMeta as BM ON B.BookId = BM.BookId

tblBooks                           tblBookMeta
BookId  Title                   |  BookMetaId   BookId  MetaName    MetaValue
1       My Thriller Book        |  1            1       Genre       Thriller
2       My SciFi Book           |  2            2       Genre       SciFi
3       My Thriller SciFi Book  |  3            3       Genre       Thriller
3       My Thriller SciFi Book  |  4            3       Genre       SciFi
</code>```

To query the books by genre I can use this query

```<code>SELECT * FROM tblBooks as B
inner join tblBookMeta as BM ON B.BookId = BM.BookId
WHERE MetaName = 'Genre' and MetaValue = 'Thriller'
</code>```

This will return 'My Thriller Book' and 'My Thriller SciFi book. Fine

if I only want books which have both the Thriller genre and the SciFi genre, I am getting a bit stuck. I can do it like this, but I am wondering if there is a better way without sub-queries.  I may in the future want to query on more than two genres, which would create another sub query.

```<code>SELECT * FROM tblBooks as B
inner join tblBookMeta as BM ON B.BookId = BM.BookId
WHERE MetaName = 'Genre' and MetaValue = 'Thriller'
and B.BookId in (SELECT B.BookId FROM tblBooks as B
    inner join tblBookMeta as BM ON B.BookId = BM.BookId
    WHERE MetaName = 'Genre' and MetaValue = 'SciFi')
</code>```

答:
You can do something like and check with EXPLAIN ANALYZE the better solution.

```<code>SELECT
    *
FROM
  tblBooks as B inner join tblBookMeta as TH
    ON (B.BookId = TH.BookId and TH.MetaValue = 'Thriller')
  inner join tblBookMeta as SC
    ON (B.BookId = SC.BookId and SC.MetaValue = 'SciFi')
WHERE
    MetaName = 'Genre'
</code>```

Regards

Body:
I have two tables : tblBooks and tblBookMeta

tblBookMeta holds the genres of the books, and there could be more than one.

Using this query I get all the results as shown.

SELECT * FROM tblBooks as B inner join tblBookMeta as BM ON B.BookId = BM.BookId

tblBooks                           tblBookMeta
BookId  Title                   |  BookMetaId   BookId  MetaName    MetaValue
1       My Thriller Book        |  1            1       Genre       Thriller
2       My SciFi Book           |  2            2       Genre       SciFi
3       My Thriller SciFi Book  |  3            3       Genre       Thriller
3       My Thriller SciFi Book  |  4            3       Genre       SciFi

To query the books by genre I can use this query

SELECT * FROM tblBooks as B
inner join tblBookMeta as BM ON B.BookId = BM.BookId
WHERE MetaName = 'Genre' and MetaValue = 'Thriller'

This will return 'My Thriller Book' and 'My Thriller SciFi book. Fine

if I only want books which have both the Thriller genre and the SciFi genre, I am getting a bit stuck. I can do it like this, but I am wondering if there is a better way without sub-queries.  I may in the future want to query on more than two genres, which would create another sub query.

SELECT * FROM tblBooks as B
inner join tblBookMeta as BM ON B.BookId = BM.BookId
WHERE MetaName = 'Genre' and MetaValue = 'Thriller'
and B.BookId in (SELECT B.BookId FROM tblBooks as B
    inner join tblBookMeta as BM ON B.BookId = BM.BookId
    WHERE MetaName = 'Genre' and MetaValue = 'SciFi')

Body:
You can do something like and check with EXPLAIN ANALYZE the better solution.

SELECT
    *
FROM
  tblBooks as B inner join tblBookMeta as TH
    ON (B.BookId = TH.BookId and TH.MetaValue = 'Thriller')
  inner join tblBookMeta as SC
    ON (B.BookId = SC.BookId and SC.MetaValue = 'SciFi')
WHERE
    MetaName = 'Genre'

Regards


问:
Why is TensorFlow producing different output even if I am setting the seed variable?
In this code I am trying to find the Max and the Max Index of some generated data.

I am trying to verify that I am getting the right Max score.

Issue: If I shift Line 1 down of Line 2 I get different output for the generated data, even though I am setting the seed variable. This makes it hard to debug my code. Any suggestions?

```<code>from keras import backend as K
import tensorflow as tf
box_confidence = tf.random_normal([19, 19 , 5, 1], mean=1, stddev=4, seed = 1)
boxes = tf.random_normal([19, 19, 5, 4], mean=1, stddev=4, seed = 1)
box_class_probs = tf.random_normal([19, 19, 5, 80], mean=1, stddev=4, seed = 1)

box_scores = box_confidence * box_class_probs
box_classes = K.argmax(box_scores,axis=-1)
box_class_scores = K.max(box_scores,axis=-1)

print("box_scores")
print(box_scores.shape)
print("box_classes")
print(box_classes.shape)
print("box_class_scores")
print(box_class_scores.shape)

with tf.Session() as sess:
    scores_for_box1_anch1 = box_scores[1,1,1,:].eval()
    max_scre_box1_anch1 = box_class_scores[1,1,1].eval()   ###->>Line 1
    max_scre_class_box1_anch1 = box_classes[1,1,1].eval()  ###->>Line 2

    print("scores_for_box1_anch1 : " + str(scores_for_box1_anch1))
    print("*max_scre_class_box1_anch1: " + str(max_scre_class_box1_anch1))
    print("*max_scre_box1_anch1 : " + str(max_scre_box1_anch1))
</code>```

答:
Each time you call eval or sess.run, the tensors box_confidence, boxes and box_class_probs get new random values. If you want to get results corresponding to the same random values, you need to compute them all in the same call:

with tf.Session() as sess:
    scores_for_box1_anch1, max_scre_box1_anch1, max_scre_class_box1_anch1 = sess.run([
        box_scores[1,1,1,:], box_class_scores[1,1,1], box_classes[1,1,1]])
    print("scores_for_box1_anch1 : " + str(scores_for_box1_anch1))
    print("*max_scre_class_box1_anch1: " + str(max_scre_class_box1_anch1))
    print("*max_scre_box1_anch1 : " + str(max_scre_box1_anch1))
```

Body:
In this code I am trying to find the Max and the Max Index of some generated data.

I am trying to verify that I am getting the right Max score.

Issue: If I shift Line 1 down of Line 2 I get different output for the generated data, even though I am setting the seed variable. This makes it hard to debug my code. Any suggestions?

from keras import backend as K
import tensorflow as tf
box_confidence = tf.random_normal([19, 19 , 5, 1], mean=1, stddev=4, seed = 1)
boxes = tf.random_normal([19, 19, 5, 4], mean=1, stddev=4, seed = 1)
box_class_probs = tf.random_normal([19, 19, 5, 80], mean=1, stddev=4, seed = 1)

box_scores = box_confidence * box_class_probs
box_classes = K.argmax(box_scores,axis=-1)
box_class_scores = K.max(box_scores,axis=-1)

print("box_scores")
print(box_scores.shape)
print("box_classes")
print(box_classes.shape)
print("box_class_scores")
print(box_class_scores.shape)

with tf.Session() as sess:
    scores_for_box1_anch1 = box_scores[1,1,1,:].eval()
    max_scre_box1_anch1 = box_class_scores[1,1,1].eval()   ###->>Line 1
    max_scre_class_box1_anch1 = box_classes[1,1,1].eval()  ###->>Line 2

    print("scores_for_box1_anch1 : " + str(scores_for_box1_anch1))
    print("*max_scre_class_box1_anch1: " + str(max_scre_class_box1_anch1))
    print("*max_scre_box1_anch1 : " + str(max_scre_box1_anch1))


问:
How to set value of variable for Azure Pipeline FileTransform conditionally
In my yaml I have a task defined like so:

```<code>- ${{ each profile in parameters.targetProfile }}:
        - task: FileTransform@1
          inputs:
            folderPath: '$(System.DefaultWorkingDirectory)/**/${{ Parameters.projectDir }}/*.csdef'
</code>```

The servicedefinition.csdef has a line like this:

```<code><WorkerRole name="CRWorkerRole" vmsize="#{VMSIZE}#">
</code>```

If I define the VMSIZE variable from the Azure Pipeline UI, the FileTransform works correctly. However, if I define a variable within the YAML like so:

```<code>variables:
      VMSIZE: 'Standard_A4_v2'
</code>```

it doesn't work. I have tried without quotes and also assume that the spacing is correct.

Also I am running FileTransform in a loop (see above). I want to set the value of the variable 'VMSIZE' conditionally.

Is this possible?

Update: 05/25/2020: Added the entire yaml file:

```<code>parameters:
  solution: ''
  cloudServiceProject: ''
  targetProfile: ''

stages:
  - stage: build
    displayName: build solution
    variables:
      buildPlatform: 'any cpu'
      buildConfiguration: 'release'
      VMSIZE: 'Standard_A4_v2'

    jobs:
      - job: build
        displayName: build Job
        pool:
          name: Azure Pipelines
          vmImage: 'windows-latest'
          demands:
            - msbuild
            - visualstudio
            - vstest
            - azureps

        steps:
        - task: NuGetToolInstaller@0
          displayName: 'Use NuGet 5.4.0'
          inputs:
            versionSpec: 5.4.0

        - task: NuGetCommand@2
          displayName: 'NuGet restore'
          inputs:
            restoreSolution: '${{ Parameters.solution }}'

        - task: VSBuild@1
          displayName: 'Build solution '
          inputs:
            solution: '${{ Parameters.solution }}'
            platform: '$(buildPlatform)'
            configuration: '$(buildConfiguration)'

        - ${{ each profile in parameters.targetProfile }}:
            - task: FileTransform@1
              inputs:
                folderPath: '$(System.DefaultWorkingDirectory)/**/${{ Parameters.projectDir }}/*.csdef'

            - task: VSBuild@1
              displayName: 'build cloud service project'
              inputs:
                solution: '${{ Parameters.cloudServiceProject }}'
                msbuildArgs: '/t:Publish /p:TargetProfile=${{ profile.name }}
     /p:AllowUnsafeBlocks=true /p:DebugType=None /p:SkipInvalidConfigurations=true /p:OutputPath=bin\ /p:PublishDir="$(build.artifactstagingdirectory)\\${{ profile.name }}\\"'
                platform: '$(buildPlatform)'
                configuration: '$(buildConfiguration)'

        - task: VSTest@2
          displayName: 'VsTest - testAssemblies'
          inputs:
            testAssemblyVer2: |
             **\$(buildConfiguration)\*test*.dll
             !**\obj\**
            platform: '$(buildPlatform)'
            configuration: '$(buildConfiguration)'

        - publish: $(build.artifactstagingdirectory)\\
          artifact: publishFiles
</code>```

答:
To run a task in a loop, you can create a template which will have a set of actions, and pass parameters across during your build. For example:

template.yml:

azure-pipelines.yml:

Check blog:

https://mattvsts.github.io/2019/05/04/solving-the-looping-problem-in-Azure-DevOps-Pipelines/

Body:
In my yaml I have a task defined like so:

- ${{ each profile in parameters.targetProfile }}:
        - task: FileTransform@1
          inputs:
            folderPath: '$(System.DefaultWorkingDirectory)/**/${{ Parameters.projectDir }}/*.csdef'

The servicedefinition.csdef has a line like this:

<WorkerRole name="CRWorkerRole" vmsize="#{VMSIZE}#">

If I define the VMSIZE variable from the Azure Pipeline UI, the FileTransform works correctly. However, if I define a variable within the YAML like so:

variables:
      VMSIZE: 'Standard_A4_v2'

it doesn't work. I have tried without quotes and also assume that the spacing is correct.

Also I am running FileTransform in a loop (see above). I want to set the value of the variable 'VMSIZE' conditionally.

Is this possible?

Update: 05/25/2020: Added the entire yaml file:

parameters:
  solution: ''
  cloudServiceProject: ''
  targetProfile: ''

stages:
  - stage: build
    displayName: build solution
    variables:
      buildPlatform: 'any cpu'
      buildConfiguration: 'release'
      VMSIZE: 'Standard_A4_v2'

    jobs:
      - job: build
        displayName: build Job
        pool:
          name: Azure Pipelines
          vmImage: 'windows-latest'
          demands:
            - msbuild
            - visualstudio
            - vstest
            - azureps

        steps:
        - task: NuGetToolInstaller@0
          displayName: 'Use NuGet 5.4.0'
          inputs:
            versionSpec: 5.4.0

        - task: NuGetCommand@2
          displayName: 'NuGet restore'
          inputs:
            restoreSolution: '${{ Parameters.solution }}'

        - task: VSBuild@1
          displayName: 'Build solution '
          inputs:
            solution: '${{ Parameters.solution }}'
            platform: '$(buildPlatform)'
            configuration: '$(buildConfiguration)'

        - ${{ each profile in parameters.targetProfile }}:
            - task: FileTransform@1
              inputs:
                folderPath: '$(System.DefaultWorkingDirectory)/**/${{ Parameters.projectDir }}/*.csdef'

            - task: VSBuild@1
              displayName: 'build cloud service project'
              inputs:
                solution: '${{ Parameters.cloudServiceProject }}'
                msbuildArgs: '/t:Publish /p:TargetProfile=${{ profile.name }}
     /p:AllowUnsafeBlocks=true /p:DebugType=None /p:SkipInvalidConfigurations=true /p:OutputPath=bin\ /p:PublishDir="$(build.artifactstagingdirectory)\\${{ profile.name }}\\"'
                platform: '$(buildPlatform)'
                configuration: '$(buildConfiguration)'

        - task: VSTest@2
          displayName: 'VsTest - testAssemblies'
          inputs:
            testAssemblyVer2: |
             **\$(buildConfiguration)\*test*.dll
             !**\obj\**
            platform: '$(buildPlatform)'
            configuration: '$(buildConfiguration)'

        - publish: $(build.artifactstagingdirectory)\\
          artifact: publishFiles


问:
duplicate params get array by node.js express or vue router
I have a big problem.

On all other project I've done I used apache or Nginx and PHP.
If I have a Url like /test?param=1&param=2 the value of $_REUEST['param'] is 2.

But in Node.js (Express) I get an array [1,2]

I could use new URLSearchParams(this.$route.fullPath) and than the method .get() or .getAll() to get only one value. But we have a big project and many loops and usages of this.$route.query in several files.

Is it possible to filter this.$route.query on one place?
Or is express able to change the return of this params like apache/nginx?

答:
```<code>app.use((req, res, next) => {
      if (req.query) {
        const oldQuery = JSON.stringify(req.query);
        const queryStrings = [];
        Object.keys(req.query).forEach((paramKey) => {
          if (Array.isArray(req.query[paramKey])) {
            const paramArray = req.query[paramKey];
            req.query[paramKey] = paramArray[paramArray.length - 1]; // always return the last provided value
            queryStrings.push(`${paramKey}=${req.query[paramKey]}`);
          }
        });
        const newQuery = JSON.stringify(req.query);
        if (oldQuery !== newQuery) {
          res.redirect(301, `${req.path}?${queryStrings.join('&')}`);
        }
      }
      next();
    });
</code>```

This works by a redirect. Not the perfect thing I want, but with the same result

Body:
app.use((req, res, next) => {
      if (req.query) {
        const oldQuery = JSON.stringify(req.query);
        const queryStrings = [];
        Object.keys(req.query).forEach((paramKey) => {
          if (Array.isArray(req.query[paramKey])) {
            const paramArray = req.query[paramKey];
            req.query[paramKey] = paramArray[paramArray.length - 1]; // always return the last provided value
            queryStrings.push(`${paramKey}=${req.query[paramKey]}`);
          }
        });
        const newQuery = JSON.stringify(req.query);
        if (oldQuery !== newQuery) {
          res.redirect(301, `${req.path}?${queryStrings.join('&')}`);
        }
      }
      next();
    });

This works by a redirect. Not the perfect thing I want, but with the same result


问:
How to print a string before using "*" to unpack list
Is it possible to print a string before using the * operator when unpacking a tuple:

```<code>m = ['b', 'a', 'e']
print(*m, sep = ',')

b, a, e
</code>```

I tried to print something before it:

```<code>print("String: " + *m, sep = ",")
</code>```

My desired output would be:

```<code>String: b, a, e
</code>```

Is it possible to have a string print before this, and what would be the correct syntax?

答:
I think you can use </p>

```<code>print(",".join(m))
</code>```

Body:
Is it possible to print a string before using the * operator when unpacking a tuple:

m = ['b', 'a', 'e']
print(*m, sep = ',')

b, a, e

I tried to print something before it:

print("String: " + *m, sep = ",")

My desired output would be:

String: b, a, e

Is it possible to have a string print before this, and what would be the correct syntax?

Body:
I think you can use

print(",".join(m))


问:
Difficulty Manipulating QSlider in a QGridLayout
I'm trying to create a dynamic QSlider that accepts a QVector of integer values and maps them underneath the QSlider relative to what position they represent.

Here's a screenshot of what I have now:
My Slider http://dev.kyleswebspace.com/images/QInteractiveSlider.jpg

As you can see, the ticks don't line up with their values. This is one of the issues.

The main issue I'm struggling with though, is that no matter what I change my PADDING value to (see qinteractiveslider.h), the QSlider in my widget remains the same size in relation to the grid of values.

Why isn't my QGridLayout's arguments
providing the correct amount of
padding?

How can I enforce these margins on
the QSlider?

Is there a better way of positioning
these labels? I'm open to
suggestions.

Here is the code:

qinteractiveslider.h

```<code>#ifndef QINTERACTIVESLIDER_H
#define QINTERACTIVESLIDER_H

#include <QtGui/QGridLayout>
#include <QtGui/QLabel>
#include <QtGui/QSlider>
#include <QtGui/QWidget>

class QInteractiveSlider : public QWidget
 {
     Q_OBJECT

public:
    QInteractiveSlider(QVector<int>* values, int min, int max, QWidget *parent = 0, Qt::WFlags flags = 0);
    ~QInteractiveSlider();

private:
    static const int GRID_WIDTH = 10000;
    static const int PADDING = GRID_WIDTH / 3;

    QGridLayout* m_layout;
    QSlider* m_slider;
    QVector<int>* m_values;
};
</code>```

qinteractiveslider.cpp

```<code>#include "qinteractiveslider.h"

QInteractiveSlider::QInteractiveSlider(QVector<int>* values, int min, int max, QWidget *parent, Qt::WFlags flags)
    : QWidget(parent, flags)
{
    m_layout = new QGridLayout();
    m_layout->setSpacing(0);

    m_slider = new QSlider(Qt::Horizontal);
    m_slider->setTickInterval(25);
    m_slider->setTickPosition(QSlider::TicksBelow);

    m_layout->addWidget(m_slider, 0, PADDING, 1, GRID_WIDTH - PADDING, Qt::AlignBottom);

    //populate bottom row with labels
    QVector<int>::Iterator iterator = values->begin();
    while(iterator != values->end()) {
        //place the label at the relative position under the slider
        int columnIndex = ((double)*iterator / (double)max) * (double)GRID_WIDTH;
        QString labelString = QString::number(*iterator);
        QLabel* label = new QLabel(labelString);
        m_layout->addWidget(label, 1, columnIndex, 1, 1, Qt::AlignTop);

        iterator++;
    }

    this->setLayout(m_layout);
}

QInteractiveSlider::~QInteractiveSlider()
{

}
</code>```

main.cpp

```<code>#include "qinteractiveslider.h"
#include <QtGui/QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QVector<int>* testVector = new QVector<int>();
    testVector->append(0);
    testVector->append(50);
    testVector->append(25);
    testVector->append(100);

    QInteractiveSlider* w = new QInteractiveSlider(testVector, 0, 100);
    w->show();

    return a.exec();
}
</code>```

答:
You could also perhaps use a combination of QHBoxLayouts instead that way you could space things properly without too much hassle with the margins.

Here is a screenshot of what the following code produces:

You could make it a bit prettier by putting a maximum width on the labels.  That way you could avoid having to set the left align right align on them.

```<code>#ifndef DESIGNERLS7532_H
#define DESIGNERLS7532_H

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QHBoxLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QSlider>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>

QT_BEGIN_NAMESPACE

class Ui_Form
{
public:
    QVBoxLayout *verticalLayout;
    QWidget *widget;
    QHBoxLayout *horizontalLayout;
    QSlider *horizontalSlider;
    QWidget *widget_2;
    QHBoxLayout *horizontalLayout_2;
    QLabel *label;
    QLabel *label_4;
    QLabel *label_2;
    QLabel *label_5;
    QLabel *label_3;

    void setupUi(QWidget *Form)
    {
        if (Form->objectName().isEmpty())
            Form->setObjectName(QString::fromUtf8("Form"));
        Form->resize(268, 55);
        verticalLayout = new QVBoxLayout(Form);
        verticalLayout->setSpacing(0);
        verticalLayout->setContentsMargins(0, 0, 0, 0);
        verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
        widget = new QWidget(Form);
        widget->setObjectName(QString::fromUtf8("widget"));
        horizontalLayout = new QHBoxLayout(widget);
        horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout"));
        horizontalLayout->setContentsMargins(-1, -1, -1, 0);
        horizontalSlider = new QSlider(widget);
        horizontalSlider->setObjectName(QString::fromUtf8("horizontalSlider"));
        horizontalSlider->setOrientation(Qt::Horizontal);
        horizontalSlider->setTickPosition(QSlider::TicksBelow);

        horizontalLayout->addWidget(horizontalSlider);

        verticalLayout->addWidget(widget);

        widget_2 = new QWidget(Form);
        widget_2->setObjectName(QString::fromUtf8("widget_2"));
        horizontalLayout_2 = new QHBoxLayout(widget_2);
        horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2"));
        horizontalLayout_2->setContentsMargins(-1, 0, -1, -1);
        label = new QLabel(widget_2);
        label->setObjectName(QString::fromUtf8("label"));

        horizontalLayout_2->addWidget(label);

        label_4 = new QLabel(widget_2);
        label_4->setObjectName(QString::fromUtf8("label_4"));
        label_4->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter);

        horizontalLayout_2->addWidget(label_4);

        label_2 = new QLabel(widget_2);
        label_2->setObjectName(QString::fromUtf8("label_2"));
        label_2->setAlignment(Qt::AlignCenter);

        horizontalLayout_2->addWidget(label_2);

        label_5 = new QLabel(widget_2);
        label_5->setObjectName(QString::fromUtf8("label_5"));
        label_5->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);

        horizontalLayout_2->addWidget(label_5);

        label_3 = new QLabel(widget_2);
        label_3->setObjectName(QString::fromUtf8("label_3"));
        label_3->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);

        horizontalLayout_2->addWidget(label_3);

        horizontalLayout_2->setStretch(0, 1);
        horizontalLayout_2->setStretch(1, 1);
        horizontalLayout_2->setStretch(2, 1);
        horizontalLayout_2->setStretch(3, 1);
        horizontalLayout_2->setStretch(4, 1);

        verticalLayout->addWidget(widget_2);

        retranslateUi(Form);

        QMetaObject::connectSlotsByName(Form);
    } // setupUi

    void retranslateUi(QWidget *Form)
    {
        Form->setWindowTitle(QApplication::translate("Form", "Form", 0, QApplication::UnicodeUTF8));
        label->setText(QApplication::translate("Form", "0", 0, QApplication::UnicodeUTF8));
        label_4->setText(QApplication::translate("Form", "25", 0, QApplication::UnicodeUTF8));
        label_2->setText(QApplication::translate("Form", "50", 0, QApplication::UnicodeUTF8));
        label_5->setText(QString());
        label_3->setText(QApplication::translate("Form", "100", 0, QApplication::UnicodeUTF8));
    } // retranslateUi

};

namespace Ui {
    class Form: public Ui_Form {};
} // namespace Ui

QT_END_NAMESPACE

#endif // DESIGNERLS7532_H
</code>```

Body:
I'm trying to create a dynamic QSlider that accepts a QVector of integer values and maps them underneath the QSlider relative to what position they represent.

Here's a screenshot of what I have now:
My Slider http://dev.kyleswebspace.com/images/QInteractiveSlider.jpg

As you can see, the ticks don't line up with their values. This is one of the issues.

The main issue I'm struggling with though, is that no matter what I change my PADDING value to (see qinteractiveslider.h), the QSlider in my widget remains the same size in relation to the grid of values.

Why isn't my QGridLayout's arguments
providing the correct amount of
padding?

How can I enforce these margins on
the QSlider?

Is there a better way of positioning
these labels? I'm open to
suggestions.

Here is the code:

qinteractiveslider.h

#ifndef QINTERACTIVESLIDER_H
#define QINTERACTIVESLIDER_H

#include <QtGui/QGridLayout>
#include <QtGui/QLabel>
#include <QtGui/QSlider>
#include <QtGui/QWidget>

class QInteractiveSlider : public QWidget
 {
     Q_OBJECT

public:
    QInteractiveSlider(QVector<int>* values, int min, int max, QWidget *parent = 0, Qt::WFlags flags = 0);
    ~QInteractiveSlider();

private:
    static const int GRID_WIDTH = 10000;
    static const int PADDING = GRID_WIDTH / 3;

    QGridLayout* m_layout;
    QSlider* m_slider;
    QVector<int>* m_values;
};

qinteractiveslider.cpp

#include "qinteractiveslider.h"

QInteractiveSlider::QInteractiveSlider(QVector<int>* values, int min, int max, QWidget *parent, Qt::WFlags flags)
    : QWidget(parent, flags)
{
    m_layout = new QGridLayout();
    m_layout->setSpacing(0);

    m_slider = new QSlider(Qt::Horizontal);
    m_slider->setTickInterval(25);
    m_slider->setTickPosition(QSlider::TicksBelow);

    m_layout->addWidget(m_slider, 0, PADDING, 1, GRID_WIDTH - PADDING, Qt::AlignBottom);

    //populate bottom row with labels
    QVector<int>::Iterator iterator = values->begin();
    while(iterator != values->end()) {
        //place the label at the relative position under the slider
        int columnIndex = ((double)*iterator / (double)max) * (double)GRID_WIDTH;
        QString labelString = QString::number(*iterator);
        QLabel* label = new QLabel(labelString);
        m_layout->addWidget(label, 1, columnIndex, 1, 1, Qt::AlignTop);

        iterator++;
    }

    this->setLayout(m_layout);
}

QInteractiveSlider::~QInteractiveSlider()
{

}

main.cpp

#include "qinteractiveslider.h"
#include <QtGui/QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QVector<int>* testVector = new QVector<int>();
    testVector->append(0);
    testVector->append(50);
    testVector->append(25);
    testVector->append(100);

    QInteractiveSlider* w = new QInteractiveSlider(testVector, 0, 100);
    w->show();

    return a.exec();
}

Body:
You could also perhaps use a combination of QHBoxLayouts instead that way you could space things properly without too much hassle with the margins.

Here is a screenshot of what the following code produces:

You could make it a bit prettier by putting a maximum width on the labels.  That way you could avoid having to set the left align right align on them.

#ifndef DESIGNERLS7532_H
#define DESIGNERLS7532_H

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QHBoxLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QSlider>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>

QT_BEGIN_NAMESPACE

class Ui_Form
{
public:
    QVBoxLayout *verticalLayout;
    QWidget *widget;
    QHBoxLayout *horizontalLayout;
    QSlider *horizontalSlider;
    QWidget *widget_2;
    QHBoxLayout *horizontalLayout_2;
    QLabel *label;
    QLabel *label_4;
    QLabel *label_2;
    QLabel *label_5;
    QLabel *label_3;

    void setupUi(QWidget *Form)
    {
        if (Form->objectName().isEmpty())
            Form->setObjectName(QString::fromUtf8("Form"));
        Form->resize(268, 55);
        verticalLayout = new QVBoxLayout(Form);
        verticalLayout->setSpacing(0);
        verticalLayout->setContentsMargins(0, 0, 0, 0);
        verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
        widget = new QWidget(Form);
        widget->setObjectName(QString::fromUtf8("widget"));
        horizontalLayout = new QHBoxLayout(widget);
        horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout"));
        horizontalLayout->setContentsMargins(-1, -1, -1, 0);
        horizontalSlider = new QSlider(widget);
        horizontalSlider->setObjectName(QString::fromUtf8("horizontalSlider"));
        horizontalSlider->setOrientation(Qt::Horizontal);
        horizontalSlider->setTickPosition(QSlider::TicksBelow);

        horizontalLayout->addWidget(horizontalSlider);

        verticalLayout->addWidget(widget);

        widget_2 = new QWidget(Form);
        widget_2->setObjectName(QString::fromUtf8("widget_2"));
        horizontalLayout_2 = new QHBoxLayout(widget_2);
        horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2"));
        horizontalLayout_2->setContentsMargins(-1, 0, -1, -1);
        label = new QLabel(widget_2);
        label->setObjectName(QString::fromUtf8("label"));

        horizontalLayout_2->addWidget(label);

        label_4 = new QLabel(widget_2);
        label_4->setObjectName(QString::fromUtf8("label_4"));
        label_4->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter);

        horizontalLayout_2->addWidget(label_4);

        label_2 = new QLabel(widget_2);
        label_2->setObjectName(QString::fromUtf8("label_2"));
        label_2->setAlignment(Qt::AlignCenter);

        horizontalLayout_2->addWidget(label_2);

        label_5 = new QLabel(widget_2);
        label_5->setObjectName(QString::fromUtf8("label_5"));
        label_5->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);

        horizontalLayout_2->addWidget(label_5);

        label_3 = new QLabel(widget_2);
        label_3->setObjectName(QString::fromUtf8("label_3"));
        label_3->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);

        horizontalLayout_2->addWidget(label_3);

        horizontalLayout_2->setStretch(0, 1);
        horizontalLayout_2->setStretch(1, 1);
        horizontalLayout_2->setStretch(2, 1);
        horizontalLayout_2->setStretch(3, 1);
        horizontalLayout_2->setStretch(4, 1);

        verticalLayout->addWidget(widget_2);

        retranslateUi(Form);

        QMetaObject::connectSlotsByName(Form);
    } // setupUi

    void retranslateUi(QWidget *Form)
    {
        Form->setWindowTitle(QApplication::translate("Form", "Form", 0, QApplication::UnicodeUTF8));
        label->setText(QApplication::translate("Form", "0", 0, QApplication::UnicodeUTF8));
        label_4->setText(QApplication::translate("Form", "25", 0, QApplication::UnicodeUTF8));
        label_2->setText(QApplication::translate("Form", "50", 0, QApplication::UnicodeUTF8));
        label_5->setText(QString());
        label_3->setText(QApplication::translate("Form", "100", 0, QApplication::UnicodeUTF8));
    } // retranslateUi

};

namespace Ui {
    class Form: public Ui_Form {};
} // namespace Ui

QT_END_NAMESPACE

#endif // DESIGNERLS7532_H


Title: How to find in a column when the row at time t is different from the one at t-1?

Body:
I  have a dataframe with 3 columns. For each column I would like to get when the jth row of column i is different from its past value. Ideally I would like to get the dates when this change happens.

Let me take an example to clarity what I mean. This is my dataframe:

df = structure(list(Date = c("2005-11-30", "2005-12-31", "2006-01-31",
"2006-02-28", "2006-03-31", "2006-04-30", "2006-05-31", "2006-06-30",
"2006-07-31", "2006-08-31", "2006-09-30", "2006-10-31", "2006-11-30",
"2006-12-31", "2007-01-31", "2007-02-28", "2007-03-31", "2007-04-30",
"2007-05-31", "2007-06-30"), MLF = c(3, 3.25, 3.25, 3.25, 3.5,
3.5, 3.5, 3.75, 3.75, 4, 4, 4.25, 4.25, 4.5, 4.5, 4.5, 4.75,
4.75, 4.75, 5), MRO = c(2, 2.25, 2.25, 2.25, 2.5, 2.5, 2.5, 2.75,
2.75, 3, 3, 3.25, 3.25, 3.5, 3.5, 3.5, 3.75, 3.75, 3.75, 4),
    DFR = c(1, 1.25, 1.25, 1.25, 1.5, 1.5, 1.5, 1.75, 1.75, 2,
    2, 2.25, 2.25, 2.5, 2.5, 2.5, 2.75, 2.75, 2.75, 3)), row.names = 83:102, class = "data.frame")

          Date  MLF  MRO  DFR
83  2005-11-30 3.00 2.00 1.00
84  2005-12-31 3.25 2.25 1.25
85  2006-01-31 3.25 2.25 1.25
86  2006-02-28 3.25 2.25 1.25
87  2006-03-31 3.50 2.50 1.50
88  2006-04-30 3.50 2.50 1.50
89  2006-05-31 3.50 2.50 1.50
90  2006-06-30 3.75 2.75 1.75
91  2006-07-31 3.75 2.75 1.75
92  2006-08-31 4.00 3.00 2.00
93  2006-09-30 4.00 3.00 2.00
94  2006-10-31 4.25 3.25 2.25
95  2006-11-30 4.25 3.25 2.25
96  2006-12-31 4.50 3.50 2.50
97  2007-01-31 4.50 3.50 2.50
98  2007-02-28 4.50 3.50 2.50
99  2007-03-31 4.75 3.75 2.75
100 2007-04-30 4.75 3.75 2.75
101 2007-05-31 4.75 3.75 2.75
102 2007-06-30 5.00 4.00 3.00

For each column now, I would like to have a code that tells me, for example, that 2005-12-31 3.25 2.25 1.25 differs from its previous values. I would like to do this for the entire dataframe and for each column.

Can anyone help me with this?

Thanks!

Body:
You can use lag to compare values from it's previous values.

library(dplyr)
df %>%  filter(MLF != lag(MLF) & MRO != lag(MRO) & DFR != lag(DFR))

#        Date  MLF  MRO  DFR
#1 2005-12-31 3.25 2.25 1.25
#2 2006-03-31 3.50 2.50 1.50
#3 2006-06-30 3.75 2.75 1.75
#4 2006-08-31 4.00 3.00 2.00
#5 2006-10-31 4.25 3.25 2.25
#6 2006-12-31 4.50 3.50 2.50
#7 2007-03-31 4.75 3.75 2.75
#8 2007-06-30 5.00 4.00 3.00

In data.table, we can use shift :

library(data.table)
setDT(df)[MLF != shift(MLF) & MRO != shift(MRO) & DFR != shift(DFR)]


问:
How to replace all the same text inside a blocked text in vim?
How to change this code:

```<code>    dayHour: {
        sunday: {
          openHour: null,
          closeHour: null,
        },
        monday: {
          openHour: null,
          closeHour: null,
        },
        tuesday: {
          openHour: null,
          closeHour: null,
        },
        wednesday: {
          openHour: null,
          closeHour: null,
        },
        thursday: {
          openHour: null,
          closeHour: null,
        },
        ...
     }
</code>```

to this code :

```<code>dayHour: {
    sunday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    monday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    tuesday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    wednesday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    thursday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    ...
  }
</code>```

This is what I've tried, I block the text :

```<code>openHour: null,
closeHour: null
</code>```

and I have no idea what to do next to find and replace the text I've blocked.
I have search several questions on google but I found nothing, and don't even know what keyword to search. Thanks

答:
You can use this replace command:

```<code>:%s/\(openHour: null,\n\s*closeHour: null,\?\)/\1\r      openMenu: null,\r      closeMenu: null/
</code>```

And you can even copy the indentation:

```<code>:%s/\(\s*\)\(openHour: null,\n\s*closeHour: null,\?\)/\1\2\r\1openMenu: null,\r\1closeMenu: null/
</code>```

For more information see :help :s.
I can also explain the command if you want.

Body:
How to change this code:

    dayHour: {
        sunday: {
          openHour: null,
          closeHour: null,
        },
        monday: {
          openHour: null,
          closeHour: null,
        },
        tuesday: {
          openHour: null,
          closeHour: null,
        },
        wednesday: {
          openHour: null,
          closeHour: null,
        },
        thursday: {
          openHour: null,
          closeHour: null,
        },
        ...
     }

to this code :

dayHour: {
    sunday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    monday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    tuesday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    wednesday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    thursday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    ...
  }

This is what I've tried, I block the text :

openHour: null,
closeHour: null

and I have no idea what to do next to find and replace the text I've blocked.
I have search several questions on google but I found nothing, and don't even know what keyword to search. Thanks

Body:
You can use this replace command:

:%s/\(openHour: null,\n\s*closeHour: null,\?\)/\1\r      openMenu: null,\r      closeMenu: null/

And you can even copy the indentation:

:%s/\(\s*\)\(openHour: null,\n\s*closeHour: null,\?\)/\1\2\r\1openMenu: null,\r\1closeMenu: null/

For more information see :help :s.
I can also explain the command if you want.


问:
UIDatePicker in UITextField in UITableView realtime update
This question has been bugging me a LOT lately. Any help would be appreciated.

These were my objectives:

Setup a UIDatePickerView for a UItextField in a UITableViewCell.

I have done all this so far, and I can see the picker working fine. Whenever I change the picker Value, I use NSLog to display the current value and it is working fine for every change.

This is what I want:
** Whenever I change the pickervalue, I need the value to also be changed automatically in the UITextField (which is in the UITableViewCell)**

This is my CellForRowIndexPath code:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(110, 10, 185, 30)];
    textField.clearsOnBeginEditing = YES;
    textField.textAlignment = UITextAlignmentRight;

    [cell.contentView addSubview:textField];
     UIDatePicker *datePicker = [[UIDatePicker alloc] init];
        datePicker.datePickerMode = UIDatePickerModeDate;
        [datePicker addTarget:self action:@selector(datePickerValueChangedd:) forControlEvents:UIControlEventValueChanged];
        datePicker.tag = indexPath.row;
        textField.inputView = datePicker;

        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        df.dateStyle = NSDateFormatterMediumStyle;
        NSString *local;
        local = [self datePickerValueChangedd: datePicker];
        NSLog(@"%@", local); //DISPLAYS OUTPUT ONCE
        textField.text =local;
        [datePicker reloadInputViews];
        [datePicker release];

// Configure the cell...

NSInteger row = [indexPath row];
cell.textLabel.text = [doseInfoDetailsArray objectAtIndex:row];

return cell;
 }
</code>```

I am also posting other code below.

```<code>- (NSString *)datePickerValueChangedd:(UIDatePicker*) datePicker{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 50, 68, 68)];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
label.text = [NSString stringWithFormat:@"%@",[df stringFromDate:datePicker.date]];

NSLog(@"%@", label.text); // DISPLAYS OUTPUT WHENEVER PICKER IS MOVED
doseInfoDetailsTable.reloadData;
return (label.text);
//[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(t) name:TestNotification object:label];
[df release];
</code>```

}

Output displays correctly. But I need it to change in the UITextField also.

```<code>    2011-06-01 17:32:23.740 Tab[13857:207] Jun 1, 2017
    2011-06-01 17:32:23.740 Tab[13857:207] Jun 1, 2017
    2011-06-01 17:32:25.321 Tab[13857:207] Dec 1, 2017
    2011-06-01 17:44:51.453 Tab[13857:207] Jun 1, 2017
    2011-06-01 17:44:52.605 Tab[13857:207] Jun 1, 2018
    2011-06-01 17:44:53.467 Tab[13857:207] Jun 2, 2018
    2011-06-01 17:44:54.247 Tab[13857:207] Jun 5, 2018
</code>```

答:
You don't need to instantiate multiple instances of UIDatePicker. One should do. Assign it to all the text fields. Now to update the text field, you will have to identify which text field is being updated. For this you should adopt the UITextFieldDelegate protocol and implement the textFieldDidBeginEditing: method to set the active text field. Now, when the value is changed on the UIDatePicker instance, update the active text field.

But this is sadly not enough. You will face a problem with cell reuse. To counter this, you will have to maintain an array of dates for each of your rows and update the array every time the value is changed on the UIDatePicker instance. You can identify which cell the text field belongs to by either tagging it or by getting the superview which would be a UITableViewCell instance and then calling indexPathForCell: method on the UITableView.

And on a side note, return (label.text); [df release]; is wrong as the method will return prior to df being released. You should swap the order there.

Body:
This question has been bugging me a LOT lately. Any help would be appreciated.

These were my objectives:

Setup a UIDatePickerView for a UItextField in a UITableViewCell.

I have done all this so far, and I can see the picker working fine. Whenever I change the picker Value, I use NSLog to display the current value and it is working fine for every change.

This is what I want:
** Whenever I change the pickervalue, I need the value to also be changed automatically in the UITextField (which is in the UITableViewCell)**

This is my CellForRowIndexPath code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(110, 10, 185, 30)];
    textField.clearsOnBeginEditing = YES;
    textField.textAlignment = UITextAlignmentRight;

    [cell.contentView addSubview:textField];
     UIDatePicker *datePicker = [[UIDatePicker alloc] init];
        datePicker.datePickerMode = UIDatePickerModeDate;
        [datePicker addTarget:self action:@selector(datePickerValueChangedd:) forControlEvents:UIControlEventValueChanged];
        datePicker.tag = indexPath.row;
        textField.inputView = datePicker;

        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        df.dateStyle = NSDateFormatterMediumStyle;
        NSString *local;
        local = [self datePickerValueChangedd: datePicker];
        NSLog(@"%@", local); //DISPLAYS OUTPUT ONCE
        textField.text =local;
        [datePicker reloadInputViews];
        [datePicker release];

// Configure the cell...

NSInteger row = [indexPath row];
cell.textLabel.text = [doseInfoDetailsArray objectAtIndex:row];

return cell;
 }

I am also posting other code below.

- (NSString *)datePickerValueChangedd:(UIDatePicker*) datePicker{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 50, 68, 68)];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
label.text = [NSString stringWithFormat:@"%@",[df stringFromDate:datePicker.date]];

NSLog(@"%@", label.text); // DISPLAYS OUTPUT WHENEVER PICKER IS MOVED
doseInfoDetailsTable.reloadData;
return (label.text);
//[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(t) name:TestNotification object:label];
[df release];

}

Output displays correctly. But I need it to change in the UITextField also.

    2011-06-01 17:32:23.740 Tab[13857:207] Jun 1, 2017
    2011-06-01 17:32:23.740 Tab[13857:207] Jun 1, 2017
    2011-06-01 17:32:25.321 Tab[13857:207] Dec 1, 2017
    2011-06-01 17:44:51.453 Tab[13857:207] Jun 1, 2017
    2011-06-01 17:44:52.605 Tab[13857:207] Jun 1, 2018
    2011-06-01 17:44:53.467 Tab[13857:207] Jun 2, 2018
    2011-06-01 17:44:54.247 Tab[13857:207] Jun 5, 2018


问:
How to transfer a Non Fungible token between accounts in R3 Corda?
I have created a Non fungible Evolvable token, shown below

```<code>@BelongsToContract(PropertyStateTokenTypeContract::class)
data class PropertyState1(
        val landTitle: String,
        val location: String,
        val price: String,
        val maintainer: Party,
        override val linearId: UniqueIdentifier,
        override val fractionDigits: Int = 0
) : EvolvableTokenType() {
    companion object {
        val contractId = this::class.java.enclosingClass.canonicalName
    }

    override val maintainers: List<Party> get() = listOf(maintainer)
}
</code>```

I have issued this token from a node(PartyA) to an account by using a tokenPointer as shown below

```<code>val TestAccount = subFlow(OurAccounts()).filter {  it.state.data.name == nameOfAccount  }.last()

val anonymous_party = subFlow(RequestKeyForAccount(TestAccount.state.data))
val propertytokentype = a.state.data.toPointer<PropertyState1>()

val PropertyToke  = propertytokentype issuedBy ourIdentity heldBy anonymous_party

val issue = subFlow(ConfidentialIssueTokens(listOf( PropertyToke)))
</code>```

Now I want to transfer this token to an account which is under PartyB So how can I achieve that ?

答:
Step 1.
Prepare query criteria to retrieve the non fungible token from the vault.

```<code>QueryCriteria queryCriteria = new QueryCriteria.LinearStateQueryCriteria().withUuid(Arrays.asList(tokenId)).withStatus(Vault.StateStatus.UNCONSUMED);
</code>```

Step 2.
Retrieve the non fungible token from the vault.

```<code>// grab the ticket off the ledger
StateAndRef<T20CricketTicket> stateAndRef = getServiceHub().getVaultService().
                queryBy(T20CricketTicket.class, queryCriteria).getStates().get(0);
</code>```

Step 3: get the pointer to the token

```<code>T20CricketTicket evolvableTokenType = stateAndRef.getState().getData();

//get the pointer to the T20CricketTicket
TokenPointer tokenPointer = evolvableTokenType.toPointer(evolvableTokenType.getClass());
</code>```

Party notary = getServiceHub().getNetworkMapCache().getNotaryIdentities().get(0);

Step 4 : create a transactionBuilder

```<code>//create a transactionBuilder
TransactionBuilder transactionBuilder = new TransactionBuilder(notary);
</code>```

Step 5: transfer the non fungible token from one account to other

```<code>//transfer the non fungible token from seller to buyer
//this add inputs and outputs to transactionBuilder
MoveTokensUtilitiesKt.addMoveNonFungibleTokens(transactionBuilder, getServiceHub(), tokenPointer, buyerAccount);
</code>```

Complete sample is available in the Corda repo here.

Hope that helps.

Body:
I have created a Non fungible Evolvable token, shown below

@BelongsToContract(PropertyStateTokenTypeContract::class)
data class PropertyState1(
        val landTitle: String,
        val location: String,
        val price: String,
        val maintainer: Party,
        override val linearId: UniqueIdentifier,
        override val fractionDigits: Int = 0
) : EvolvableTokenType() {
    companion object {
        val contractId = this::class.java.enclosingClass.canonicalName
    }

    override val maintainers: List<Party> get() = listOf(maintainer)
}

I have issued this token from a node(PartyA) to an account by using a tokenPointer as shown below

val TestAccount = subFlow(OurAccounts()).filter {  it.state.data.name == nameOfAccount  }.last()

val anonymous_party = subFlow(RequestKeyForAccount(TestAccount.state.data))
val propertytokentype = a.state.data.toPointer<PropertyState1>()

val PropertyToke  = propertytokentype issuedBy ourIdentity heldBy anonymous_party

val issue = subFlow(ConfidentialIssueTokens(listOf( PropertyToke)))

Now I want to transfer this token to an account which is under PartyB So how can I achieve that ?

Body:
Step 1.
Prepare query criteria to retrieve the non fungible token from the vault.

QueryCriteria queryCriteria = new QueryCriteria.LinearStateQueryCriteria().withUuid(Arrays.asList(tokenId)).withStatus(Vault.StateStatus.UNCONSUMED);

Step 2.
Retrieve the non fungible token from the vault.

// grab the ticket off the ledger
StateAndRef<T20CricketTicket> stateAndRef = getServiceHub().getVaultService().
                queryBy(T20CricketTicket.class, queryCriteria).getStates().get(0);

Step 3: get the pointer to the token

T20CricketTicket evolvableTokenType = stateAndRef.getState().getData();

//get the pointer to the T20CricketTicket
TokenPointer tokenPointer = evolvableTokenType.toPointer(evolvableTokenType.getClass());

Party notary = getServiceHub().getNetworkMapCache().getNotaryIdentities().get(0);

Step 4 : create a transactionBuilder

//create a transactionBuilder
TransactionBuilder transactionBuilder = new TransactionBuilder(notary);

Step 5: transfer the non fungible token from one account to other

//transfer the non fungible token from seller to buyer
//this add inputs and outputs to transactionBuilder
MoveTokensUtilitiesKt.addMoveNonFungibleTokens(transactionBuilder, getServiceHub(), tokenPointer, buyerAccount);

Complete sample is available in the Corda repo here.

Hope that helps.


问:
How to ignore lines starting with a string with diff?
How can I diff two files and ignore lines starting with a sequence.

E.g

```<code>File1:
abc
def
time:123

File2:
igh
def
time:345
</code>```

With unix diff it will report

```<code><time:123
>time:345
</code>```

I want to ignore this diff. Any ideas?

答:
What about this?</p>

```<code>diff <(grep -v '^time:' file1) <(grep -v '^time:' file2)
</code>```

Body:
How can I diff two files and ignore lines starting with a sequence.

E.g

File1:
abc
def
time:123

File2:
igh
def
time:345

With unix diff it will report

<time:123
>time:345

I want to ignore this diff. Any ideas?

Body:
What about this?

diff <(grep -v '^time:' file1) <(grep -v '^time:' file2)


问:
win_copy giving error when using with_items
I am trying to use win_copy in a following fashion:

```<code>    win_copy:
      src: {{item}}_outputfile.txt
      dest: c:\temp{{ item }}_outputfile.csv
    with_items:
      {{ AnArrayOfValues }}
</code>```

Now if the file does not exist Ansible giving error: FIleNotExist and it fails the script, but I want the Ansible script to continue and ignore the file which doesn't exist.
Any help in this regard?

答:
You can use ignore_errors: True with the ansible modules.

Note:- ignore_errors: True will ignore all the error but in case of win_copy we can use this as there won't be many error except for FIleNotExist

```<code>- hosts: localhost
  tasks:
    - win_copy:
        src: "{{item}}_outputfile.txt"
        dest: c:\temp{{ item }}_outputfile.csv
      with_items:
        - "{{ AnArrayOfValues }}"
      ignore_errors: true
</code>```

Body:
I am trying to use win_copy in a following fashion:

    win_copy:
      src: {{item}}_outputfile.txt
      dest: c:\temp{{ item }}_outputfile.csv
    with_items:
      {{ AnArrayOfValues }}

Now if the file does not exist Ansible giving error: FIleNotExist and it fails the script, but I want the Ansible script to continue and ignore the file which doesn't exist.
Any help in this regard?

Body:
You can use ignore_errors: True with the ansible modules.

Note:- ignore_errors: True will ignore all the error but in case of win_copy we can use this as there won't be many error except for FIleNotExist

- hosts: localhost
  tasks:
    - win_copy:
        src: "{{item}}_outputfile.txt"
        dest: c:\temp{{ item }}_outputfile.csv
      with_items:
        - "{{ AnArrayOfValues }}"
      ignore_errors: true


Title: Cumsum on one column conditional on number of occurence of values from another column

Body:
The title really is just a very rough idea and very likely not a good match for the actual problem.

I have some stock data, which looks likes this:

"DateTime","Price","Volume","Group"
2020-05-01 13:30:01.354,174.003,750,2020-05-01
2020-05-01 13:30:01.454,174.003,750,2020-05-01
2020-05-01 13:30:01.612,174.592,750,2020-05-01
2020-05-01 13:30:01.663,174.812,750,2020-05-01
2020-05-01 13:30:01.775,174.742,750,2020-05-01
2020-05-01 13:30:02.090,174.742,2000.0001,2020-05-01
2020-05-01 13:30:02.139,174.742,750,2020-05-01
2020-05-01 13:30:02.190,174.743,2000.0001,2020-05-01
2020-05-01 13:30:02.308,174.612,2000.0001,2020-05-01
2020-05-01 13:30:02.428,174.612,750,2020-05-01
2020-05-01 13:30:02.554,174.522,2000.0001,2020-05-01
2020-05-01 13:30:02.656,174.552,750,2020-05-01
2020-05-01 13:30:02.705,174.522,2000.0001,2020-05-01
2020-05-01 13:30:02.913,174.645,750,2020-05-01
2020-05-01 13:30:02.963,175.002,750,2020-05-01
2020-05-01 13:30:03.013,175.002,2000.0001,2020-05-01
2020-05-01 13:30:03.125,175.002,750,2020-05-01
2020-05-01 13:30:03.312,174.803,750,2020-05-01
2020-05-01 13:30:03.362,175.002,2000.0001,2020-05-01
2020-05-01 13:30:03.876,174.772,750,2020-05-01
2020-05-01 13:30:03.927,174.802,2000.0001,2020-05-01
2020-05-01 13:30:04.052,174.802,2000.0001,2020-05-01
2020-05-01 13:30:04.154,174.692,750,2020-05-01
2020-05-01 13:30:04.203,174.802,750,2020-05-01
2020-05-01 13:30:04.255,174.803,2000.0001,2020-05-01
2020-05-01 13:30:04.304,174.803,2000.0001,2020-05-01
2020-05-01 13:30:04.404,174.802,750,2020-05-01
2020-05-01 13:30:04.455,175.003,2000.0001,2020-05-01
2020-05-01 13:30:04.521,174.803,750,2020-05-01
2020-05-01 13:30:04.649,174.802,750,2020-05-01
2020-05-01 13:30:04.771,174.803,2000.0001,2020-05-01
2020-05-01 13:30:04.822,174.803,2000.0001,2020-05-01
2020-05-01 13:30:04.899,174.702,750,2020-05-01
2020-05-01 13:30:04.950,174.802,750,2020-05-01
2020-05-01 13:30:06.498,174.722,750,2020-05-01
2020-05-01 13:30:07.794,174.723,750,2020-05-01
2020-05-01 13:30:07.843,175.003,2000.0001,2020-05-01
2020-05-01 13:30:08.095,175.002,750,2020-05-01
2020-05-01 13:30:08.466,175.002,750,2020-05-01
2020-05-01 13:30:08.567,175.002,750,2020-05-01
2020-05-01 13:30:08.743,174.982,2000.0001,2020-05-01
2020-05-01 13:30:09.123,175.002,750,2020-05-01
2020-05-01 13:30:09.381,174.982,750,2020-05-01
2020-05-01 13:30:09.893,175.002,750,2020-05-01
2020-05-01 13:30:09.942,174.882,750,2020-05-01
2020-05-01 13:30:09.993,174.962,750,2020-05-01
2020-05-01 13:30:11.404,175.002,2000.0001,2020-05-01
2020-05-01 13:30:11.716,174.963,750,2020-05-01
2020-05-01 13:30:11.932,174.963,750,2020-05-01
2020-05-01 13:30:11.983,175.002,750,2020-05-01
2020-05-01 13:30:12.038,174.962,750,2020-05-01
2020-05-01 13:30:12.414,174.963,2000.0001,2020-05-01
2020-05-01 13:30:12.533,174.863,750,2020-05-01
2020-05-01 13:30:12.585,174.962,2000.0001,2020-05-01
2020-05-01 13:30:13.763,175.002,750,2020-05-01
2020-05-01 13:30:14.473,174.962,750,2020-05-01
2020-05-01 13:30:16.157,174.962,750,2020-05-01
2020-05-01 13:30:16.207,175.002,2000.0001,2020-05-01
2020-05-01 13:30:16.268,175.002,750,2020-05-01
2020-05-01 13:30:18.455,175.002,750,2020-05-01
2020-05-01 13:30:18.506,175.322,750,2020-05-01
2020-05-01 13:30:19.289,175.322,750,2020-05-01
2020-05-01 13:30:19.340,175.342,750,2020-05-01
2020-05-01 13:30:19.953,175.343,750,2020-05-01
2020-05-01 13:30:20.761,175.362,2000.0001,2020-05-01
2020-05-01 13:30:21.588,175.363,750,2020-05-01
2020-05-01 13:30:21.638,175.382,750,2020-05-01
2020-05-01 13:30:22.387,175.383,750,2020-05-01
2020-05-01 13:30:22.486,175.442,750,2020-05-01
2020-05-01 13:30:22.580,175.382,750,2020-05-01
2020-05-01 13:30:23.595,175.442,750,2020-05-01
2020-05-01 13:30:23.645,175.383,750,2020-05-01
2020-05-01 13:30:23.762,175.442,750,2020-05-01
2020-05-01 13:30:24.085,175.382,750,2020-05-01
2020-05-01 13:30:24.134,175.273,2000.0001,2020-05-01
2020-05-01 13:30:24.608,175.272,750,2020-05-01
2020-05-01 13:30:24.658,175.272,750,2020-05-01
2020-05-01 13:30:25.019,175.272,750,2020-05-01
2020-05-01 13:30:25.070,175.332,750,2020-05-01
2020-05-01 13:30:25.238,175.283,750,2020-05-01
2020-05-01 13:30:25.289,175.282,2000.0001,2020-05-01
2020-05-01 13:30:25.749,175.273,750,2020-05-01
2020-05-01 13:30:25.799,175.273,2000.0001,2020-05-01
2020-05-01 13:30:25.863,175.273,750,2020-05-01
2020-05-01 13:30:25.914,175.333,2000.0001,2020-05-01
2020-05-01 13:30:26.073,175.283,750,2020-05-01
2020-05-01 13:30:26.124,175.282,2000.0001,2020-05-01
2020-05-01 13:30:26.187,175.203,750,2020-05-01
2020-05-01 13:30:26.237,175.182,2000.0001,2020-05-01
2020-05-01 13:30:26.710,175.282,2000.0001,2020-05-01
2020-05-01 13:30:27.511,175.282,2000.0001,2020-05-01
2020-05-01 13:30:27.763,175.332,2000.0001,2020-05-01
2020-05-01 13:30:28.187,175.233,750,2020-05-01
2020-05-01 13:30:28.236,175.232,750,2020-05-01
2020-05-01 13:30:28.302,175.232,750,2020-05-01
2020-05-01 13:30:28.353,175.232,2000.0001,2020-05-01
2020-05-01 13:30:28.457,175.152,750,2020-05-01
2020-05-01 13:30:28.507,175.152,750,2020-05-01
2020-05-01 13:30:28.601,175.153,2000.0001,2020-05-01
2020-05-01 13:30:28.894,175.093,750,2020-05-01
2020-05-01 13:30:28.945,175.092,750,2020-05-01
2020-05-01 13:30:29.049,175.093,2000.0001,2020-05-01

What I wanted to do was to calculate a cumsum for Volume based on the sequential frequencies of values in Price column. Following is an example r output of above csv as data.frame/data.table.

                  DateTime   Price Volume      Group
 1: 2020-05-01 13:30:01.354 174.003    750 2020-05-01
 2: 2020-05-01 13:30:01.454 174.003    750 2020-05-01
 3: 2020-05-01 13:30:01.612 174.592    750 2020-05-01
 4: 2020-05-01 13:30:01.663 174.812    750 2020-05-01
 5: 2020-05-01 13:30:01.775 174.742    750 2020-05-01
 6: 2020-05-01 13:30:02.090 174.742   2000 2020-05-01
 7: 2020-05-01 13:30:02.139 174.742    750 2020-05-01
 8: 2020-05-01 13:30:02.190 174.743   2000 2020-05-01
 9: 2020-05-01 13:30:02.308 174.612   2000 2020-05-01
10: 2020-05-01 13:30:02.428 174.612    750 2020-05-01
 8: 2020-05-01 13:30:02.554 174.522   2000 2020-05-01
 9: 2020-05-01 13:30:02.656 174.552   2000 2020-05-01
10: 2020-05-01 13:30:02.705 174.522    750 2020-05-01

To explain in more details, I'll take first 2 rows and sum up their corresponding volumes into one element of an output data object (preferably data.frame); the prices of row 3 and row 4 have a frequency of 1 (unique occurrence in the price series) therefore their volumes do not need to be summed up and would produce 2 rows in output data object. price for row 5,6,7 was the same 174.742, then again I'd sum up 3 volumes and produce 1 row in output data object. The same logic applies to the rest of the data.

I've been experimenting with dplyr but to no avail; the best I could get was the index groups for each price occurrence but the natural order could not be reserved.  I can't think of a way to even get close to the result I wanted (in a vectorised flavour I was trying to avoid plain looping and writing too much logic).

as suggested by @RonakShah I'll add this expected output example. Sorry I didn't add one earlier as I really wasn't sure what it would look like. But as I thought over once again, I think I would just need an output for the cumsum volume sequence, as a single column. I don't really need another column for indexing (although apparently any additional column would serve as very-nice-to-have).

Example output:

         Cumsum.Volume
    1:       1500  # aggregated from row 1,2 as they have same price
    2:       750   # no aggregation as row 3 has occurred only once
    3:       750   # same as above
    4:       3500  # aggregation from row 4,5,6 as they have the same price
    5:       2000  # row 7 no aggregation for unique price occurrence in sequence
    6:       2750  # row 8,9 maps to same price so add them up
    7:       2000  # row 10 needs no aggregation
    8:       2000  # row 11 needs no aggregation
    9:       750   # row 12 needs no aggregation

Here's a mapping between price and volume:

`174.003` appeared twice together, so we cumsum their volumes
`174.592` appeared by itself, so we keep its volume
`174.812` appeared by itself, so we keep its volume
`174.742` appeared 3 times consecutively, so we cumsum/aggregate their volumes
`174.743` appeared by itself, so we keep its volume
`174.612` appeared twice together, so we cumsum their volumes
`174.522` appeared once by itself, we keep its volume
`174.552` appeared by itself, we keep its volume
`174,522` appeared again by itself, we keep its volume

I hope above addition could give you guys a better idea; the order of the cumsum volume was in correspondence with the natural order of the price column, but I don't need to keep the price column.

Any tips for a right direction?

Body:
As Ronak Shah says, you might just want to group by price then take the cumulative sum of the volume. However, you need to be careful, because if you just group by price, you will inadvertantly group some later rows with earlier rows (say, if the price goes up then falls back to the same place later on). I'm guessing you don't want this. Therefore you should group according to adjacent rows with the same price. You can do that like this:

library(dplyr)

df %>%
  mutate(PriceChange = cumsum(c(TRUE, diff(Price) != 0))) %>%
  group_by(PriceChange) %>%
  mutate(CumSumVolume = cumsum(Volume)) %>%
  ungroup() %>%
  select(-PriceChange) %>%
  as.data.frame()

The first few rows of output would look like this:

#>                    DateTime   Price Volume      Group CumSumVolume
#> 1   2020-05-01 13:30:01.354 174.003    750 2020-05-01          750
#> 2   2020-05-01 13:30:01.454 174.003    750 2020-05-01         1500
#> 3   2020-05-01 13:30:01.612 174.592    750 2020-05-01          750
#> 4   2020-05-01 13:30:01.663 174.812    750 2020-05-01          750
#> 5   2020-05-01 13:30:01.775 174.742    750 2020-05-01          750
#> 6   2020-05-01 13:30:02.090 174.742   2000 2020-05-01         2750
#> 7   2020-05-01 13:30:02.139 174.742    750 2020-05-01         3500
#> 8   2020-05-01 13:30:02.190 174.743   2000 2020-05-01         2000
#> 9   2020-05-01 13:30:02.308 174.612   2000 2020-05-01         2000
#> 10  2020-05-01 13:30:02.428 174.612    750 2020-05-01         2750
#> 11  2020-05-01 13:30:02.554 174.522   2000 2020-05-01         2000
#> 12  2020-05-01 13:30:02.656 174.552    750 2020-05-01          750
#> 13  2020-05-01 13:30:02.705 174.583   2000 2020-05-01         2000