问:
Unity Particle system: Change Emitter Velocity with Script
I have a particle system connected with an object that it follows. The Emitter Velocity is here set on Rigidbody. What I want is to have the particle system follow the object, as it does, but when detecting a touch input the particles are to follow the touch input, changing the Emitter Velocity to Transform. When running the code that I attached, there are two compiler errors that I have tried and failed to fix. Would appreciate someone taking a look at it.

The 'Particle System' does not contain a definition for
'emitterVelocity' and no accessible extension method
'emitterVelocity' accepting a first argument of type 'ParticleSystem'
could be found. line 28.

'Transform' is a type, which is not valid in the given context.
line 28.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DragFingerMove : MonoBehaviour
{
    private Vector3 touchPosition;
    private ParticleSystem ps;
    private Vector3 direction;
    private float moveSpeed = 10f;

    // Use this for initialization
    private void Start()
    {
        ps = GetComponent<ParticleSystem>();
    }

    // Update is called once per frame
    private void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
            touchPosition.z = 0;
            direction = (touchPosition - transform.position);
            ps.emitterVelocity = Transform;
            ps.velocity = new Vector2(direction.x, direction.y) * moveSpeed;

            if (touch.phase == TouchPhase.Ended)
                ps.velocity = Vector2.zero;
        }
    }
}
</code>```

答:
First, when trying to access the Transform to which a Unity component is attached, you want to use transform (note lowercase "t" vs. uppercase). Switch Transform to transform or this.transform.

transform is a property that all MonoBehaviours have that gives the same value as calling this.GetComponent<Transform>(). By contrast, Transform is the type UnityEngine.Transform, which is to say there exists a class with that name.

Second, in regards to setting the emitter, you can set the emitterVelocityMode (labelled as "Emitter Velocity") in the particle system's main component. The values for emitterVelocityMode are an enum named "ParticleSystemEmitterVelocityMode".

You can say:

```<code>var ps_main = GetComponent<ParticleSystem>().main;
ps_main.emitterVelocityMode = ParticleSystemEmitterVelocityMode.Transform;
</code>```

Body:
I have a particle system connected with an object that it follows. The Emitter Velocity is here set on Rigidbody. What I want is to have the particle system follow the object, as it does, but when detecting a touch input the particles are to follow the touch input, changing the Emitter Velocity to Transform. When running the code that I attached, there are two compiler errors that I have tried and failed to fix. Would appreciate someone taking a look at it.

The 'Particle System' does not contain a definition for
'emitterVelocity' and no accessible extension method
'emitterVelocity' accepting a first argument of type 'ParticleSystem'
could be found. line 28.

'Transform' is a type, which is not valid in the given context.
line 28.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DragFingerMove : MonoBehaviour
{
    private Vector3 touchPosition;
    private ParticleSystem ps;
    private Vector3 direction;
    private float moveSpeed = 10f;

    // Use this for initialization
    private void Start()
    {
        ps = GetComponent<ParticleSystem>();
    }

    // Update is called once per frame
    private void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
            touchPosition.z = 0;
            direction = (touchPosition - transform.position);
            ps.emitterVelocity = Transform;
            ps.velocity = new Vector2(direction.x, direction.y) * moveSpeed;

            if (touch.phase == TouchPhase.Ended)
                ps.velocity = Vector2.zero;
        }
    }
}

Body:
First, when trying to access the Transform to which a Unity component is attached, you want to use transform (note lowercase "t" vs. uppercase). Switch Transform to transform or this.transform.

transform is a property that all MonoBehaviours have that gives the same value as calling this.GetComponent<Transform>(). By contrast, Transform is the type UnityEngine.Transform, which is to say there exists a class with that name.

Second, in regards to setting the emitter, you can set the emitterVelocityMode (labelled as "Emitter Velocity") in the particle system's main component. The values for emitterVelocityMode are an enum named "ParticleSystemEmitterVelocityMode".

You can say:

var ps_main = GetComponent<ParticleSystem>().main;
ps_main.emitterVelocityMode = ParticleSystemEmitterVelocityMode.Transform;


来源: stackexchange

问:
ModuleNotFoundError, i am trying to install pandas but i got some error
i am trying to install Pandas(or any other libraries) by running "pip install library-name" command in my command prompt(or also in window power shell) but i got some error(i attached screen shot for your reference,please see the screen shotenter image description here)i.e "ModuleNotFoundError: No module named 'pip._internal.vcs.git'" and i am not able to solve it out...please help me out on this</p>

答:
I would suggest reinstalling pip by following this link or installing miniconda here.

After installing miniconda, create a new environment (conda create --name NAME OF ENVIRONMENT python=3.6) and then activate it (conda activate NAME OF ENVIRONMENT).

Replace NAME OF ENVIRONMENT with your name of choice (2 environments can't have the same name). Anaconda is not needed for this, only miniconda.

Every time you make a new environment, a new pip is installed, ensuring that it will almost always work with ease.

ContentLicense: CC BY-SA 4.0


问:
Is there a way to console.log when a variable has a certain value?
I am a starter coder and cannot find the solution to this problem. I have tried the code

```<code>var X = "Angry";
if X = "Angry" console.log(X is Angry)
</code>```

When I run this code I am informed of an error on the third line.

答:
If x == "angry"

Double equal sign for condition of equality

Body:
I am a starter coder and cannot find the solution to this problem. I have tried the code

var X = "Angry";
if X = "Angry" console.log(X is Angry)

When I run this code I am informed of an error on the third line.


问:
Why is it possible to update UI using Handler created in a background Thread?
I have a worker class which has a Handler created in it. When I try to update my UI using the handler created in background thread its updating the UI and there is no crash here. Ideally it should crash as its running in the background thread. Please find the code below:

```<code>class WorkerThread(val mainThreadHandler: Handler, handlerThreadName: String) :
  HandlerThread(handlerThreadName) {

  lateinit var workerThreadHandler: Handler

override fun onLooperPrepared() {
    super.onLooperPrepared()
    Log.d("LLoyd", "onLooperPrepared")

}

override fun run() {
    super.run()
    Log.d("LLoyd", "run method called")

}

fun startTask(){
    workerThreadHandler = object : Handler(this.looper) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            Log.d(
                "Lloyd",
                "Message from Main Thread received " + msg.what + "  Thread name  " +
currentThread().name
            )
            val message = Message()
            message.what = msg.what
            mainThreadHandler.sendMessage(message)
        }
    }

 }
}
</code>```

This startTask() is called from activity on click of a button as below:

```<code>val workerThread = WorkerThread(mainThreadHandler, "Lloyd")
    workerThread.start()
    btn_task1.setOnClickListener {
        workerThread.startTask()
        val message = Message()
        message.what = FROM_MAINTHREAD
        workerThread.workerThreadHandler.sendMessage(message)
        val message1 = Message()
        message.what = 55
        Log.d("Lloyd ", "Outside Thread name " + Thread.currentThread().name)

        workerThread.workerThreadHandler.post {
            Log.d("Lloyd ", "Runnable Thread name " + currentThread().name)
            btn_task1.text = "Task 2"
            tv.text= "YAAAAAAAAAAAAAAAAAAAAAAy"
        }
    }
</code>```

Any kind of help is Appreciated!

答:
When you connect a Handler to your UI thread, the code that handles
  messages runs on the UI thread.

taken from the docs

i believe because you're calling the workerThread.startTask() from the button click, which is the UI thread, the handler is simply returning the result to the UI thread as well, which is why the UI will update as well

Body:
I have a worker class which has a Handler created in it. When I try to update my UI using the handler created in background thread its updating the UI and there is no crash here. Ideally it should crash as its running in the background thread. Please find the code below:

class WorkerThread(val mainThreadHandler: Handler, handlerThreadName: String) :
  HandlerThread(handlerThreadName) {

  lateinit var workerThreadHandler: Handler

override fun onLooperPrepared() {
    super.onLooperPrepared()
    Log.d("LLoyd", "onLooperPrepared")

}

override fun run() {
    super.run()
    Log.d("LLoyd", "run method called")

}

fun startTask(){
    workerThreadHandler = object : Handler(this.looper) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            Log.d(
                "Lloyd",
                "Message from Main Thread received " + msg.what + "  Thread name  " +
currentThread().name
            )
            val message = Message()
            message.what = msg.what
            mainThreadHandler.sendMessage(message)
        }
    }

 }
}

This startTask() is called from activity on click of a button as below:

val workerThread = WorkerThread(mainThreadHandler, "Lloyd")
    workerThread.start()
    btn_task1.setOnClickListener {
        workerThread.startTask()
        val message = Message()
        message.what = FROM_MAINTHREAD
        workerThread.workerThreadHandler.sendMessage(message)
        val message1 = Message()
        message.what = 55
        Log.d("Lloyd ", "Outside Thread name " + Thread.currentThread().name)

        workerThread.workerThreadHandler.post {
            Log.d("Lloyd ", "Runnable Thread name " + currentThread().name)
            btn_task1.text = "Task 2"
            tv.text= "YAAAAAAAAAAAAAAAAAAAAAAy"
        }
    }

Any kind of help is Appreciated!


问:
How do I only return SOME fields ($project) from Mongodb aggregation, while also using $match, $lookup AND $filter
I am VERY close to getting what I want out of this query... but I only want SOME of the fields returned and right now it is returning all of them

NOTE: This is a refinement : I am now asking how to return only certain fields, while my similar question asks how to return the data between a start and end date

In addition, can somebody please please provide an answer using the MongoDB Playground with MY data sets so I can try it out... I can't quite figure out how to "name" the data sets so they work in the playground !

Register Schema

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const RegisterSchema = new Schema({
    userId: {type: Schema.Types.ObjectId, required: true},
    accessToken: {type:String, required: true, default: null},
})
module.exports = Register = mongoose.model( 'register', RegisterSchema)
```

<p>Here is some register data</p>

<pre class="lang-js prettyprint-override"><code>[
  {
    "_id": "5eac9e815fc57b07f5d0d29f",
    "userId": "5ea108babb65b800172b11be",
    "accessToken": "111"
  },
  {
    "_id": "5ecaeba3c7b910d3276df839",
    "userId": "5e6c2dddad72870c84f8476b",
    "accessToken": "222"
  }
]
</code>```

The next document contains data that is related to the Register schema via the accessToken

Notifications

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const NotificationSchema = new Schema({
    accessToken: {type:String, required: true},
    summaryId: {type:Number, required: true},
    dateCreated: {type: Date, default: Date.now},

    // I don't want these returned in the final results
    dontWantThis1: {type:Number, required: true},
    dontWantThis2: {type:Number, required: true},
})
module.exports = Notification = mongoose.model( 'notification', NotificationSchema)
```

<p>Here is some notification data</p>

<pre class="lang-js prettyprint-override"><code>[{
    "_id": "5ebf0390c719e60004f42e74",
    "accessToken": "111",
    "summaryId": 1111,
    "dontWantThis1": 61,
    "dontWantThis2": 62,
    "dateCreated": "2020-04-17T00:00:00.000+00:00" },
  {
    "_id": "6ebf0390c719e60004f42e76",
    "accessToken": "222",
    "summaryId": 2221,
    "dontWantThis1": 71,
    "dontWantThis2": 72,
    "dateCreated": "2020-04-18T00:00:00.000+00:00" },
  {
    "_id": "6ebf0390c719e60004f42e78",
    "accessToken": "111",
    "summaryId": 1112,
    "dontWantThis1": 611,
    "dontWantThis2": 622,
    "dateCreated": "2020-05-25T00:00:00.000+00:00" },
  {
    "_id": "6ebf0390c719e60004f42e80",
    "accessToken": "222",
    "summaryId": 2222,
    "dontWantThis1": 711,
    "dontWantThis2": 722,
    "dateCreated": "2020-05-26T00:00:00.000+00:00" }
]
</code>```

Works, returns data between the two dates, but

This code returns everything, including the 'dontWantThis1' and 'dontWantThis2'

NOTE

I do not want the fields prefaced with 'dontWantThis' - but that is only to show which ones I don't want... I don't literally want to exclude fields prefaced with 'dontWantThis' ..... they could be named 'foo' or 'apple' or 'dog' they are just named that way to indicate that I don't want them

        // make sure the input dates are REALLY date objects
        // I only want to see notifications for the month of May (in this example)
        var dateStart = new Date('2020-05-01T00:00:00.000+00:00');
        var dateEnd = new Date('2020-05-30T00:00:00.000+00:00');

        var match = {$match: { userId: mongoose.Types.ObjectId(userId) } };

        var lookup ={
            $lookup:
            {
                from: "my_Notifications",
                localField: "accessToken",
                foreignField: "accessToken",
                as: "notifications"
            }
        };

        var dateCondition = { $and: [
            { $gte: [ "$$item.dateCreated", dateStart ] },
            { $lte: [ "$$item.dateCreated", dateEnd ] }
          ]}

        var project = {
            $project: {
                notifications: {
                    $filter: {
                    input: "$notifications",
                    as: "item",
                    cond: dateCondition
                    } } }
        };

        var agg = [
            match,
            lookup,
            project
        ];

        Register.aggregate(agg)
        .then( ..... )
```

<h2>Try 1</h2>

<p>I thought I could do something like this, but it still returns ALL of the notification fields</p>

<pre class="lang-js prettyprint-override"><code>        var project = {
            $project: {
                "_id": 1,
                "userId": 1,
                "accessToken":1,
                "count":{$size:"$notifications"},
                "notifications._id":1,
                "notifications.summaryId": 1,
                "notifications.dateCreated":1,

                notifications : {
                    $filter: {
                    input: "$notifications",
                    as: "item",
                    cond: dateCondition
                    },
            }}
        };
</code>```

SOLUTION

I created another projection and added that to the pipeline:

        var project2 = {
            $project: {
                "_id": 1,
                "userId": 1,
                "accessToken":1,
                "count":{$size:"$notifications"},
                "notifications._id":1,
                "notifications.summaryId": 1,
                "notifications.dateCreated":1,
                "notifications.dateProcessed":1,
            }
        };

        var agg = [
            match,
            lookup,
            project,
            project2,
        ];
```

Thanks!!

答:
https://stackoverflow.com/users/6635464/ngshravil-py was spot on.

I created another projection:

        var project2 = {
            $project: {
                "_id": 1,
                "userId": 1,
                "accessToken":1,
                "count":{$size:"$notifications"},
                "notifications._id":1,
                "notifications.summaryId": 1,
                "notifications.dateCreated":1,
                "notifications.dateProcessed":1,
            }
        };
```

<p>Then added it to my aggregation pipeline:</p>

<pre class="lang-js prettyprint-override"><code>        var agg = [
            match,
            lookup,
            project,
            project2,
        ];
</code>```

Worked ! -- thank you  https://stackoverflow.com/users/6635464/ngshravil-py

Body:
I am VERY close to getting what I want out of this query... but I only want SOME of the fields returned and right now it is returning all of them

NOTE: This is a refinement : I am now asking how to return only certain fields, while my similar question asks how to return the data between a start and end date

In addition, can somebody please please provide an answer using the MongoDB Playground with MY data sets so I can try it out... I can't quite figure out how to "name" the data sets so they work in the playground !

Register Schema

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const RegisterSchema = new Schema({
    userId: {type: Schema.Types.ObjectId, required: true},
    accessToken: {type:String, required: true, default: null},
})
module.exports = Register = mongoose.model( 'register', RegisterSchema)

Here is some register data

[
  {
    "_id": "5eac9e815fc57b07f5d0d29f",
    "userId": "5ea108babb65b800172b11be",
    "accessToken": "111"
  },
  {
    "_id": "5ecaeba3c7b910d3276df839",
    "userId": "5e6c2dddad72870c84f8476b",
    "accessToken": "222"
  }
]

The next document contains data that is related to the Register schema via the accessToken

Notifications

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const NotificationSchema = new Schema({
    accessToken: {type:String, required: true},
    summaryId: {type:Number, required: true},
    dateCreated: {type: Date, default: Date.now},

    // I don't want these returned in the final results
    dontWantThis1: {type:Number, required: true},
    dontWantThis2: {type:Number, required: true},
})
module.exports = Notification = mongoose.model( 'notification', NotificationSchema)

Here is some notification data

[{
    "_id": "5ebf0390c719e60004f42e74",
    "accessToken": "111",
    "summaryId": 1111,
    "dontWantThis1": 61,
    "dontWantThis2": 62,
    "dateCreated": "2020-04-17T00:00:00.000+00:00" },
  {
    "_id": "6ebf0390c719e60004f42e76",
    "accessToken": "222",
    "summaryId": 2221,
    "dontWantThis1": 71,
    "dontWantThis2": 72,
    "dateCreated": "2020-04-18T00:00:00.000+00:00" },
  {
    "_id": "6ebf0390c719e60004f42e78",
    "accessToken": "111",
    "summaryId": 1112,
    "dontWantThis1": 611,
    "dontWantThis2": 622,
    "dateCreated": "2020-05-25T00:00:00.000+00:00" },
  {
    "_id": "6ebf0390c719e60004f42e80",
    "accessToken": "222",
    "summaryId": 2222,
    "dontWantThis1": 711,
    "dontWantThis2": 722,
    "dateCreated": "2020-05-26T00:00:00.000+00:00" }
]

Works, returns data between the two dates, but

This code returns everything, including the 'dontWantThis1' and 'dontWantThis2'

NOTE

I do not want the fields prefaced with 'dontWantThis' - but that is only to show which ones I don't want... I don't literally want to exclude fields prefaced with 'dontWantThis' ..... they could be named 'foo' or 'apple' or 'dog' they are just named that way to indicate that I don't want them

        // make sure the input dates are REALLY date objects
        // I only want to see notifications for the month of May (in this example)
        var dateStart = new Date('2020-05-01T00:00:00.000+00:00');
        var dateEnd = new Date('2020-05-30T00:00:00.000+00:00');

        var match = {$match: { userId: mongoose.Types.ObjectId(userId) } };

        var lookup ={
            $lookup:
            {
                from: "my_Notifications",
                localField: "accessToken",
                foreignField: "accessToken",
                as: "notifications"
            }
        };

        var dateCondition = { $and: [
            { $gte: [ "$$item.dateCreated", dateStart ] },
            { $lte: [ "$$item.dateCreated", dateEnd ] }
          ]}

        var project = {
            $project: {
                notifications: {
                    $filter: {
                    input: "$notifications",
                    as: "item",
                    cond: dateCondition
                    } } }
        };

        var agg = [
            match,
            lookup,
            project
        ];

        Register.aggregate(agg)
        .then( ..... )

Try 1

I thought I could do something like this, but it still returns ALL of the notification fields

        var project = {
            $project: {
                "_id": 1,
                "userId": 1,
                "accessToken":1,
                "count":{$size:"$notifications"},
                "notifications._id":1,
                "notifications.summaryId": 1,
                "notifications.dateCreated":1,

                notifications : {
                    $filter: {
                    input: "$notifications",
                    as: "item",
                    cond: dateCondition
                    },
            }}
        };

SOLUTION

I created another projection and added that to the pipeline:

        var project2 = {
            $project: {
                "_id": 1,
                "userId": 1,
                "accessToken":1,
                "count":{$size:"$notifications"},
                "notifications._id":1,
                "notifications.summaryId": 1,
                "notifications.dateCreated":1,
                "notifications.dateProcessed":1,
            }
        };

        var agg = [
            match,
            lookup,
            project,
            project2,
        ];

Thanks!!

Body:
https://stackoverflow.com/users/6635464/ngshravil-py was spot on.

I created another projection:

        var project2 = {
            $project: {
                "_id": 1,
                "userId": 1,
                "accessToken":1,
                "count":{$size:"$notifications"},
                "notifications._id":1,
                "notifications.summaryId": 1,
                "notifications.dateCreated":1,
                "notifications.dateProcessed":1,
            }
        };

Then added it to my aggregation pipeline:

        var agg = [
            match,
            lookup,
            project,
            project2,
        ];

Worked ! -- thank you  https://stackoverflow.com/users/6635464/ngshravil-py


问:
pandas dataframe - does filtering / selecting cols by String preserve order?
I have a use case where I have say 10 cols out of which 5 start with the string 'Region'. I need to get a resulting dataframe which only contains those cols (starting with string 'Region'). Not only that, I need to make sure the order is preserved (e.g. if in original df, the col order is 'Region 1', 'Region 2', 'Region 3' -- this should be preserved and not result in 'Region 3', 'Region 2', 'Region 1' instead).

Would following the 'accepted answer' for this question preserve the order or is there some other method to achieve that?

stackoverflow - find-column-whose-name-contains-a-specific-string

答:
Yes, it will. df.columns is a list, when you iterate over list, you preserve the order of the list. Thus, you can use the answer from the mentioned link:

```<code>region_cols = [col for col in df.columns if 'Region' in col]
</code>```

df[region_cols] - will be the df you require.

Body:
Yes, it will. df.columns is a list, when you iterate over list, you preserve the order of the list. Thus, you can use the answer from the mentioned link:

region_cols = [col for col in df.columns if 'Region' in col]

df[region_cols] - will be the df you require.


问:
Stop all Pods in a StatefulSet before scaling it up or down
My team is currently working on migrating a Discord chat bot to Kubernetes. We plan on using a StatefulSet for the main bot service, as each Shard (pod) should only have a single connection to the Gateway. Whenever a shard connects to said Gateway, it tells it its ID (in our case the pod's ordinal index) and how many shards we are running in total (the amount of replicas in the StatefulSet).

Having to tell the gateway the total number of shards means that in order to scale our StatefulSet up or down we'd have to stop all pods in that StatefulSet before starting new ones with the updated value.

How can I achieve that? Preferrably through configuration so I don't have to run a special command each time.

答:
Try kubectl rollout restart sts <sts name> command. It'll restart the pods one by one in a RollingUpdate way.

Scale down the sts
kubectl scale --replicas=0 sts <sts name>

Scale up the sts
kubectl scale --replicas=<number of replicas> sts <sts name>


问:
Any way to get flow status (maybe like, running, stopped, stopped with exception) with spring integration?
Recently, I was trying to build a rest service to create, start and stop an integration flow (which was reading an RSS feed and printing on console), and I was able to achieve that.

But my next requirement was to get status (maybe like, running, stopped, stopped with exception) from the already running flow, and I was unable to do that, I cannot see any method related to that in "IntegrationFlowRegistration".

Also, is there a way to store "IntegrationFlow" in RDBMS like MySql, etc?

答:
Well, the flow by itself is just a logical container for components it connects. Even though we really can get somehow access to all those components in one IntegrationFlow, that doesn't mean that your whole solution contains only one IntegrationFlow. It is fully normal to connect components from different IntegrationFlows since at runtime they are fully not related to the IntegrationFlow created them. Those runtime components are identical after any configuration parsing we have in the framework: XML, Java DSL, Kotlin DSL or just plain Java & Annotation configuration. You even can create all the beans manually and still at runtime it is going to be an EIP solution.

What I'm trying to say that it is wrong to try to find a solution for the whole flow state. Or you should consult some individual component (e.g. the mentioned RSS one), or you should have some separate component to track such a custom state.

See Lifecycle contract. Most of Spring Integration implements it, so you can check its isRunning() whenever you need. In fact even a StandardIntegrationFlow implement this one, but you should not fully rely on it because your final solution might consist from several flows or many independent components.

There is no anything like stopped with exception - we don't stop components because of an error. Instead you can enable metrics and check channel or handlers success and failure send counts: https://docs.spring.io/spring-integration/docs/5.3.0.RELEASE/reference/html/system-management.html#metrics-management


问:
How can I replace multiple strings with rollup-replace
The first replace works, the second not. I just can't get it from the docs here what to do:
https://github.com/rollup/plugins/tree/master/packages/replace

```<code>export default {
  input: './src/js/index.js',
  output: {
    file: 'dist/build.js',
    format: 'iife',
  },
  plugins: [
    replace(
      { 'originalprefix-': 'myprefix-', delimiters: ['', ''] },
      { 'ABCprefix': 'DEFprefix', delimiters: ['', ''] }
    ),
</code>```

I also tried this, but it seems multiple runs create double replaces:

```<code>    replace(
      { 'origprefix-': 'myprefix-', delimiters: ['', ''] },
    ),
    replace(
      { 'ABCprefix': 'DEFprefix', delimiters: ['', ''] }
    ),
</code>```

Same here:

```<code>    replace(
      {
       'origprefix-': 'myprefix-', delimiters: ['', ''],
       'ABCprefix': 'DEFprefix', delimiters: ['', '']
      }
    ),
</code>```

答:
```<code>replace({
    'origprefix-': 'myprefix-',
    'ABCprefix': 'DEFprefix',
    delimiters: ['', '']
}),
</code>```

Body:
The first replace works, the second not. I just can't get it from the docs here what to do:
https://github.com/rollup/plugins/tree/master/packages/replace

export default {
  input: './src/js/index.js',
  output: {
    file: 'dist/build.js',
    format: 'iife',
  },
  plugins: [
    replace(
      { 'originalprefix-': 'myprefix-', delimiters: ['', ''] },
      { 'ABCprefix': 'DEFprefix', delimiters: ['', ''] }
    ),

I also tried this, but it seems multiple runs create double replaces:

    replace(
      { 'origprefix-': 'myprefix-', delimiters: ['', ''] },
    ),
    replace(
      { 'ABCprefix': 'DEFprefix', delimiters: ['', ''] }
    ),

Same here:

    replace(
      {
       'origprefix-': 'myprefix-', delimiters: ['', ''],
       'ABCprefix': 'DEFprefix', delimiters: ['', '']
      }
    ),


问:
Reactive nesting forms. Getting error cannot read property 'hasError' of undefined
I used reactive nesting forms of angular 8 with angular material.

in component.ts file

```<code>this.dataForm = this.formBuilder.group({
     name: [null, Validators.required],
     user: this.formBuilder.group({
        firstname: [null, Validators.required],
        lastname: [null, Validators.required]
     })
});

get dataControls() {
  return this.dataForm.controls;
}
</code>```

In component.html file

```<code><form [formGroup]="dataForm">
  <mat-form-field>
     <mat-label>Name</mat-label>
     <input matInput type="text" formControlName="name" required>
     <mat-error *ngIf="dataControls.name.hasError('required')">Name required</mat-error>
  </mat-form-field>
  <div formGroupName="user">
  <mat-form-field>
     <mat-label>First Name</mat-label>
     <input matInput type="text" formControlName="firstname" required>
     <mat-error *ngIf="dataControls.firstname.hasError('required')">Firstname required</mat-error>
  </mat-form-field>
  <mat-form-field>
     <mat-label>Last Name</mat-label>
     <input matInput type="text" formControlName="lastname" required>
     <mat-error *ngIf="dataControls.lastname.hasError('required')">Lastname required</mat-error>
  </mat-form-field>
  </div>
</form>
</code>```

Getting error cannot read property 'hasError' of undefined. I tried like

<mat-error *ngIf="dataControls.user.firstname.hasError('required')">Firstname required</mat-error>

But not work

答:
Rather, the problem is that only reactive forms take:
1 - FormControl
2 - FormGroup
3 - FormArray

If you need to make a nested form, try something like this

```<code>public dataForm:FormGroup = new FormGroup({
    name: ['', [Validators.required]],
    user: new FormGroup({
       firstname: new FormControl(''),
       lastname: new FormControl('')
    })
})
</code>```

and check errors

```<code>isControlInvalid(controlName: string): boolean {
    const control = this.formBasic.controls[controlName];
    const result = control.invalid && control.touched;
    return result;
}
</code>```

in component

```<code><form [formGroup]="dataForm">
   <div>
   <input type="text" formControlName="name">
   <div class="error" *ngIf="isControlInvalid('name')"></div>
   </div>
   <fieldset formGroupName="user">
     <input type="text" formControlName="firstname">
     <input type="text" formControlName="lastname">
   </fieldset>
</form>
</code>```

I adhere to the logic that there is no need to push the displayed component into a large logic, for conditions it is ideal to check the value true \ false

Body:
I used reactive nesting forms of angular 8 with angular material.

in component.ts file

this.dataForm = this.formBuilder.group({
     name: [null, Validators.required],
     user: this.formBuilder.group({
        firstname: [null, Validators.required],
        lastname: [null, Validators.required]
     })
});

get dataControls() {
  return this.dataForm.controls;
}

In component.html file

<form [formGroup]="dataForm">
  <mat-form-field>
     <mat-label>Name</mat-label>
     <input matInput type="text" formControlName="name" required>
     <mat-error *ngIf="dataControls.name.hasError('required')">Name required</mat-error>
  </mat-form-field>

  <mat-form-field>
     <mat-label>First Name</mat-label>
     <input matInput type="text" formControlName="firstname" required>
     <mat-error *ngIf="dataControls.firstname.hasError('required')">Firstname required</mat-error>
  </mat-form-field>
  <mat-form-field>
     <mat-label>Last Name</mat-label>
     <input matInput type="text" formControlName="lastname" required>
     <mat-error *ngIf="dataControls.lastname.hasError('required')">Lastname required</mat-error>
  </mat-form-field>

</form>

Getting error cannot read property 'hasError' of undefined. I tried like

<mat-error *ngIf="dataControls.user.firstname.hasError('required')">Firstname required</mat-error>

But not work

Body:
Rather, the problem is that only reactive forms take:
1 - FormControl
2 - FormGroup
3 - FormArray

If you need to make a nested form, try something like this

public dataForm:FormGroup = new FormGroup({
    name: ['', [Validators.required]],
    user: new FormGroup({
       firstname: new FormControl(''),
       lastname: new FormControl('')
    })
})

and check errors

isControlInvalid(controlName: string): boolean {
    const control = this.formBasic.controls[controlName];
    const result = control.invalid && control.touched;
    return result;
}

in component

<form [formGroup]="dataForm">
   <div>
   <input type="text" formControlName="name">
   <div class="error" *ngIf="isControlInvalid('name')"></div>
   </div>
   <fieldset formGroupName="user">
     <input type="text" formControlName="firstname">
     <input type="text" formControlName="lastname">
   </fieldset>
</form>

I adhere to the logic that there is no need to push the displayed component into a large logic, for conditions it is ideal to check the value true \ false


问:
Unloading data from Amazon redshift to Amazon s3
I am trying to use the following code to unload data into S3 bucket. Which works but after unloading it throws some error.

```<code> Properties props = new Properties();
 props.setProperty("user", MasterUsername);
 props.setProperty("password", MasterUserPassword);
 conn = DriverManager.getConnection(dbURL, props);
 stmt = conn.createStatement();
 String sql;
 sql = "unload('select * from part where p_partkey in (select p_partkey from
       part limit 10)') to"
       + " 's3://redshiftdump.****' "
       + " DELIMITER AS ','"
       + "ADDQUOTES "
       + "NULL AS ''"
       + "credentials 'aws_access_key_id=****;aws_secret_access_key=***' "
       + "parallel off" +
       ";";
 boolean i = stmt.execute(sql);
 stmt.close();
 conn.close();
</code>```

The unloading works. It is creating a file in the bucket. But it is giving me some error

```<code>   java.sql.SQLException:
      dataengine.impl.DSISimpleRowCountResult cannot be cast to
      com.amazon.dsi.dataengine.interfaces.IResultSet
   at
   com.amazon.redshift.core.jdbc42.PGJDBC42Statement.createResultSet(Unknown
   Source)
   at com.amazon.jdbc.common.SStatement.executeQuery(Unknown Source)
</code>```

what is this error and how to avoid it? Is there any way to dump the table in CSV format. Right now it is dumping the file in FILE format.

答:
```<code>use executeUpdate .

  def runQuery(sql: String)  = {
    Class.forName("com.amazon.redshift.jdbc.Driver")
    val connection = DriverManager.getConnection(url, username, password)
    var statement: Statement = null
    try {
      statement = connection.createStatement()
      statement.setQueryTimeout(redshiftTimeoutInSeconds)
      val result = statement.executeUpdate(sql)
      logger.info(s"statement response code : ${result}")
    } catch {
      case e: Exception => {
        logger.error(s"statement.isCloseOnCompletion :${e.getMessage} ::: ${e.printStackTrace()}")
        throw new IngestionException(e.getMessage)
      }
    }
    finally {
      if(statement != null ) statement.close()
      connection.close()
    }
  }
</code>```

Body:
I am trying to use the following code to unload data into S3 bucket. Which works but after unloading it throws some error.

 Properties props = new Properties();
 props.setProperty("user", MasterUsername);
 props.setProperty("password", MasterUserPassword);
 conn = DriverManager.getConnection(dbURL, props);
 stmt = conn.createStatement();
 String sql;
 sql = "unload('select * from part where p_partkey in (select p_partkey from
       part limit 10)') to"
       + " 's3://redshiftdump.****' "
       + " DELIMITER AS ','"
       + "ADDQUOTES "
       + "NULL AS ''"
       + "credentials 'aws_access_key_id=****;aws_secret_access_key=***' "
       + "parallel off" +
       ";";
 boolean i = stmt.execute(sql);
 stmt.close();
 conn.close();

The unloading works. It is creating a file in the bucket. But it is giving me some error

   java.sql.SQLException:
      dataengine.impl.DSISimpleRowCountResult cannot be cast to
      com.amazon.dsi.dataengine.interfaces.IResultSet
   at
   com.amazon.redshift.core.jdbc42.PGJDBC42Statement.createResultSet(Unknown
   Source)
   at com.amazon.jdbc.common.SStatement.executeQuery(Unknown Source)

what is this error and how to avoid it? Is there any way to dump the table in CSV format. Right now it is dumping the file in FILE format.


问:
Why would adding a delay improve data throughput in this multithreaded environment?
In my application, I have two threads, a producer (thread 1) and a consumer (thread 2). Each thread has an input and output interface (effectively a pointer to a list) that is connected to a third thread which serves as a router.

When the producer writes, it calls memcpy to copy data into a buffer and pushes the buffer into a list. Meanwhile, the router thread is round-robin searching through all the threads that are connected to it and monitoring their interfaces to see if any thread has data to send out. When it sees that thread 1's list is non-empty, it checks to determine which thread the data is intended for. The data is spliced into the destination thread's (in this case thread 2) input list, at which point thread 2 will malloc some memory, memcpy the data into it and return the pointer to this new region.

For my test, I'm measuring throughput to see how long it takes to send 100k messages of varying sizes. Thread 1 sends data of some size, thread 2 reads it and sends back a small reply message, which thread 1 reads. This would be one complete exchange. In the first test, in thread 1, I'm sending all 100k messages, and then reading 100k replies. In the second test, in thread 1, I'm alternating sending a message and waiting for the reply and repeating 100k times. In both tests, thread 2 is in a loop reading the message and sending a reply. I would expect test 1 to have higher throughput because the threads should spend less time waiting around. However, it has markedly worse throughput than test 2. I've measured how long individual function calls (to read/write) take in the two test cases and they invariably take longer in test 1 (based on the means and medians and no delay) though the numbers are of the same order of magnitude.

When I add a loop doing nothing into thread 1's sending loop in test 1, I see dramatically improved throughput for this case as opposed to not having the delay. My only guess is that adding a delay slows down the producer so the consumer can absorb the data which prevents its input list from growing very large. I'm wondering if there may be other explanations and if so, how I can test for them.

Edit

Unfortunately, my own code is just the test I described above which calls a library that actually performs the reads/writes, creates that third thread etc. It's difficult to make a minimal example out of it because the library is complex and not mine. I provide some pseudocode to illustrate the setup in more detail.

int NUM_ITERATIONS = 100000;
int msg_reply = 2; // size of the reply message in words
int msg_size = 512; // indicates 512 64 bit words

void generate(int iterations, int size, interface* out){
    std::vector<long long> vec(size);
    for(int i = 0; i < size; i++)
        vec[i] = (long long) i;

    for(int i = 0; i < iterations; i++)
        out->lib_write((char*) vec.data(), size);
}

void receive(int iterations, int size, interface* in){
    for(int i = 0; i < iterations; i++)
        char* data = in->lib_read(size)

void producer(interface* in, interface* out){
    // test 1
    start = std::chrono::high_resolution_clock::now();
    // write data of size msg_size, NUM_ITERATIONS times to out
    generate(NUM_ITERATIONS, msg_size, out);
    // read data of size msg_reply, NUM_ITERATIONS times from in
    receive(NUM_ITERATIONS, msg_reply, in);
    end = std::chrono::high_resolution_clock::now();
    // using NUM_ITERATIONS, msg_size and time, compute and print throughput to stdout
    print_throughput(end-start, "throughput_0", msg_size);

    // test 2
    start = std::chrono::high_resolution_clock::now();
    for(int j = 0; j < NUM_ITERATIONS; j++){
        generate(1, msg_size, out);
        receive(1, msg_reply, in);
    }
    end = std::chrono::high_resolution_clock::now();
    print_throughput(end-start, "throughput_1", msg_size);
}

void consumer(interface* in, interface* out){
    for(int i = 0; i < 2; i++}{
        for(int j = 0; j < NUM_ITERATIONS; j++){
            receive(1, msg_size, in);
            generate(1, msg_reply, out);
        }
    }
}
```

<p>The calls to <code>lib_write()</code> and <code>lib_read()</code> become fairly complex. To elaborate on the description above, the data gets memcpy'd into a buffer and then moved into a list. The interface has a condition variable member and the write calls its <code>notify_one()</code> method. The third thread is looping through all the interface pointers it has and checking to see if their lists are non-empty. If so, the data is spliced from one output list to the destination's input list using the <code>splice()</code> method in std::list. Meanwhile, the consumer calls the <code>lib_read()</code> which waits on the condition variable while the interface is empty, and then memcpy's the data into a new region and returns it.</p>

<pre class="lang-cpp prettyprint-override"><code>// note: these will not compile as is. Undefined variables are class members

char * interface::lib_read(size_t * _size){

    char * ret;
    {
        std::unique_lock<std::mutex> lock(mutex);
        // packets is an std::list containing the incoming data
        while (packets.empty()) {
            cv.wait(lock);
        }
        curr_read_it = packets.begin();
    }

    size_t buff_size = curr_read_it->size;

    ret = (char *)malloc(buff_size);
    memcpy((char *)ret, (char *)curr_read_it->data, buff_size);
    {
        std::unique_lock<std::mutex> lock(mutex);
        packets.erase(curr_read_it);
        curr_read_it = packets.end();
    }
    return ret;
}

void interface::lib_write(char * data, int size){
    // indicates the destination thread id
    long long header = 1;

    // buffer is a just an array that's max packet sized
    memcpy((char *)buffer.data, &header, sizeof(long long));
    memcpy((char *)buffer.data + sizeof(long long), (char *)data, size * sizeof(long long));

    std::lock_guard<std::mutex> guard(mutex);
    packets.push_back(std::move(buffer));
    cv.notify_one();
}

// this is on thread 3
void route(){
    do{
        // this is a vector containing all the "out" interfaces
        for(int i = 0; i < out_ptrs.size(); i++){
            interface <long long> * _out = out_ptrs[i];
            if(!_out->empty()){
                // this just returns the header id (also locks the mutex)
                long long dest= _out->get_dest();
                // looks up the correct interface based on the id and splices
                // a packet into from _out to the appropriate one. Locks mutex
                in_ptrs[dest_map[dest]]->splice(_out);
            }
        }

    }while(!done());
</code>```

答:
I was looking for general advice on what factors may influence multithreading performance and what to test for in order to better understand what was going on.

I talked to some other people and the advice I got that was helpful was to determine if the OS scheduling was the issue (which is what I suspected but was unsure how to test). Essentially, I used taskset and sched_affinity() to force the application to run on one core or on a subset of cores and looked at how they compared to each other and to the unrestricted case.

Based on the restrictions, I got dramatically different results and could see some trends so I'm pretty confident in saying that it's an OS scheduling issue. Different ones can yield better performance under different workloads.

Body:
In my application, I have two threads, a producer (thread 1) and a consumer (thread 2). Each thread has an input and output interface (effectively a pointer to a list) that is connected to a third thread which serves as a router.

When the producer writes, it calls memcpy to copy data into a buffer and pushes the buffer into a list. Meanwhile, the router thread is round-robin searching through all the threads that are connected to it and monitoring their interfaces to see if any thread has data to send out. When it sees that thread 1's list is non-empty, it checks to determine which thread the data is intended for. The data is spliced into the destination thread's (in this case thread 2) input list, at which point thread 2 will malloc some memory, memcpy the data into it and return the pointer to this new region.

For my test, I'm measuring throughput to see how long it takes to send 100k messages of varying sizes. Thread 1 sends data of some size, thread 2 reads it and sends back a small reply message, which thread 1 reads. This would be one complete exchange. In the first test, in thread 1, I'm sending all 100k messages, and then reading 100k replies. In the second test, in thread 1, I'm alternating sending a message and waiting for the reply and repeating 100k times. In both tests, thread 2 is in a loop reading the message and sending a reply. I would expect test 1 to have higher throughput because the threads should spend less time waiting around. However, it has markedly worse throughput than test 2. I've measured how long individual function calls (to read/write) take in the two test cases and they invariably take longer in test 1 (based on the means and medians and no delay) though the numbers are of the same order of magnitude.

When I add a loop doing nothing into thread 1's sending loop in test 1, I see dramatically improved throughput for this case as opposed to not having the delay. My only guess is that adding a delay slows down the producer so the consumer can absorb the data which prevents its input list from growing very large. I'm wondering if there may be other explanations and if so, how I can test for them.

Edit

Unfortunately, my own code is just the test I described above which calls a library that actually performs the reads/writes, creates that third thread etc. It's difficult to make a minimal example out of it because the library is complex and not mine. I provide some pseudocode to illustrate the setup in more detail.

int NUM_ITERATIONS = 100000;
int msg_reply = 2; // size of the reply message in words
int msg_size = 512; // indicates 512 64 bit words

void generate(int iterations, int size, interface* out){
    std::vector<long long> vec(size);
    for(int i = 0; i < size; i++)
        vec[i] = (long long) i;

    for(int i = 0; i < iterations; i++)
        out->lib_write((char*) vec.data(), size);
}

void receive(int iterations, int size, interface* in){
    for(int i = 0; i < iterations; i++)
        char* data = in->lib_read(size)

void producer(interface* in, interface* out){
    // test 1
    start = std::chrono::high_resolution_clock::now();
    // write data of size msg_size, NUM_ITERATIONS times to out
    generate(NUM_ITERATIONS, msg_size, out);
    // read data of size msg_reply, NUM_ITERATIONS times from in
    receive(NUM_ITERATIONS, msg_reply, in);
    end = std::chrono::high_resolution_clock::now();
    // using NUM_ITERATIONS, msg_size and time, compute and print throughput to stdout
    print_throughput(end-start, "throughput_0", msg_size);

    // test 2
    start = std::chrono::high_resolution_clock::now();
    for(int j = 0; j < NUM_ITERATIONS; j++){
        generate(1, msg_size, out);
        receive(1, msg_reply, in);
    }
    end = std::chrono::high_resolution_clock::now();
    print_throughput(end-start, "throughput_1", msg_size);
}

void consumer(interface* in, interface* out){
    for(int i = 0; i < 2; i++}{
        for(int j = 0; j < NUM_ITERATIONS; j++){
            receive(1, msg_size, in);
            generate(1, msg_reply, out);
        }
    }
}

The calls to lib_write() and lib_read() become fairly complex. To elaborate on the description above, the data gets memcpy'd into a buffer and then moved into a list. The interface has a condition variable member and the write calls its notify_one() method. The third thread is looping through all the interface pointers it has and checking to see if their lists are non-empty. If so, the data is spliced from one output list to the destination's input list using the splice() method in std::list. Meanwhile, the consumer calls the lib_read() which waits on the condition variable while the interface is empty, and then memcpy's the data into a new region and returns it.

// note: these will not compile as is. Undefined variables are class members

char * interface::lib_read(size_t * _size){

    char * ret;
    {
        std::unique_lock<std::mutex> lock(mutex);
        // packets is an std::list containing the incoming data
        while (packets.empty()) {
            cv.wait(lock);
        }
        curr_read_it = packets.begin();
    }

    size_t buff_size = curr_read_it->size;

    ret = (char *)malloc(buff_size);
    memcpy((char *)ret, (char *)curr_read_it->data, buff_size);
    {
        std::unique_lock<std::mutex> lock(mutex);
        packets.erase(curr_read_it);
        curr_read_it = packets.end();
    }
    return ret;
}

void interface::lib_write(char * data, int size){
    // indicates the destination thread id
    long long header = 1;

    // buffer is a just an array that's max packet sized
    memcpy((char *)buffer.data, &header, sizeof(long long));
    memcpy((char *)buffer.data + sizeof(long long), (char *)data, size * sizeof(long long));

    std::lock_guard<std::mutex> guard(mutex);
    packets.push_back(std::move(buffer));
    cv.notify_one();
}

// this is on thread 3
void route(){
    do{
        // this is a vector containing all the "out" interfaces
        for(int i = 0; i < out_ptrs.size(); i++){
            interface <long long> * _out = out_ptrs[i];
            if(!_out->empty()){
                // this just returns the header id (also locks the mutex)
                long long dest= _out->get_dest();
                // looks up the correct interface based on the id and splices
                // a packet into from _out to the appropriate one. Locks mutex
                in_ptrs[dest_map[dest]]->splice(_out);
            }
        }

    }while(!done());


问:
Trouble running eclipse on Fedora 9, KDE 4.2 (Runs fine in Gnome)
I recently installed KDE4.2 on my Fedora 9 machine, which already had Gnome, and have been trying to run Eclipse 3.3 (Europa, which ships with a Fedora Distro), but without luck. Eclipse runs fine when I use gnome session, however I need to use it in KDE.

I am attaching the screen-shot taken after the crash and some information about my machine:

uname -a yields:

Linux localhost.localdomain
  2.6.25-14.fc9.i686 #1 SMP Thu May 1 06:28:41 EDT 2008 i686 i686 i386
  GNU/Linux

I have a Intel Core 2 Duo processor. Also I have a host of JREs & JDKs ( JRE, JDK 5 and 6, JRE 4). JDK6 s the one in use.

I have a feeling that its something to do with gtk and qt. Since KDE runs on qt, I may need some plug-in. But couldn't find much upon searching the internet.

Some pointers would really help! Also, let me know if you need more information about the machine or eclipse

EDIT: Added the screenshot.

答:
I had also bad experiences with the packaged Eclipse from the distributors. They often patch Eclipse to have the plugins in the system and leave only the application in the users home. This gave me often problems with plugins because of the missing rights.
Better to get a original Eclipse and place it in your home.

Mmh, you have the newest JRE installed (Sun JRE 6) so I cannot see a problem here. But you could remove the JRE package completely and reinstall it.

OwnerDisplayName: Swanand

LastEditorDisplayName: Swanand

OwnerDisplayName: devarni

ContentLicense: CC BY-SA 2.5


问:
Lambda or LINQ to Sort List<Employee> by Shift, C#
I have a List of Employee that I need to filter, and I'd like to see how to do this using a lambda and/or LINQ expression.

I want to return ALL of the Employees in the List, but I want them returned in order of Shift, Lastname, and Firstname.

```<code>List<Employee> empList = GetEmployeesInOtherCode();
// ...
int MAX_SHIFT = 5;
List<string> sortedNames = new List<string>(empList.Count);
for (int i = 0; i < MAX_SHIFT; i++) {
  List<string> localShift = new List<string>();
  for (int j = 0; j < empList.Count; j++) {
    Employee e = empList[j];
    if (e.Shift == i) {
      localShift.Add(string.Format("{0}, {1}", e.Lastname, e.Firstname));
    }
  }
  localShift.Sort();
  sortedNames.AddRange(localShift.ToArray());
}
foreach (string line in sortedNames) {
  Console.WriteLine(line);
}
</code>```

EDIT: Jeez you guys are fast! What do you use to generate this stuff? Are you hand coding it, or is there a tool out there that helps?

答:
For this I like query expression syntax better:</p>

```<code>List<string> sortedNames = (from e in empList
                            orderby e.Shift, e.LastName, e.FirstName
                            select string.Format("{0}, {1}",
                                                  e.Lastname,
                                                  e.Firstname)).ToList();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a List of Employee that I need to filter, and I'd like to see how to do this using a lambda and/or LINQ expression.

I want to return ALL of the Employees in the List, but I want them returned in order of Shift, Lastname, and Firstname.

List<Employee> empList = GetEmployeesInOtherCode();
// ...
int MAX_SHIFT = 5;
List<string> sortedNames = new List<string>(empList.Count);
for (int i = 0; i < MAX_SHIFT; i++) {
  List<string> localShift = new List<string>();
  for (int j = 0; j < empList.Count; j++) {
    Employee e = empList[j];
    if (e.Shift == i) {
      localShift.Add(string.Format("{0}, {1}", e.Lastname, e.Firstname));
    }
  }
  localShift.Sort();
  sortedNames.AddRange(localShift.ToArray());
}
foreach (string line in sortedNames) {
  Console.WriteLine(line);
}

EDIT: Jeez you guys are fast! What do you use to generate this stuff? Are you hand coding it, or is there a tool out there that helps?

Body:
For this I like query expression syntax better:

List<string> sortedNames = (from e in empList
                            orderby e.Shift, e.LastName, e.FirstName
                            select string.Format("{0}, {1}",
                                                  e.Lastname,
                                                  e.Firstname)).ToList();


问:
segfault when trying to itterate through features after Deleting fields ogr layers
I am deleting a bunch of fields from layers in a dataset.

But I find once I have deleted some fields I get a segfault if i try to iterate through the features after the fields are deleted

```<code># If I comment out this for loop that deletes fields everything is fine
    for layer in ds:
        layer_fields = _get_layer_fields(layer)
        for field in layer_fields:
            if field in list_of_fields_to_delete:
                layer.DeleteField(layer.FindFieldIndex(field, True))

# This prints successfully showing the fields have been deleted
    for layer in ds:
        print(layer.GetFeatureCount())
        print(_get_layer_fields(layer))

# but if I do delete feilds it will segfault when I try to iterate over features
    for layer in ds:
        for feature in layer:
            pass

# Here's the function were calling for list of fields
def _get_layer_fields(layer):
    layerDefinition = layer.GetLayerDefn()

    layer_fields = []

    if layerDefinition.GetFieldCount():
        for i in range(layerDefinition.GetFieldCount()):
            layer_fields.append(layerDefinition.GetFieldDefn(i).GetName())
</code>```

I can GetFeatureCount, GetFieldCount all that good stuff but I cannot iterate over the features once I have deleted fields, I get an error

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

Can anyone help me understand why I lose the ability to iterate after deleting fields?

答:
Seems I cannot delete feilds once a layer has features, to get round this I removed the attributes earlier when copying layers into the mem dataset, I adapted the code below for my purposes.

much more code, would of been nice to just copy layer, delete a few fields

```<code>def main( field_name_target ):
    # Get the input Layer
    inShapefile = "~/DATA/SHAPES/KC_ADMIN/parcel_address/parcel_address.shp"
    inDriver = ogr.GetDriverByName("ESRI Shapefile")
    inDataSource = inDriver.Open(inShapefile, 0)
    inLayer = inDataSource.GetLayer()
    inLayer.SetAttributeFilter("minor = 'HYDR'")

    # Create the output LayerS
    outShapefile = os.path.join( os.path.split( inShapefile )[0], "ogr_api_filter.shp" )
    outDriver = ogr.GetDriverByName("ESRI Shapefile")

    # Remove output shapefile if it already exists
    if os.path.exists(outShapefile):
        outDriver.DeleteDataSource(outShapefile)

    # Create the output shapefile
    outDataSource = outDriver.CreateDataSource(outShapefile)
    out_lyr_name = os.path.splitext( os.path.split( outShapefile )[1] )[0]
    outLayer = outDataSource.CreateLayer( out_lyr_name, geom_type=ogr.wkbMultiPolygon )

    # Add input Layer Fields to the output Layer if it is the one we want
    inLayerDefn = inLayer.GetLayerDefn()
    for i in range(0, inLayerDefn.GetFieldCount()):
        fieldDefn = inLayerDefn.GetFieldDefn(i)
        fieldName = fieldDefn.GetName()
        if fieldName not in field_name_target:
            continue
        outLayer.CreateField(fieldDefn)

    # Get the output Layer's Feature Definition
    outLayerDefn = outLayer.GetLayerDefn()

    # Add features to the ouput Layer
    for inFeature in inLayer:
        # Create output Feature
        outFeature = ogr.Feature(outLayerDefn)

        # Add field values from input Layer
        for i in range(0, outLayerDefn.GetFieldCount()):
            fieldDefn = outLayerDefn.GetFieldDefn(i)
            fieldName = fieldDefn.GetName()
            if fieldName not in field_name_target:
                continue

            outFeature.SetField(outLayerDefn.GetFieldDefn(i).GetNameRef(),
                inFeature.GetField(i))

        # Set geometry as centroid
        geom = inFeature.GetGeometryRef()
        outFeature.SetGeometry(geom.Clone())
        # Add new feature to output Layer
        outLayer.CreateFeature(outFeature)
        outFeature = None

    # Save and close DataSources
    inDataSource = None
    outDataSource = None
</code>```

Body:
I am deleting a bunch of fields from layers in a dataset.

But I find once I have deleted some fields I get a segfault if i try to iterate through the features after the fields are deleted

# If I comment out this for loop that deletes fields everything is fine
    for layer in ds:
        layer_fields = _get_layer_fields(layer)
        for field in layer_fields:
            if field in list_of_fields_to_delete:
                layer.DeleteField(layer.FindFieldIndex(field, True))

# This prints successfully showing the fields have been deleted
    for layer in ds:
        print(layer.GetFeatureCount())
        print(_get_layer_fields(layer))

# but if I do delete feilds it will segfault when I try to iterate over features
    for layer in ds:
        for feature in layer:
            pass

# Here's the function were calling for list of fields
def _get_layer_fields(layer):
    layerDefinition = layer.GetLayerDefn()

    layer_fields = []

    if layerDefinition.GetFieldCount():
        for i in range(layerDefinition.GetFieldCount()):
            layer_fields.append(layerDefinition.GetFieldDefn(i).GetName())

I can GetFeatureCount, GetFieldCount all that good stuff but I cannot iterate over the features once I have deleted fields, I get an error

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

Can anyone help me understand why I lose the ability to iterate after deleting fields?

Body:
Seems I cannot delete feilds once a layer has features, to get round this I removed the attributes earlier when copying layers into the mem dataset, I adapted the code below for my purposes.

much more code, would of been nice to just copy layer, delete a few fields

def main( field_name_target ):
    # Get the input Layer
    inShapefile = "~/DATA/SHAPES/KC_ADMIN/parcel_address/parcel_address.shp"
    inDriver = ogr.GetDriverByName("ESRI Shapefile")
    inDataSource = inDriver.Open(inShapefile, 0)
    inLayer = inDataSource.GetLayer()
    inLayer.SetAttributeFilter("minor = 'HYDR'")

    # Create the output LayerS
    outShapefile = os.path.join( os.path.split( inShapefile )[0], "ogr_api_filter.shp" )
    outDriver = ogr.GetDriverByName("ESRI Shapefile")

    # Remove output shapefile if it already exists
    if os.path.exists(outShapefile):
        outDriver.DeleteDataSource(outShapefile)

    # Create the output shapefile
    outDataSource = outDriver.CreateDataSource(outShapefile)
    out_lyr_name = os.path.splitext( os.path.split( outShapefile )[1] )[0]
    outLayer = outDataSource.CreateLayer( out_lyr_name, geom_type=ogr.wkbMultiPolygon )

    # Add input Layer Fields to the output Layer if it is the one we want
    inLayerDefn = inLayer.GetLayerDefn()
    for i in range(0, inLayerDefn.GetFieldCount()):
        fieldDefn = inLayerDefn.GetFieldDefn(i)
        fieldName = fieldDefn.GetName()
        if fieldName not in field_name_target:
            continue
        outLayer.CreateField(fieldDefn)

    # Get the output Layer's Feature Definition
    outLayerDefn = outLayer.GetLayerDefn()

    # Add features to the ouput Layer
    for inFeature in inLayer:
        # Create output Feature
        outFeature = ogr.Feature(outLayerDefn)

        # Add field values from input Layer
        for i in range(0, outLayerDefn.GetFieldCount()):
            fieldDefn = outLayerDefn.GetFieldDefn(i)
            fieldName = fieldDefn.GetName()
            if fieldName not in field_name_target:
                continue

            outFeature.SetField(outLayerDefn.GetFieldDefn(i).GetNameRef(),
                inFeature.GetField(i))

        # Set geometry as centroid
        geom = inFeature.GetGeometryRef()
        outFeature.SetGeometry(geom.Clone())
        # Add new feature to output Layer
        outLayer.CreateFeature(outFeature)
        outFeature = None

    # Save and close DataSources
    inDataSource = None
    outDataSource = None


问:
Selenium : The browser is getting opened but not able to get URL in the browser
OS:Windows 10

Execution Environment : JavaSE-1.8 (jre1.8.0_144)

JARs and class folders on build path:
client-combined-3.6.0-sources.jar
client-combined3.6.0.jar
selenium-server-standalone-3.6.0.jar

Browser:
FireFox 56.0

Code Snippet:
System.setProperty("webdriver.firefox.marionette","C:/Users/admin/Downloads/geckodriver-v0.11.1-win32/geckodriver.exe");
WebDriver driver = new FirefoxDriver ();
driver.get("https://www.facebook.com");

Error:

```<code>    Exception in thread "main" org.openqa.selenium.WebDriverException: Timed out waiting 45 seconds for Firefox to start.
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:26.402Z'
System info: host: 'ADMIN-PC', ip: '192.168.1.6', os.name: 'Windows 10', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_144'
Driver info: driver.version: FirefoxDriver
at org.openqa.selenium.firefox.XpiDriverService.waitUntilAvailable(XpiDriverService.java:112)
at org.openqa.selenium.firefox.XpiDriverService.start(XpiDriverService.java:97)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:217)
at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:140)
at org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:120)
at org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:98)
at FacebookFriends.main(FacebookFriends.java:18)
Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:45149/hub/status] to be available after 45005 ms
at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:100)
at org.openqa.selenium.firefox.XpiDriverService.waitUntilAvailable(XpiDriverService.java:110)
... 8 more
Caused by: java.util.concurrent.TimeoutException
at java.util.concurrent.FutureTask.get(Unknown Source)
at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:147)
at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:75)
... 9 more
</code>```

答:
I haved this error for 2 days, the solution for me was in Set.Plataform put Platafor.ANY or Plataform.Windows because Plataform.WIN10 not worked, marionette wasn't necessary and I added and neether works, only works this. I hope this helps someone else:

public class Main {
    public static RemoteWebDriver driver;

```<code>public static void main(String[] args) throws MalformedURLException {
    System.setProperty("webdriver.gecko.driver", "D:/Lib/geckodriver.exe");
    DesiredCapabilities desiredCapabilities = new DesiredCapabilities().firefox();
    desiredCapabilities.setPlatform(Platform.ANY);
    desiredCapabilities.setBrowserName("firefox");

    driver = new RemoteWebDriver(new URL("http://172.20.19.182:5557/wd/hub"), desiredCapabilities);
    driver.navigate().to("http://www.google.com");
    driver.findElementByName("q").sendKeys("execute automation");
    driver.findElementByName("q").sendKeys(Keys.ENTER);
    driver.close();
    // write your code here
}
</code>```

}

Body:
OS:Windows 10

Execution Environment : JavaSE-1.8 (jre1.8.0_144)

JARs and class folders on build path:
client-combined-3.6.0-sources.jar
client-combined3.6.0.jar
selenium-server-standalone-3.6.0.jar

Browser:
FireFox 56.0

Code Snippet:
System.setProperty("webdriver.firefox.marionette","C:/Users/admin/Downloads/geckodriver-v0.11.1-win32/geckodriver.exe");
WebDriver driver = new FirefoxDriver ();
driver.get("https://www.facebook.com");

Error:

    Exception in thread "main" org.openqa.selenium.WebDriverException: Timed out waiting 45 seconds for Firefox to start.
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:26.402Z'
System info: host: 'ADMIN-PC', ip: '192.168.1.6', os.name: 'Windows 10', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_144'
Driver info: driver.version: FirefoxDriver
at org.openqa.selenium.firefox.XpiDriverService.waitUntilAvailable(XpiDriverService.java:112)
at org.openqa.selenium.firefox.XpiDriverService.start(XpiDriverService.java:97)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:217)
at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:140)
at org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:120)
at org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:98)
at FacebookFriends.main(FacebookFriends.java:18)
Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:45149/hub/status] to be available after 45005 ms
at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:100)
at org.openqa.selenium.firefox.XpiDriverService.waitUntilAvailable(XpiDriverService.java:110)
... 8 more
Caused by: java.util.concurrent.TimeoutException
at java.util.concurrent.FutureTask.get(Unknown Source)
at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:147)
at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:75)
... 9 more

Body:
I haved this error for 2 days, the solution for me was in Set.Plataform put Platafor.ANY or Plataform.Windows because Plataform.WIN10 not worked, marionette wasn't necessary and I added and neether works, only works this. I hope this helps someone else:

public class Main {
    public static RemoteWebDriver driver;

public static void main(String[] args) throws MalformedURLException {
    System.setProperty("webdriver.gecko.driver", "D:/Lib/geckodriver.exe");
    DesiredCapabilities desiredCapabilities = new DesiredCapabilities().firefox();
    desiredCapabilities.setPlatform(Platform.ANY);
    desiredCapabilities.setBrowserName("firefox");

    driver = new RemoteWebDriver(new URL("http://172.20.19.182:5557/wd/hub"), desiredCapabilities);
    driver.navigate().to("http://www.google.com");
    driver.findElementByName("q").sendKeys("execute automation");
    driver.findElementByName("q").sendKeys(Keys.ENTER);
    driver.close();
    // write your code here
}

}


问:
chartjs-plugin-annotation won't draw anything
I have a chartjs line chart setup and I'm trying to draw a horizontal annotation line across the chart at a fixed value.  But nothing happens and no errors in console.

I've included the chartjs-plugin-annotation.js such as this:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.min.js"></script>
</code>```

Then added this into the options: (which should add a 2px thick line across the chart as value "25"):

```<code>            annotation: {
                drawTime: 'afterDraw',
                annotations: [{
                    type: 'line',
                    id: 'line',
                    mode: 'horizontal',
                    scaleID: 'y-axis-0',
                    value: 25,
                    borderWidth: 2,
                    borderColor: 'black'
                }]
            },
</code>```

Full code for the chart is here:

```<code>    var temperaturechart = new Chart($('#temperaturechart'), {
        type: 'line',
        data: {
            datasets: [{
                label: 'Temperature',
                backgroundColor: 'rgba(252, 132, 3, 0.1)',
                borderColor: 'rgba(252, 132, 3, 1)',
                data: [{"x":"2020-05-21 14:00:00","y":27.28},{"x":"2020-05-21 16:00:00","y":28.64},{"x":"2020-05-21 18:00:00","y":29.83},{"x":"2020-05-21 20:00:00","y":20.24},{"x":"2020-05-21 22:00:00","y":21.63},{"x":"2020-05-22 00:00:00","y":30.34},{"x":"2020-05-22 02:00:00","y":19.01},{"x":"2020-05-22 04:00:00","y":18.88}],
            }]
        },
        options: {
            annotation: {
                drawTime: 'afterDraw',
                annotations: [{
                    type: 'line',
                    id: 'line',
                    mode: 'horizontal',
                    scaleID: 'y-axis-0',
                    value: 25,
                    borderWidth: 2,
                    borderColor: 'black'
                }]
            },
            aspectRatio: 2.5,
            legend: {
                display: false
            },
            scales: {
                xAxes: [{
                    type: 'time',
                    time: {
                        unit: 'day',
                        unitStepSize: 1,
                        displayFormats: {
                            'day': 'MMM DD'
                        }
                    },
                    scaleLabel: {
                        display: false,
                        labelString: 'Date'
                    },
                    gridLines: {
                        tickMarkLength: 8,
                        zeroLineColor: 'rgba(0, 0, 0, 0.1)'
                    },
                    ticks: {
                        maxRotation: 90,
                        minRotation: 45,
                        padding: 10
                    }
                }],
                yAxes: [{
                    scaleLabel: {
                        display: true,
                        labelString: 'Temperature'
                    }
                }]
            },

        }
    });
</code>```

答:
I had made a dumb mistake of including both Chart.min.js and then later on Chart.bundle.min.js also.

So something like this:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.min.js"></script>

...other code...

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
</code>```

Deleting this later Chart.bundle.min.js solved the problem.

Body:
I have a chartjs line chart setup and I'm trying to draw a horizontal annotation line across the chart at a fixed value.  But nothing happens and no errors in console.

I've included the chartjs-plugin-annotation.js such as this:

Then added this into the options: (which should add a 2px thick line across the chart as value "25"):

            annotation: {
                drawTime: 'afterDraw',
                annotations: [{
                    type: 'line',
                    id: 'line',
                    mode: 'horizontal',
                    scaleID: 'y-axis-0',
                    value: 25,
                    borderWidth: 2,
                    borderColor: 'black'
                }]
            },

Full code for the chart is here:

    var temperaturechart = new Chart($('#temperaturechart'), {
        type: 'line',
        data: {
            datasets: [{
                label: 'Temperature',
                backgroundColor: 'rgba(252, 132, 3, 0.1)',
                borderColor: 'rgba(252, 132, 3, 1)',
                data: [{"x":"2020-05-21 14:00:00","y":27.28},{"x":"2020-05-21 16:00:00","y":28.64},{"x":"2020-05-21 18:00:00","y":29.83},{"x":"2020-05-21 20:00:00","y":20.24},{"x":"2020-05-21 22:00:00","y":21.63},{"x":"2020-05-22 00:00:00","y":30.34},{"x":"2020-05-22 02:00:00","y":19.01},{"x":"2020-05-22 04:00:00","y":18.88}],
            }]
        },
        options: {
            annotation: {
                drawTime: 'afterDraw',
                annotations: [{
                    type: 'line',
                    id: 'line',
                    mode: 'horizontal',
                    scaleID: 'y-axis-0',
                    value: 25,
                    borderWidth: 2,
                    borderColor: 'black'
                }]
            },
            aspectRatio: 2.5,
            legend: {
                display: false
            },
            scales: {
                xAxes: [{
                    type: 'time',
                    time: {
                        unit: 'day',
                        unitStepSize: 1,
                        displayFormats: {
                            'day': 'MMM DD'
                        }
                    },
                    scaleLabel: {
                        display: false,
                        labelString: 'Date'
                    },
                    gridLines: {
                        tickMarkLength: 8,
                        zeroLineColor: 'rgba(0, 0, 0, 0.1)'
                    },
                    ticks: {
                        maxRotation: 90,
                        minRotation: 45,
                        padding: 10
                    }
                }],
                yAxes: [{
                    scaleLabel: {
                        display: true,
                        labelString: 'Temperature'
                    }
                }]
            },

        }
    });

Body:
I had made a dumb mistake of including both Chart.min.js and then later on Chart.bundle.min.js also.

So something like this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.min.js"></script>

...other code...

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>

Deleting this later Chart.bundle.min.js solved the problem.


答:
Two steps first use filter

```<code>s=df.filter(like='Region')
</code>```

Title: pandas dataframe - does filtering / selecting cols by String preserve order?

Body:
I have a use case where I have say 10 cols out of which 5 start with the string 'Region'. I need to get a resulting dataframe which only contains those cols (starting with string 'Region'). Not only that, I need to make sure the order is preserved (e.g. if in original df, the col order is 'Region 1', 'Region 2', 'Region 3' -- this should be preserved and not result in 'Region 3', 'Region 2', 'Region 1' instead).

Would following the 'accepted answer' for this question preserve the order or is there some other method to achieve that?

stackoverflow - find-column-whose-name-contains-a-specific-string

Body:
Two steps first use filter

s=df.filter(like='Region')


问:
Determine if an array is decreasing-increasing O(log(n)) and find the "switch" value
I'm trying to determine whether an array is decreasing first then increasing.
Also I need to find out the value when the pattern changes from ascending to descending which would be the min value in the arrays

Let's say for example I have the following array:

[10, 10, 10, 10, 10, 10, 8, 8, 8, 6, 6, 6, 6, 6, 4, 3, 12, 13, 22, 31, 40, 59, 78]

and this one

[-1, 1, 2, 4, 8, 16, 32, 64]

Edit: for simplicity you can assume the values won't be repeated like the first example I showed you

I mainly want to write a program that takes O(logn) time.
I'm trying to use binary search and this is what I have come up with. The input to the function is a sorted list or an descending-ascending list. That can have repeated values as shown in the above examples

```<code>    def find_middle(ls):
        start = 0
        end = len(ls) - 1
        idx = -1
        while start < end:
            mid = start + (end - start) // 2
            middle = ls[mid]
            if ls[mid-1] <= middle and middle > ls[mid+1]):
                return middle
            elif ls[mid-1] < middle:
                start = mid
            else:
                end = mid
     return idx
</code>```

Sorry for the messy code, I have tinkered with it alot and at this point I've just given up on finding a solution.

If the array is JUST decreasing or increasing, I want the function to return -1.

Any help will be appreciated!

答:
In your example there is repetition. Without repetition this is easy. Check the values at three different indices. Calling these x, y, and z, we can see that the boundary can only be in of of the three intervals (x,y), (y,z), (z,x). So if we look at the ordering of these pairs, either 2 will be ascending and 1 descending or the reverse. The majority matches the array. Then, you can use binary search to find the boundary. This is O(log n)

With repetition this requires (in the worst case) linear time. A bad example is where you have an array where all but 2 elements are identical. In this case it is O(n) just to find the different elements. In general, with repetition the same algorithm applies but you have the added work of finding different elements.

Body:
I'm trying to determine whether an array is decreasing first then increasing.
Also I need to find out the value when the pattern changes from ascending to descending which would be the min value in the arrays

Let's say for example I have the following array:

[10, 10, 10, 10, 10, 10, 8, 8, 8, 6, 6, 6, 6, 6, 4, 3, 12, 13, 22, 31, 40, 59, 78]

and this one

[-1, 1, 2, 4, 8, 16, 32, 64]

Edit: for simplicity you can assume the values won't be repeated like the first example I showed you

I mainly want to write a program that takes O(logn) time.
I'm trying to use binary search and this is what I have come up with. The input to the function is a sorted list or an descending-ascending list. That can have repeated values as shown in the above examples

    def find_middle(ls):
        start = 0
        end = len(ls) - 1
        idx = -1
        while start < end:
            mid = start + (end - start) // 2
            middle = ls[mid]
            if ls[mid-1] <= middle and middle > ls[mid+1]):
                return middle
            elif ls[mid-1] < middle:
                start = mid
            else:
                end = mid
     return idx

Sorry for the messy code, I have tinkered with it alot and at this point I've just given up on finding a solution.

If the array is JUST decreasing or increasing, I want the function to return -1.

Any help will be appreciated!


问:
Web API dynamic parameters for filtering
I'm building an API using Web API where i return database tables as JSON.

This is my controller method:

```<code>public List<ExampleDataDTO> ExampleData(int offset = 0, int limit = 0)
{
    return DataAccessLayer.GetExampleData(offset, limit);
}
</code>```

DataAccess method:

```<code>public List<ExampleDataDTO> GetExampleData(int offset, int limit)
        {
            using (var db = new Context())
            {
                db.Configuration.ProxyCreationEnabled = false;
                var exampleQuery = db.example.AsEnumerable().Select(item =>
                 new ExampleDataDTO
                 {
                    //Selects
                 });

                if(offset == 0 && limit == 0)
                {
                    return exampleQuery .ToList();
                }
                else
                {
                    return exampleQuery .Skip(offset).Take(limit).ToList();
                }
            }
        }
</code>```

Now the ExampleDataDTO contains over 100 files, and i want to be able to filter data on any field with the API.

Is there any way to make dynamic query parameters? for example if i go to localhost/api/ExampleData?offset=0&limit=10&name=test1&size=test2 i want to get the keys and values for name and size to be able to include them in my LINQ code.

Is this doable?

EDIT:

I can get all the parameters as  IEnumerable<KeyValuePair<String, String>> queryString

Is there any way to use the Key in a lambda expression i were to loop through all the keyValuePairs? like Where(c = c.Key == Value),

```<code>foreach(var queryKeyValuePair in queryString)
{
    Something including Where(c => c.queryKeyValuePair.Key == queryKeyValuePair.Value)
}
</code>```

答:
I know it's a bit late for the answer on this question but wanted to share my response anyways.

I would like to suggest a different approach and that is to move the logic to DB. By doing it, your code will be more adaptable to changes and will require change only in one place, DB. After all, changes in query shouldn't require you to recompile the code. So here's an example how to implement this approach:

You should consider using a model for your controller action to collect parameters for your query. The benefit is that you just need to add more properties to model if down the road you decide to add more filters.

Model:

```<code>public class ExampleParams
{
    public int size { get; set; } = 40; // Could be any number
    public int page { get; set; } = 1; // you can apply offset here but this should be done on db, see below
    public string q { get; set; } = string.Empty;
}
</code>```

Controller:

```<code>public List<ExampleDataDTO> ExampleData([FromQuery] ExampleParams params)
{
    return DataAccessLayer.GetExampleData(params);
}
</code>```

This will allow you to have dynamic query params, for example:

localhost/api/ExampleData?q=someString will search by param q

localhost/api/ExampleData?q=someString&page=2 will show page 2 for search param q

localhost/api/ExampleData?q=someString&page=2&size=10 will show 10 items on page 2 for search param q

I am assuming  you are using MySQL, but if not, still concept will remain the same. Offset and Limit could be bad performers on the large amount of data overall and what you are trying to implement is some sort of pagination which you can tackle in 2 different ways.

First one would would great if you know your table won't grow extremely large, thus offset and limit could be applied easily and efficiently, through a property "page" in above model, and limit and offset will be dynamic and calculated on the go.

```<code>-- page and size is what you are passing via model
SET @page := IFNULL(`page`, 1);
SET @size := SELECT CASE WHEN IFNULL(`size`, 40) > 40 THEN 40 ELSE IFNULL(`size`, 40) END); -- 40 is some default max limit

SELECT * FROM elementTable LIMIT @size OFFSET ((@page - 1) * @size)
</code>```

Second one would be better option if you know your table grow very large over time in which case you would be implementing more efficient "timestamp_id". For more reference click here:

```<code>-- Given that T is the timestamp and I is the id contained in the token.
SELECT * FROM elementTable
WHERE (
  timestampColumn > T
  OR (timestampColumn = T AND idColumn > I)
)
AND timestampColumn < now()
ORDER BY timestampColumn asc, idColumn asc;
-- The ids in the idColumn must be unique (out-of-the-box for primary keys)
-- We need an index on both columns timestampColumn and idColumn
</code>```

Now when it comes to filtering by fields, you have few options but scaling would be better with dynamic SQL although tedious to write it. Dynamic SQL would create and cache a different plan for each permutation of the Query parameters, but at least each plan will be 'tailored' to the specific query (it doesn't matter whether it is a PROC or Adhoc SQL - as long as they are parameterized queries, they will be cached)

```<code>SET @SQL = 'SELECT * FROM elementTable WHERE 1 = 1'
IF (`optionalParam1` IS NOT NULL) then
    SET @SQL = CONCAT(@SQL , ' AND myColumn1 = \'', `optionalParam1`, '\' ' );
IF (`optionalParam2` IS NOT NULL) then
    SET @SQL = CONCAT(@SQL , ' AND myColumn2 = \'', `optionalParam1`, '\' ' );
</code>```

The awful 1 == 1 hack can also be avoided if you keep track of whether any predicates have yet been applied or not, and then conditionally apply the first AND only on the second and subsequent predicates. If there are no predicates at all, then WHERE disappears as well.

Hope this answer your question more completely.

Body:
I'm building an API using Web API where i return database tables as JSON.

This is my controller method:

public List<ExampleDataDTO> ExampleData(int offset = 0, int limit = 0)
{
    return DataAccessLayer.GetExampleData(offset, limit);
}

DataAccess method:

public List<ExampleDataDTO> GetExampleData(int offset, int limit)
        {
            using (var db = new Context())
            {
                db.Configuration.ProxyCreationEnabled = false;
                var exampleQuery = db.example.AsEnumerable().Select(item =>
                 new ExampleDataDTO
                 {
                    //Selects
                 });

                if(offset == 0 && limit == 0)
                {
                    return exampleQuery .ToList();
                }
                else
                {
                    return exampleQuery .Skip(offset).Take(limit).ToList();
                }
            }
        }

Now the ExampleDataDTO contains over 100 files, and i want to be able to filter data on any field with the API.

Is there any way to make dynamic query parameters? for example if i go to localhost/api/ExampleData?offset=0&limit=10&name=test1&size=test2 i want to get the keys and values for name and size to be able to include them in my LINQ code.

Is this doable?

EDIT:

I can get all the parameters as  IEnumerable<KeyValuePair<String, String>> queryString

Is there any way to use the Key in a lambda expression i were to loop through all the keyValuePairs? like Where(c = c.Key == Value),

foreach(var queryKeyValuePair in queryString)
{
    Something including Where(c => c.queryKeyValuePair.Key == queryKeyValuePair.Value)
}

Body:
I know it's a bit late for the answer on this question but wanted to share my response anyways.

I would like to suggest a different approach and that is to move the logic to DB. By doing it, your code will be more adaptable to changes and will require change only in one place, DB. After all, changes in query shouldn't require you to recompile the code. So here's an example how to implement this approach:

You should consider using a model for your controller action to collect parameters for your query. The benefit is that you just need to add more properties to model if down the road you decide to add more filters.

Model:

public class ExampleParams
{
    public int size { get; set; } = 40; // Could be any number
    public int page { get; set; } = 1; // you can apply offset here but this should be done on db, see below
    public string q { get; set; } = string.Empty;
}

Controller:

public List<ExampleDataDTO> ExampleData([FromQuery] ExampleParams params)
{
    return DataAccessLayer.GetExampleData(params);
}

This will allow you to have dynamic query params, for example:

localhost/api/ExampleData?q=someString will search by param q

localhost/api/ExampleData?q=someString&page=2 will show page 2 for search param q

localhost/api/ExampleData?q=someString&page=2&size=10 will show 10 items on page 2 for search param q

I am assuming  you are using MySQL, but if not, still concept will remain the same. Offset and Limit could be bad performers on the large amount of data overall and what you are trying to implement is some sort of pagination which you can tackle in 2 different ways.

First one would would great if you know your table won't grow extremely large, thus offset and limit could be applied easily and efficiently, through a property "page" in above model, and limit and offset will be dynamic and calculated on the go.

-- page and size is what you are passing via model
SET @page := IFNULL(`page`, 1);
SET @size := SELECT CASE WHEN IFNULL(`size`, 40) > 40 THEN 40 ELSE IFNULL(`size`, 40) END); -- 40 is some default max limit

SELECT * FROM elementTable LIMIT @size OFFSET ((@page - 1) * @size)

Second one would be better option if you know your table grow very large over time in which case you would be implementing more efficient "timestamp_id". For more reference click here:

-- Given that T is the timestamp and I is the id contained in the token.
SELECT * FROM elementTable
WHERE (
  timestampColumn > T
  OR (timestampColumn = T AND idColumn > I)
)
AND timestampColumn < now()
ORDER BY timestampColumn asc, idColumn asc;
-- The ids in the idColumn must be unique (out-of-the-box for primary keys)
-- We need an index on both columns timestampColumn and idColumn

Now when it comes to filtering by fields, you have few options but scaling would be better with dynamic SQL although tedious to write it. Dynamic SQL would create and cache a different plan for each permutation of the Query parameters, but at least each plan will be 'tailored' to the specific query (it doesn't matter whether it is a PROC or Adhoc SQL - as long as they are parameterized queries, they will be cached)

SET @SQL = 'SELECT * FROM elementTable WHERE 1 = 1'
IF (`optionalParam1` IS NOT NULL) then
    SET @SQL = CONCAT(@SQL , ' AND myColumn1 = \'', `optionalParam1`, '\' ' );
IF (`optionalParam2` IS NOT NULL) then
    SET @SQL = CONCAT(@SQL , ' AND myColumn2 = \'', `optionalParam1`, '\' ' );

The awful 1 == 1 hack can also be avoided if you keep track of whether any predicates have yet been applied or not, and then conditionally apply the first AND only on the second and subsequent predicates. If there are no predicates at all, then WHERE disappears as well.

Hope this answer your question more completely.


问:
Replacing strings with values from dictionary using random.sample
Suppose I'm creating a madLib and i want to replace each word from a string that has the word 'plural noun'. Basically, the user gets a prompt that states to input plural nouns and those inputs the go to a dictionary (pluralnoDict).

I've been using random.choice, and it's been working out, however, the repeats is obviously the issue. I tried random.sample, however, instead of choosing one word from a given sample, the code replaces the words with the whole sample.

Is there a way I can replace each string using random.sample from a dictionary list? For example:

Original: The 'plural noun' have 'plural noun' and 'plural noun'.
Expected: The 'birds' have 'wings' and 'feet'.

Below is the for loop i use to replace the plural noun strings.

```<code>for key in pluralnoDict:
        target_word = "({0})".format(key)
        while target_word in madString:
            madString = madString.replace(target_word, random.choice(pluralnoDict[key]), 1)
</code>```

答:
Have you looked into the random library? You can use it to get random indices and so, to the best of my understanding, a possible solution could look something like this:

import re
import random

list_of_words = ["dogs", "cats", "mice"]

mad_lib = "the quick brown plural noun jumped over the lazy plural noun"

while "plural noun" in mad_lib:
    random_index = random.randint(0, len(list_of_words))
    mad_lib = re.sub("plural noun", list_of_words[random_index], mad_lib, 1)
    del list_of_words[random_index]

print(mad_lib)
```

Body:
Suppose I'm creating a madLib and i want to replace each word from a string that has the word 'plural noun'. Basically, the user gets a prompt that states to input plural nouns and those inputs the go to a dictionary (pluralnoDict).

I've been using random.choice, and it's been working out, however, the repeats is obviously the issue. I tried random.sample, however, instead of choosing one word from a given sample, the code replaces the words with the whole sample.

Is there a way I can replace each string using random.sample from a dictionary list? For example:

Original: The 'plural noun' have 'plural noun' and 'plural noun'.
Expected: The 'birds' have 'wings' and 'feet'.

Below is the for loop i use to replace the plural noun strings.

for key in pluralnoDict:
        target_word = "({0})".format(key)
        while target_word in madString:
            madString = madString.replace(target_word, random.choice(pluralnoDict[key]), 1)


问:
Need a suggestion on error handling in partial views
I can't seem to find an answer to this. Basically, inside of a View, I got

```<code>@{
    Html.RenderAction("PartialViewAction", "SomeController");
}
</code>```

Let's say, this partial action throws an exception: DB connection is out, or whatever. How would I display the error to the user?

All articles/blogs that I see talk about error handling in (non-partial) Views and partials rendered on AJAX calls.  But this case is neither.

答:
I think each view should handle their exceptions, so your logic should be in the view, but if we keep in mind MVC rules, exception handling should be on controllers, because they are in charge of communicating with the model. So the question is how make them show in the final view. I don't know if this could be helpful, but I will try a workaround.

The idea is subscribe your exceptions during a request in a list for example, an elegant solution could be having this list in your Viewbag, and then in your global layout write them in the view for example

```<code><ul name="hiddenExceptions" class="hidden">
     <li>exception 1 message wrote in the layout</li>
     <li>exception 2</li>
</ul>
</code>```

You can have an script later that iterates through this list an take appropriate actions, show them in a box, show at the top of the page, etc.

Hope it helps

Body:
I can't seem to find an answer to this. Basically, inside of a View, I got

@{
    Html.RenderAction("PartialViewAction", "SomeController");
}

Let's say, this partial action throws an exception: DB connection is out, or whatever. How would I display the error to the user?

All articles/blogs that I see talk about error handling in (non-partial) Views and partials rendered on AJAX calls.  But this case is neither.

Body:
I think each view should handle their exceptions, so your logic should be in the view, but if we keep in mind MVC rules, exception handling should be on controllers, because they are in charge of communicating with the model. So the question is how make them show in the final view. I don't know if this could be helpful, but I will try a workaround.

The idea is subscribe your exceptions during a request in a list for example, an elegant solution could be having this list in your Viewbag, and then in your global layout write them in the view for example

<ul name="hiddenExceptions" class="hidden">
     <li>exception 1 message wrote in the layout</li>
     <li>exception 2</li>
</ul>

You can have an script later that iterates through this list an take appropriate actions, show them in a box, show at the top of the page, etc.

Hope it helps