问:
Making python wait until subprocess.call has finished its command
So this question is following on from this (Read comments aswell as that is the path I took). I just want the first call robocopy to finish executing before moving on to the rest of the code. As I want the second robocopy to just skip all of the files as they have already been copied over. However what is happening is that the rest of the script will run (ie starts the second robocopy) while the first robocopy is copying over the files. Below is the code:

```<code>call(["start", "cmd", "/K", "RoboCopy.exe", f"{self.srcEntry.get()}", f"{self.dstEntry.get()}", "*.*", "/E", "/Z", "/MT:8"], stdout=PIPE, shell=True)
temp2 = Popen(["RoboCopy.exe", f"{self.srcEntry.get()}", f"{self.dstEntry.get()}", "*.*", "/E", "/Z"], stdout=PIPE, stdin=PIPE, shell=True)
</code>```

EDIT 1:

Issue is noticeable when copying over large files. I'm thinking about putting in a sleep function which is dependent upon the total size of the files to be copied over. However this doesn't take into account upload/download speeds as the files will be transferred over a network.

答: What I've found out: Thanks to QuantumChris. I've found out that robocopy returns from the terminal and back into my script although I've used subprocess.run which should have paused my script until it had finished running. I'm stalling the second robocopy from running by checking if the files have been copied over to the destination folder before progressing with the second robocopy. The issue is that if the last file is big then os.path.isfile() detects the file WHILE it is still being copied over. So it engages the second robocopy however the second robocopy doesn't detect that last file and so attempts to copy the file over but recognises that it can't access the file as it is already in use (by the first robocopy) so it waits 30 secs before trying again. After the 30 secs it is able to access the file and copies it over. What I would like to do now is to make my last file an empty dummy file which I don't care about it being copied twice as it is empty. Robocopy seems to copy over the files according to ASCII order. So I've named the file ~~~~~.txt :D

Body:
So this question is following on from this (Read comments aswell as that is the path I took). I just want the first call robocopy to finish executing before moving on to the rest of the code. As I want the second robocopy to just skip all of the files as they have already been copied over. However what is happening is that the rest of the script will run (ie starts the second robocopy) while the first robocopy is copying over the files. Below is the code:

call(["start", "cmd", "/K", "RoboCopy.exe", f"{self.srcEntry.get()}", f"{self.dstEntry.get()}", "*.*", "/E", "/Z", "/MT:8"], stdout=PIPE, shell=True)
temp2 = Popen(["RoboCopy.exe", f"{self.srcEntry.get()}", f"{self.dstEntry.get()}", "*.*", "/E", "/Z"], stdout=PIPE, stdin=PIPE, shell=True)

EDIT 1:

Issue is noticeable when copying over large files. I'm thinking about putting in a sleep function which is dependent upon the total size of the files to be copied over. However this doesn't take into account upload/download speeds as the files will be transferred over a network.


来源: stackexchange

问:
There is no option to build solution and open properties of project after retarget to net standard 2.0
Repro

I created new solution with project targeted net 4.6.1 and its test project.

Project was copied from solution created in VS 2017

I have changed <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
to <TargetFramework>netstandard2.0</TargetFramework> for both unit test and library project (<OutputType>Library</OutputType>).

Now I cannot build solution. When I open project properties window I see error:

```<code>An error occurred trying to load the project properties window.  Close the window and try again. Member not found. (Exception from HRESULT: 0x80020003 (DISP_E_MEMBERNOTFOUND))
</code>```

答:
Does this help?

Ran into the same issue myself. Appears to be an issue with the solution file. I removed the project from the solution then added it back again. This cause VS to recognize this as the correct project type. Hope this helps somebody else from spending too much time on this issue.

Visual studio 2017 not treating csproj as a valid project file after conversion from netstandard to framework

ContentLicense: CC BY-SA 4.0

Body:
Repro

I created new solution with project targeted net 4.6.1 and its test project.

Project was copied from solution created in VS 2017

I have changed <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
to <TargetFramework>netstandard2.0</TargetFramework> for both unit test and library project (<OutputType>Library</OutputType>).

Now I cannot build solution. When I open project properties window I see error:

An error occurred trying to load the project properties window.  Close the window and try again. Member not found. (Exception from HRESULT: 0x80020003 (DISP_E_MEMBERNOTFOUND))


问:
splitting list into its components and combine to form another list in R
I have list 1:

```<code>l1 <- list(letters[1:26])
</code>```

I have list 2:

```<code>l2 <- list(c(1:26))
</code>```

How would I combine l1 and l2 into a new list l4 with 52 elements: the first 26 elements are the elements of l1 and the next 26 are the elements of l2?

答:
You could use c to combine them

```<code>l4 <- c(l1[[1]], l2[[1]])
</code>```

Or with unlist

```<code>l4 <- c(unlist(l1), unlist(l2))
</code>```

Maybe you want to wrap it in list

```<code>l4 <- list(c(l1[[1]], l2[[1]]))
</code>```

Body:
I have list 1:

l1 <- list(letters[1:26])

I have list 2:

l2 <- list(c(1:26))

How would I combine l1 and l2 into a new list l4 with 52 elements: the first 26 elements are the elements of l1 and the next 26 are the elements of l2?

Body:
You could use c to combine them

l4 <- c(l1[[1]], l2[[1]])

Or with unlist

l4 <- c(unlist(l1), unlist(l2))

Maybe you want to wrap it in list

l4 <- list(c(l1[[1]], l2[[1]]))


问:
Get Video Thumbnail from Uri
I want to select a video from my Gallery. It's working fine. But now I want to display a Bitmap, as a thumbnail.I tried this code and it's not working, it always says: NullPointerException

```<code>Bitmap bitmap2 = ThumbnailUtils.createVideoThumbnail(uri.getPath, MediaStore.Video.Thumbnails.MICRO_KIND);
</code>```

This is all in an onActivityResult().

How can I get the Bitmap from the video Uri??

Thanks for your help

答:
For API 27, for document URI (1000 is microseconds)</p>

```<code>MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource( context, doc_uri );
Bitmap bm = mmr.getScaledFrameAtTime( 1000, MediaMetadataRetriever.OPTION_NEXT_SYNC, 128, 128 );
</code>```

Title: Get Video Thumbnail from Uri

Body:
I want to select a video from my Gallery. It's working fine. But now I want to display a Bitmap, as a thumbnail.I tried this code and it's not working, it always says: NullPointerException

Bitmap bitmap2 = ThumbnailUtils.createVideoThumbnail(uri.getPath, MediaStore.Video.Thumbnails.MICRO_KIND);

This is all in an onActivityResult().

How can I get the Bitmap from the video Uri??

Thanks for your help

Body:
For API 27, for document URI (1000 is microseconds)

MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource( context, doc_uri );
Bitmap bm = mmr.getScaledFrameAtTime( 1000, MediaMetadataRetriever.OPTION_NEXT_SYNC, 128, 128 );


问:
CNN not training TF 2.0 using functional API
I'm trying to train a CNN on this dataset.

I have parsed the image using the below function:

```<code>def parse_image(img, lbl):
image = tf.io.read_file(img)
image = tf.image.decode_jpeg(image)
image = tf.image.convert_image_dtype(image, tf.float32)
image = tf.image.resize(image, [50, 50])
image = tf.reshape(image, [-1, 50, 50, 3])
return image, tf.reshape(lbl, [-1, 1])
</code>```

My model is as follows:

```<code>_input = tf.keras.Input(shape=(50, 50, 3), name='img')
x = tf.keras.layers.Conv2D(32, 3, activation='relu')(_input)
x = tf.keras.layers.Conv2D(64, 3, activation='relu')(x)
x = tf.keras.layers.MaxPooling2D(2)(x)
x = tf.keras.layers.Conv2D(64, 3, activation='relu')(x)
x = tf.keras.layers.Conv2D(64, 3, activation='relu')(x)
x = tf.keras.layers.Conv2D(128, 3, activation='relu')(x)
x = tf.keras.layers.Conv2D(128, 3, activation='relu')(x)
x = tf.keras.layers.Conv2D(128, 3, activation='relu')(x)
x = tf.keras.layers.Conv2D(128, 3, activation='relu')(x)
x = tf.keras.layers.Conv2D(256, 3, activation='relu')(x)
x = tf.keras.layers.Conv2D(256, 3, activation='relu')(x)
x = tf.keras.layers.Flatten()(x)
x = tf.keras.layers.Dense(100, activation='relu', use_bias= True, bias_initializer='he_normal')(x)
_output = tf.keras.layers.Dense(1, activation='softmax',  use_bias= True, bias_initializer='he_normal')(x)
model = keras.Model(_input, _output, name='cnn')
model.summary()
Model: "cnn"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
img (InputLayer)             [(None, 50, 50, 3)]       0
_________________________________________________________________
conv2d_32 (Conv2D)           (None, 48, 48, 32)        896
_________________________________________________________________
conv2d_33 (Conv2D)           (None, 46, 46, 64)        18496
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 23, 23, 64)        0
_________________________________________________________________
conv2d_34 (Conv2D)           (None, 21, 21, 64)        36928
_________________________________________________________________
conv2d_35 (Conv2D)           (None, 19, 19, 64)        36928
_________________________________________________________________
conv2d_36 (Conv2D)           (None, 17, 17, 128)       73856
_________________________________________________________________
conv2d_37 (Conv2D)           (None, 15, 15, 128)       147584
_________________________________________________________________
conv2d_38 (Conv2D)           (None, 13, 13, 128)       147584
_________________________________________________________________
conv2d_39 (Conv2D)           (None, 11, 11, 128)       147584
_________________________________________________________________
conv2d_40 (Conv2D)           (None, 9, 9, 256)         295168
_________________________________________________________________
conv2d_41 (Conv2D)           (None, 7, 7, 256)         590080
_________________________________________________________________
flatten_4 (Flatten)          (None, 12544)             0
_________________________________________________________________
dense_7 (Dense)              (None, 100)               1254500
_________________________________________________________________
dense_8 (Dense)              (None, 1)                 101
=================================================================
Total params: 2,749,705
Trainable params: 2,749,705
</code>```

When trying to train the model the loss stays constant and the accuracy is zero.

```<code>model.compile(tf.keras.optimizers.Adam(lr=0.001), loss='binary_crossentropy',
              metrics=['accuracy'])
model.fit(train_data,
          epochs=2)
Epoch 1/2
1/1 [==============================] - 1s 727ms/step - loss: 15.3332 - accuracy: 0.0000e+00
Epoch 2/2
1/1 [==============================] - 0s 43ms/step - loss: 15.3332 - accuracy: 0.0000e+00
</code>```

I'm not sure what I've done incorrectly as I've used the same parse_image function with the same CNN setup and the Subclassing API yet I was able to train the model.

Thank you.

答:
Don't use Softmax activation when you have only one output for binary classification, use Sigmoid instead :</p>

```<code>_output = tf.keras.layers.Dense(1, activation='sigmoid',  use_bias= True, bias_initializer='he_normal')(x)
</code>```

Body:
I'm trying to train a CNN on this dataset.

I have parsed the image using the below function:

def parse_image(img, lbl):
image = tf.io.read_file(img)
image = tf.image.decode_jpeg(image)
image = tf.image.convert_image_dtype(image, tf.float32)
image = tf.image.resize(image, [50, 50])
image = tf.reshape(image, [-1, 50, 50, 3])
return image, tf.reshape(lbl, [-1, 1])

My model is as follows:

_input = tf.keras.Input(shape=(50, 50, 3), name='img')
x = tf.keras.layers.Conv2D(32, 3, activation='relu')(_input)
x = tf.keras.layers.Conv2D(64, 3, activation='relu')(x)
x = tf.keras.layers.MaxPooling2D(2)(x)
x = tf.keras.layers.Conv2D(64, 3, activation='relu')(x)
x = tf.keras.layers.Conv2D(64, 3, activation='relu')(x)
x = tf.keras.layers.Conv2D(128, 3, activation='relu')(x)
x = tf.keras.layers.Conv2D(128, 3, activation='relu')(x)
x = tf.keras.layers.Conv2D(128, 3, activation='relu')(x)
x = tf.keras.layers.Conv2D(128, 3, activation='relu')(x)
x = tf.keras.layers.Conv2D(256, 3, activation='relu')(x)
x = tf.keras.layers.Conv2D(256, 3, activation='relu')(x)
x = tf.keras.layers.Flatten()(x)
x = tf.keras.layers.Dense(100, activation='relu', use_bias= True, bias_initializer='he_normal')(x)
_output = tf.keras.layers.Dense(1, activation='softmax',  use_bias= True, bias_initializer='he_normal')(x)
model = keras.Model(_input, _output, name='cnn')
model.summary()
Model: "cnn"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
img (InputLayer)             [(None, 50, 50, 3)]       0
_________________________________________________________________
conv2d_32 (Conv2D)           (None, 48, 48, 32)        896
_________________________________________________________________
conv2d_33 (Conv2D)           (None, 46, 46, 64)        18496
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 23, 23, 64)        0
_________________________________________________________________
conv2d_34 (Conv2D)           (None, 21, 21, 64)        36928
_________________________________________________________________
conv2d_35 (Conv2D)           (None, 19, 19, 64)        36928
_________________________________________________________________
conv2d_36 (Conv2D)           (None, 17, 17, 128)       73856
_________________________________________________________________
conv2d_37 (Conv2D)           (None, 15, 15, 128)       147584
_________________________________________________________________
conv2d_38 (Conv2D)           (None, 13, 13, 128)       147584
_________________________________________________________________
conv2d_39 (Conv2D)           (None, 11, 11, 128)       147584
_________________________________________________________________
conv2d_40 (Conv2D)           (None, 9, 9, 256)         295168
_________________________________________________________________
conv2d_41 (Conv2D)           (None, 7, 7, 256)         590080
_________________________________________________________________
flatten_4 (Flatten)          (None, 12544)             0
_________________________________________________________________
dense_7 (Dense)              (None, 100)               1254500
_________________________________________________________________
dense_8 (Dense)              (None, 1)                 101
=================================================================
Total params: 2,749,705
Trainable params: 2,749,705

When trying to train the model the loss stays constant and the accuracy is zero.

model.compile(tf.keras.optimizers.Adam(lr=0.001), loss='binary_crossentropy',
              metrics=['accuracy'])
model.fit(train_data,
          epochs=2)
Epoch 1/2
1/1 [==============================] - 1s 727ms/step - loss: 15.3332 - accuracy: 0.0000e+00
Epoch 2/2
1/1 [==============================] - 0s 43ms/step - loss: 15.3332 - accuracy: 0.0000e+00

I'm not sure what I've done incorrectly as I've used the same parse_image function with the same CNN setup and the Subclassing API yet I was able to train the model.

Thank you.

Body:
Don't use Softmax activation when you have only one output for binary classification, use Sigmoid instead :

_output = tf.keras.layers.Dense(1, activation='sigmoid',  use_bias= True, bias_initializer='he_normal')(x)


问:
Looping over List of different generic types in c#
I have a list comprised of different generic types like such:

```<code>public abstract class BaseClass {}

public class BaseChild<T> : BaseClass {
   public SomeOtherClass<T> data;
}

List<BaseClass> items;
items.Add(new BaseChild<int>());
items.Add(new BaseChild<bool>());
items.Add(new BaseChild<double>());
</code>```

I now want to loop over this list and pass the data property of each item of type SomeOtherClass to a field of the same type in another generic class. Something like this

```<code>public class GenClass<T> {
   public SomeOtherClass<T> assignHere;
}

for(int i=0;i<=items.Count;i++){
   // this does not work. It is unable to get data since it is not
   // defined in BaseClass and the List is of type BaseClass
   items[i].data;
   // somehow assign to assignHere field in GenClass<T> since I don't know type
}
</code>```

I have two questions:

How do I access the data field, since it is only defined on the inheritors but not the parent class? The List I loop over is of Type BaseClass and not BaseChild<T>

How do I assign the data to the assignHere field in the GenClass<T> if I don't know it's Type while looping?

Edit:
Code for SomeOtherClass<T>

```<code>public class SomeOtherClass<T>{
   public T Value;
   public GameEvent<T> event
}

public GameEvent<T>:UnityEvent<T>{
   public void Raise(T value){
      //does something
   }

}
</code>```

Edit #2: Here is one implementation that I have tried and works. Is this better?

```<code>public abstract class BaseButton
    {
        public string displayText;

        public abstract void TriggerButton();
    }

public class IntButton : BaseButton
{
    public IntEvent triggerEvent;
    public int Value;

    public override void TriggerButton()
    {
        triggerEvent.Raise(Value);
    }
}

public class IntEvent : BaseGameEvent<int>{}

public abstract class BaseGameEvent<T>{
    public void Raise(T value){
        // do something
    }
}
</code>```

Thanks!

答:
With reflection :

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");

        List<BaseClass> items = new List<BaseClass>();
        items.Add(new BaseChild<int>());
        items.Add(new BaseChild<bool>());
        items.Add(new BaseChild<double>());

        for (int i = 0; i <= items.Count; i++)
        {
            var generated = Convert(items[i]);
            if (generated is GenClass<int> genInt)
            {
                Console.WriteLine(genInt?.assignHere?.Value);
            }
            else if (generated is GenClass<bool> genBool)
            {
                Console.WriteLine(genBool?.assignHere?.Value);
            }
        }
    }

    static object Convert(BaseClass item)
    {
        var type = item.GetType().GenericTypeArguments[0];
        var method = typeof(Program).GetMethod("GenericConvert", BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(type);
        return method.Invoke(null, new[] { item });
    }

    static GenClass<T> GenericConvert<T>(BaseChild<T> from)
    {
        return new GenClass<T> { assignHere = from.data };
    }
}
```

Body:
I have a list comprised of different generic types like such:

public abstract class BaseClass {}

public class BaseChild<T> : BaseClass {
   public SomeOtherClass<T> data;
}

List<BaseClass> items;
items.Add(new BaseChild<int>());
items.Add(new BaseChild<bool>());
items.Add(new BaseChild<double>());

I now want to loop over this list and pass the data property of each item of type SomeOtherClass to a field of the same type in another generic class. Something like this

public class GenClass<T> {
   public SomeOtherClass<T> assignHere;
}

for(int i=0;i<=items.Count;i++){
   // this does not work. It is unable to get data since it is not
   // defined in BaseClass and the List is of type BaseClass
   items[i].data;
   // somehow assign to assignHere field in GenClass<T> since I don't know type
}

I have two questions:

How do I access the data field, since it is only defined on the inheritors but not the parent class? The List I loop over is of Type BaseClass and not BaseChild<T>

How do I assign the data to the assignHere field in the GenClass<T> if I don't know it's Type while looping?

Edit:
Code for SomeOtherClass<T>

public class SomeOtherClass<T>{
   public T Value;
   public GameEvent<T> event
}

public GameEvent<T>:UnityEvent<T>{
   public void Raise(T value){
      //does something
   }

}

Edit #2: Here is one implementation that I have tried and works. Is this better?

public abstract class BaseButton
    {
        public string displayText;

        public abstract void TriggerButton();
    }

public class IntButton : BaseButton
{
    public IntEvent triggerEvent;
    public int Value;

    public override void TriggerButton()
    {
        triggerEvent.Raise(Value);
    }
}

public class IntEvent : BaseGameEvent<int>{}

public abstract class BaseGameEvent<T>{
    public void Raise(T value){
        // do something
    }
}

Thanks!


问:
Obtaining Azure AD token with Grant_Type=password in fiddler
I was wondering if it is possible to obtain azure ad token in fiddler for a specific user with grant_type=password in fiddler.

I've followed THIS wiki in Github, but I can't get it to work.

I get this error message:

AADSTS50034: To sign into this application the account must be added to the f2f535e0-294f-4704-befc-8ce754f10bd7 directory.

And i know i have added the account because that's the global admin account which is owner over the AD.

Any ideas on what i'm doing wrong.

This is what i'm doing:

```<code>POST: https://login.microsoftonline.com/f2f535e0-294f-4704-befc-8ce754f10bd7/oauth2/token

Content-Type: application/x-www-form-urlencoded
Host: login.microsoftonline.com

grant_type=password&resource=<my application app id>&client_id=<my application client id>&username=<my account>&password=<mypassword>
</code>```

答: ROPC is not supported in hybrid identity federation scenarios (for example, Azure AD and ADFS used to authenticate on-premises accounts, this means you have only sync the users in the azure ad from on prem ad but not syncronize the password). If users are full-page redirected to an on-premises identity providers, Azure AD is not able to test the username and password against that identity provider. </p>

ContentLicense: CC BY-SA 3.0

Body:
I was wondering if it is possible to obtain azure ad token in fiddler for a specific user with grant_type=password in fiddler.

I've followed THIS wiki in Github, but I can't get it to work.

I get this error message:

AADSTS50034: To sign into this application the account must be added to the f2f535e0-294f-4704-befc-8ce754f10bd7 directory.

And i know i have added the account because that's the global admin account which is owner over the AD.

Any ideas on what i'm doing wrong.

This is what i'm doing:

POST: https://login.microsoftonline.com/f2f535e0-294f-4704-befc-8ce754f10bd7/oauth2/token

Content-Type: application/x-www-form-urlencoded
Host: login.microsoftonline.com

grant_type=password&resource=<my application app id>&client_id=<my application client id>&username=<my account>&password=<mypassword>


问:
why is the address of a c++ function always True?
well why would,

```<code>#include <iostream>

using namespace std;

int afunction () {return 0;};

int anotherfunction () {return 0;};

int main ()
{
    cout << &afunction << endl;
}
</code>```

give this,

1

why is every functions address true?

and how then can a function pointer work if all functions share (so it seems) the same addresss?

答: The function pointer type is not supported by std::ostream out of the box. Your pointers are converted to only possible compatible type - bool - and verything that is not zero is true thanks to backward compatibility to C.

Body:
well why would,

#include <iostream>

using namespace std;

int afunction () {return 0;};

int anotherfunction () {return 0;};

int main ()
{
    cout << &afunction << endl;
}

give this,

1

why is every functions address true?

and how then can a function pointer work if all functions share (so it seems) the same addresss?


问:
Akka HTTP server: Acceptor thread in blocked state
I am running Akka HTTP server, where I observe that under load "Acceptor1" and "Acceptor2" threads are always in blocked state. Below is a excerpt from the thread dump.
Why are the acceptors in blocked state? What is a way to increase the number of acceptors?

"qtp1907228381-105 Acceptor1 SelectChannelConnector@0.0.0.0:9000" prio=5 tid=105 BLOCKED
    at sun.nio.ch.ServerSocketChannelImpl.accept(ServerSocketChannelImpl.java:225)
    at org.eclipse.jetty.server.nio.SelectChannelConnector.accept(SelectChannelConnector.java:109)
    at org.eclipse.jetty.server.AbstractConnector$Acceptor.run(AbstractConnector.java:938)
       local variable: java.lang.String#54885
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
       local variable: org.eclipse.jetty.server.AbstractConnector$Acceptor#2
    at java.lang.Thread.run(Thread.java:745)

答: Basically this means it is waiting for more connections to arrive - it's typically not an indication of a problem</p>


问:
Issue with positioning camera that is controlled with mouse so that player stays in view (for third person view)
I've set up rigged player character, moved main camera inside the player object, so it is always moving together with the player and added simple camera movement script that is controlled with mouse. The script is attached to player object.

Here is the script code:

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

public class MouseLook : MonoBehaviour
{
    public float mouseSensitivity = 100f;
    public float minAngle = -45f;
    public float maxAngle = 45f;
    public float minPosition = 0f;
    public float maxPosition = 6f;
    public float camDefaultY = 3.198001f;
    public GameObject headObject;

    private float yaw = 0f;
    private float pitch = 0f;

    private Transform headAngle;
    // Start is called before the first frame update
    void Start()
    {
        headAngle = headObject.transform;
    }

    // Update is called once per frame
    void Update()
    {
        yaw += Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        pitch -= Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
        pitch = Mathf.Clamp(pitch, minAngle, maxAngle);

        transform.eulerAngles = new Vector3(0f, yaw, 0f);
        headObject.transform.eulerAngles = new Vector3(-pitch, headAngle.eulerAngles.y, headAngle.eulerAngles.z);
        Camera.main.transform.eulerAngles = new Vector3(pitch, yaw, 0f);
    }
}
</code>```

The preferred result is to:

make player object  rotate with the camera horizontally (on x axis) on mouse movement (solved)

make player head (child object) and camera rotate vertically on mouse movement (solved)

limit vertical camera rotation to, let's say, 45° (solved)

position camera vertically so the player object is always in the same place (having issue with this)

The issue I'm having is that while I got first 3 things working, I can't find proper way to position camera vertically in a way that player object always will stay +/- in the same place/view. How can I achieve it?

Here is what I got:

And here is what I want to achieve (notice how player stays in the same place in camera):

Also I would like to know if there is maybe easier way to achieve this whole 3rd person mouse control?

Thanks in advance!

答:
So I finally figured it out with some help.
To keep the animation for head, rotate it with the mouse movement and make camera follow no only player's head but also mouse with vertical limitation, I just created additional empty object under Player object to use it as camera target and put the camera inside it.

From that point I added it in my script. Here's an updated code:

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

public class MouseLook : MonoBehaviour
{
    public float mouseSensitivity = 100f;
    public float minAngle = -45f;
    public float maxAngle = 45f;
    public float minPosition = 0f;
    public float maxPosition = 6f;
    public float camDefaultY = 3.198001f;
    public GameObject cameraTarget;
    public GameObject headTarget;

    private float yaw = 0f;
    private float pitch = 0f;

    private Transform targetAngle;
    // Start is called before the first frame update
    void Start()
    {
        targetAngle = cameraTarget.transform;
    }

    // Update is called once per frame
    void Update()
    {
        yaw += Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        pitch -= Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
        pitch = Mathf.Clamp(pitch, minAngle, maxAngle);

        transform.eulerAngles = new Vector3(0f, yaw, 0f);
        cameraTarget.transform.eulerAngles = new Vector3(-pitch, targetAngle.eulerAngles.y, targetAngle.eulerAngles.z);
    }

    void LateUpdate()
    {
        headTarget.transform.eulerAngles = new Vector3(-pitch, targetAngle.eulerAngles.y, targetAngle.eulerAngles.z);
    }
}
</code>```

Body:
I've set up rigged player character, moved main camera inside the player object, so it is always moving together with the player and added simple camera movement script that is controlled with mouse. The script is attached to player object.

Here is the script code:

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

public class MouseLook : MonoBehaviour
{
    public float mouseSensitivity = 100f;
    public float minAngle = -45f;
    public float maxAngle = 45f;
    public float minPosition = 0f;
    public float maxPosition = 6f;
    public float camDefaultY = 3.198001f;
    public GameObject headObject;

    private float yaw = 0f;
    private float pitch = 0f;

    private Transform headAngle;
    // Start is called before the first frame update
    void Start()
    {
        headAngle = headObject.transform;
    }

    // Update is called once per frame
    void Update()
    {
        yaw += Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        pitch -= Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
        pitch = Mathf.Clamp(pitch, minAngle, maxAngle);

        transform.eulerAngles = new Vector3(0f, yaw, 0f);
        headObject.transform.eulerAngles = new Vector3(-pitch, headAngle.eulerAngles.y, headAngle.eulerAngles.z);
        Camera.main.transform.eulerAngles = new Vector3(pitch, yaw, 0f);
    }
}

The preferred result is to:

make player object  rotate with the camera horizontally (on x axis) on mouse movement (solved)

make player head (child object) and camera rotate vertically on mouse movement (solved)

limit vertical camera rotation to, let's say, 45° (solved)

position camera vertically so the player object is always in the same place (having issue with this)

The issue I'm having is that while I got first 3 things working, I can't find proper way to position camera vertically in a way that player object always will stay +/- in the same place/view. How can I achieve it?

Here is what I got:

And here is what I want to achieve (notice how player stays in the same place in camera):

Also I would like to know if there is maybe easier way to achieve this whole 3rd person mouse control?

Thanks in advance!

Body:
So I finally figured it out with some help.
To keep the animation for head, rotate it with the mouse movement and make camera follow no only player's head but also mouse with vertical limitation, I just created additional empty object under Player object to use it as camera target and put the camera inside it.

From that point I added it in my script. Here's an updated code:

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

public class MouseLook : MonoBehaviour
{
    public float mouseSensitivity = 100f;
    public float minAngle = -45f;
    public float maxAngle = 45f;
    public float minPosition = 0f;
    public float maxPosition = 6f;
    public float camDefaultY = 3.198001f;
    public GameObject cameraTarget;
    public GameObject headTarget;

    private float yaw = 0f;
    private float pitch = 0f;

    private Transform targetAngle;
    // Start is called before the first frame update
    void Start()
    {
        targetAngle = cameraTarget.transform;
    }

    // Update is called once per frame
    void Update()
    {
        yaw += Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        pitch -= Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
        pitch = Mathf.Clamp(pitch, minAngle, maxAngle);

        transform.eulerAngles = new Vector3(0f, yaw, 0f);
        cameraTarget.transform.eulerAngles = new Vector3(-pitch, targetAngle.eulerAngles.y, targetAngle.eulerAngles.z);
    }

    void LateUpdate()
    {
        headTarget.transform.eulerAngles = new Vector3(-pitch, targetAngle.eulerAngles.y, targetAngle.eulerAngles.z);
    }
}


问:
AppleScript:IF command doesn't execute
I am a beginner at AppleScript so I really don't know a lot. I have been trying to make the user select from a list of situations and then based on what they choose have an appropriate response. However, I have run into a few problems:

The script runs but doesn't display the notification.

Is there a better way than just chaining a lot of IF statements?

PS: I am nowhere near finishing this whole script.

```<code>on run
    choose from list {"Thunderstorm", "Flood", "Heatwave", "Hazmat"} with prompt "Please select one of the emergency situations below" without multiple selections allowed and empty selection allowed
    return the result as string
    if string is Thunderstorm then display notification "hello"
end run
</code>```

答:
You made some pretty good guesses about what the sample code you were looking at does; but some of those guesses were wrong. With time you’ll get a better feel for how AppleScript works.

You have the situation names entered correctly as strings in the choose from list line, by surrounding their text with quotes. But in the check to see whether it’s a thunderstorm, you do not surround that text with quotes. AppleScript is looking in a variable called Thunderstorm for its contents, not looking at the string of text “Thunderstorm”.

return the result as string does not create a variable called string but rather ends the handler called run, returning the result to whatever code called run, as a string of text. To assign the result of choose from list to a variable, use something like set theSituation to the result as string.

Here’s an example of how your code might work better:

```<code>on run
    --get the situation we're dealing with
    choose from list {"Thunderstorm", "Flood", "Heatwave", "Hazmat"} with prompt "Please select one of the emergency situations below" without multiple selections allowed and empty selection allowed
    copy the result as string to theSituation

    --Thunderstorms require that the user be immediately notified
    if theSituation is "Thunderstorm" then display notification "hello"
end run
</code>```

Since you have this as a run handler, you probably don’t want to return any result, as you rarely call run handlers. But if you do need to return the result, the last line of the handler (just before end run) would be:

```<code>return theSituation
</code>```

You might look around for an AppleScript tutorial that fits your needs. Apple has their Introduction to AppleScript Language Guide.

IF statements can be chained using if/else if/else if:

```<code>on run
    --get the situation we're dealing with
    choose from list {"Thunderstorm", "Flood", "Heatwave", "Hazmat"} with prompt "Please select one of the emergency situations below" without multiple selections allowed and empty selection allowed
    copy the result as string to theSituation

    --Thunderstorms require that the user be immediately notified
    if theSituation is "Thunderstorm" then
        display notification "hello"
    else if theSituation is "Flood" then
        display notification "hike pants"
    else if theSituation is "Heatwave" then
        display notification "Play Bing Crosby"
    else if theSituation is "Hazmat" then
        display notification "Use highway 183"
    end if
end run
</code>```

There is no switch/case control structure in AppleScript.

Title: AppleScript:IF command doesn't execute

Body:
I am a beginner at AppleScript so I really don't know a lot. I have been trying to make the user select from a list of situations and then based on what they choose have an appropriate response. However, I have run into a few problems:

The script runs but doesn't display the notification.

Is there a better way than just chaining a lot of IF statements?

PS: I am nowhere near finishing this whole script.

on run
    choose from list {"Thunderstorm", "Flood", "Heatwave", "Hazmat"} with prompt "Please select one of the emergency situations below" without multiple selections allowed and empty selection allowed
    return the result as string
    if string is Thunderstorm then display notification "hello"
end run

Body:
You made some pretty good guesses about what the sample code you were looking at does; but some of those guesses were wrong. With time you’ll get a better feel for how AppleScript works.

You have the situation names entered correctly as strings in the choose from list line, by surrounding their text with quotes. But in the check to see whether it’s a thunderstorm, you do not surround that text with quotes. AppleScript is looking in a variable called Thunderstorm for its contents, not looking at the string of text “Thunderstorm”.

return the result as string does not create a variable called string but rather ends the handler called run, returning the result to whatever code called run, as a string of text. To assign the result of choose from list to a variable, use something like set theSituation to the result as string.

Here’s an example of how your code might work better:

on run
    --get the situation we're dealing with
    choose from list {"Thunderstorm", "Flood", "Heatwave", "Hazmat"} with prompt "Please select one of the emergency situations below" without multiple selections allowed and empty selection allowed
    copy the result as string to theSituation

    --Thunderstorms require that the user be immediately notified
    if theSituation is "Thunderstorm" then display notification "hello"
end run

Since you have this as a run handler, you probably don’t want to return any result, as you rarely call run handlers. But if you do need to return the result, the last line of the handler (just before end run) would be:

return theSituation

You might look around for an AppleScript tutorial that fits your needs. Apple has their Introduction to AppleScript Language Guide.

IF statements can be chained using if/else if/else if:

on run
    --get the situation we're dealing with
    choose from list {"Thunderstorm", "Flood", "Heatwave", "Hazmat"} with prompt "Please select one of the emergency situations below" without multiple selections allowed and empty selection allowed
    copy the result as string to theSituation

    --Thunderstorms require that the user be immediately notified
    if theSituation is "Thunderstorm" then
        display notification "hello"
    else if theSituation is "Flood" then
        display notification "hike pants"
    else if theSituation is "Heatwave" then
        display notification "Play Bing Crosby"
    else if theSituation is "Hazmat" then
        display notification "Use highway 183"
    end if
end run

There is no switch/case control structure in AppleScript.


问:
Ideas to comments better with python
If you're a python coder you may encounter looking for a way to comments your code better on subcategory code. My meaning by the subcategory code is you may have blocks of codes and then again blocks of codes that relate to the previous block. Here is an example (pay  more attention to comments):

```<code># Drink some water to keep your body hydrated:
initialize some parameters

# Choice a glass:
pick up the glass number one
if the glass was dirty:
   wash the dishes  # this would be difficult.

# Pour the glass with water:
while the glass is not filled up:
   pour the glass
</code>```

All I'm saying we are looking for simplicity and when you are in the middle of a code, it's better to know where you are exactly. See the comments again but this time as headers:

```<code># h1
initialize some parameters

# h2:
pick up the glass number one
if the glass was dirty:
   wash the dishes

# h2:
while the glass is not filled up:
   pour the glass
</code>```

so when you see the comment h2s it would be convenient to know that this part of code is subcode of h1:

I used to make the first letter capital as h1 for comments, and the following code blocks that are related are not capital. Let's wipe out the codes and just focus on the comments:

```<code># Drink some water to keep your body hydrated:
... line of codes ...

# choice a glass:
... line of codes ...

# pour the glass with water:
... line of codes ...
</code>```

There are some pros and coins with that:

pros:

Easy to use.

coins:

It doesn't come to the mind right of way.

If you have more subcategory code this doesn't work.

So I was like "why don't I share this with others to see what they think and what they prefer or use", said it to myself.

答:
I usually split my code in python sections:

```<code>##########  Imports  ##########

##########  Globals  ##########

########## Functions ##########

##########   Main   ###########

</code>```

(I space it equal out with spaces)

And I put comments about functions right before their definition

```<code># a random fuction...
def randomfunction()
    pass
</code>```

Comments about code I put behind the code

```<code>code() # a random example function call
</code>```

Commented out code I delineate from comments this way

```<code>## commented.out.code()
</code>```

Title: Ideas to comments better with python

Body:
If you're a python coder you may encounter looking for a way to comments your code better on subcategory code. My meaning by the subcategory code is you may have blocks of codes and then again blocks of codes that relate to the previous block. Here is an example (pay  more attention to comments):

# Drink some water to keep your body hydrated:
initialize some parameters

# Choice a glass:
pick up the glass number one
if the glass was dirty:
   wash the dishes  # this would be difficult.

# Pour the glass with water:
while the glass is not filled up:
   pour the glass

All I'm saying we are looking for simplicity and when you are in the middle of a code, it's better to know where you are exactly. See the comments again but this time as headers:

# h1
initialize some parameters

# h2:
pick up the glass number one
if the glass was dirty:
   wash the dishes

# h2:
while the glass is not filled up:
   pour the glass

so when you see the comment h2s it would be convenient to know that this part of code is subcode of h1:

I used to make the first letter capital as h1 for comments, and the following code blocks that are related are not capital. Let's wipe out the codes and just focus on the comments:

# Drink some water to keep your body hydrated:
... line of codes ...

# choice a glass:
... line of codes ...

# pour the glass with water:
... line of codes ...

There are some pros and coins with that:

pros:

Easy to use.

coins:

It doesn't come to the mind right of way.

If you have more subcategory code this doesn't work.

So I was like "why don't I share this with others to see what they think and what they prefer or use", said it to myself.

Body:
I usually split my code in python sections:

##########  Imports  ##########

##########  Globals  ##########

########## Functions ##########

##########   Main   ###########

(I space it equal out with spaces)

And I put comments about functions right before their definition

# a random fuction...
def randomfunction()
    pass

Comments about code I put behind the code

code() # a random example function call

Commented out code I delineate from comments this way

## commented.out.code()


问:
Access 'name' property on React Dropzone component
I'm looking to create multiple dropzones in the same component with React Dropzone and I want to handle a file from each dropzone differently. This will be part of a form with many different dropzones that each have different parameters. To start, I am trying to pass some identifying information from a particular dropzone to the useDropzone hook so I can eventually use a different function to handle each dropzone.

How can I access the name property passed through the getRootProps function so I can handle each drop, or is there a better way to accomplish this entirely? In the code below, I was able to print the event to the console, but I can't find "testtesttest" as a value anywhere in the event object. I the props from getRootProps and getInputProps are overriding the name prop I've included, even though I also put it through the getInputProps function.

```<code>import React, {useState, useEffect} from 'react';
import {useDropzone} from 'react-dropzone'
import styled from 'styled-components';

const MasterDropzone = styled.div`
    height: 150px;
    width: 80%;
    border: 3px dashed black;
`

function UploadMedia(){

    const [masterFile, setMasterFile] = useState({
        file: null,
        preview: null
    });

    const {
        getRootProps,
        getInputProps,
    } = useDropzone({
        accept: '.jpeg,.png',
        noClick: false,
        noKeyboard: true,
        onDrop: (acceptedFiles,rejected,event) => {
            console.log(event)
            setMasterFile({
                ...masterFile,
                file: acceptedFiles[0]
            })
        }
    });

    useEffect(
        () => {
            if(!masterFile.file){
                setMasterFile({
                    ...masterFile,
                    preview: undefined
                })
                return
            }
            const objectUrl = URL.createObjectURL(masterFile.file)
            setMasterFile({
                ...masterFile,
                preview: objectUrl
            })
            return () => URL.revokeObjectURL(objectUrl)
        },
        [masterFile.file]
    );
    return (
        <div>
          <h1>Upload Media</h1>
          {
          masterFile.preview
          ?
          <img width='300px' height='300px' src={masterFile.preview} />
          :
          <MasterDropzone name='testtesttest' {...getRootProps({name: 'testtesttest'})}>
          <p>Drag file here or click to upload</p>
          <input name='testtesttest'{...getInputProps({name: 'testtesttest'})} />
          </MasterDropzone>
          }
         </div>
    )
}

export default UploadMedia
</code>```

答:
Ended up solving this by making a Dropzone component and altering what I needed for each dropzone with props thanks to Alvaro's suggestion. Here's what I did

UploadMedia.js

```<code>import Dropzone from './Dropzone'

function UploadMedia({ title }){

    const [masterFile, setMasterFile] = useState({
        content: null,
        preview: null
    });
    const [subtitleFile, setSubtitleFile] = useState({
        content: null,
        preview: null
    })

    const [posterImage, setPosterImage] = useState({
        content: null,
        preview: null
    })

    const [coverImage, setCoverImage] = useState({
        content: null,
        preview: null
    })

    const [featureImage, setFeatureImage] = useState({
        content: null,
        preview: null
    })

    const masterText = <p>Master Video File</p>

    const subtitleText = <p>Subtitle File</p>

    const posterText = <p>Poster Image</p>

    const coverText = <p>Cover Photo</p>

    const featureText = <p>Feature Photo</p>

    async function handleSubmit(evt) {
        evt.preventDefault()
        console.log('handle files here')
    }

    return (
        <Container>
            <h1>Upload media for {title.titleName}</h1>
            <Form onSubmit={handleSubmit}>
            <Dropzone file={masterFile} setFile={setMasterFile} text={masterText} height='200px' width='70%'/>
            <Dropzone file={subtitleFile} setFile={setSubtitleFile} text={subtitleText} height='100px' width='70%'/>
            <Dropzone file={posterImage} setFile={setPosterImage} text={posterText} height='200px' width='100px'/>
            <Dropzone file={coverImage} setFile={setCoverImage} text={coverText} height='150px' width='350px'/>
            <Dropzone file={featureImage} setFile={setFeatureImage} text={featureText} height='200px' width='400px'/>
            <button type="submit">Save And Upload</button>
            </Form>
        </Container>
    )
}

export default UploadMedia
</code>```

Dropzone.js

```<code>function Dropzone({file, setFile, height, width, text}){

    const {
        getRootProps,
        getInputProps,
    } = useDropzone({
        acceptedFiles: '',
        noClick: false,
        noKeyboard: true,
        onDrop: (acceptedFiles) => {
            setFile({
                ...file,
                content: acceptedFiles[0]
            })
        }
    });

    useEffect(
        () => {
            if(!file.content){
                setFile({
                    ...file,
                    preview: undefined
                })
                return
            }
            const objectUrl = URL.createObjectURL(file.content)
            setFile({
                ...file,
                preview: objectUrl
            })
            // this line prevents memory leaks, but also removes reference to the image URL
            // google chrome will remove this automatically when current session ends

            // return () => URL.revokeObjectURL(objectUrl)
        },
        [file.content]
    );

    return (
        <Container height={height} width={width}>
        {
        file.preview
        ?
        <img width='40px' height='40px' src={file.preview} />
        :
        <DropzoneContainer {...getRootProps()}>
        {text}
        <p>Drag file or click to upload file</p>
        <input {...getInputProps()} />
        </DropzoneContainer>
        }
        </Container>
    )
}

export default Dropzone
</code>```

Body:
I'm looking to create multiple dropzones in the same component with React Dropzone and I want to handle a file from each dropzone differently. This will be part of a form with many different dropzones that each have different parameters. To start, I am trying to pass some identifying information from a particular dropzone to the useDropzone hook so I can eventually use a different function to handle each dropzone.

How can I access the name property passed through the getRootProps function so I can handle each drop, or is there a better way to accomplish this entirely? In the code below, I was able to print the event to the console, but I can't find "testtesttest" as a value anywhere in the event object. I the props from getRootProps and getInputProps are overriding the name prop I've included, even though I also put it through the getInputProps function.

import React, {useState, useEffect} from 'react';
import {useDropzone} from 'react-dropzone'
import styled from 'styled-components';

const MasterDropzone = styled.div`
    height: 150px;
    width: 80%;
    border: 3px dashed black;
`

function UploadMedia(){

    const [masterFile, setMasterFile] = useState({
        file: null,
        preview: null
    });

    const {
        getRootProps,
        getInputProps,
    } = useDropzone({
        accept: '.jpeg,.png',
        noClick: false,
        noKeyboard: true,
        onDrop: (acceptedFiles,rejected,event) => {
            console.log(event)
            setMasterFile({
                ...masterFile,
                file: acceptedFiles[0]
            })
        }
    });

    useEffect(
        () => {
            if(!masterFile.file){
                setMasterFile({
                    ...masterFile,
                    preview: undefined
                })
                return
            }
            const objectUrl = URL.createObjectURL(masterFile.file)
            setMasterFile({
                ...masterFile,
                preview: objectUrl
            })
            return () => URL.revokeObjectURL(objectUrl)
        },
        [masterFile.file]
    );
    return (

Upload Media

          {
          masterFile.preview
          ?

          :
          <MasterDropzone name='testtesttest' {...getRootProps({name: 'testtesttest'})}>

Drag file here or click to upload

          <input name='testtesttest'{...getInputProps({name: 'testtesttest'})} />
          </MasterDropzone>
          }

    )
}

export default UploadMedia

Body:
Ended up solving this by making a Dropzone component and altering what I needed for each dropzone with props thanks to Alvaro's suggestion. Here's what I did

UploadMedia.js

import Dropzone from './Dropzone'

function UploadMedia({ title }){

    const [masterFile, setMasterFile] = useState({
        content: null,
        preview: null
    });
    const [subtitleFile, setSubtitleFile] = useState({
        content: null,
        preview: null
    })

    const [posterImage, setPosterImage] = useState({
        content: null,
        preview: null
    })

    const [coverImage, setCoverImage] = useState({
        content: null,
        preview: null
    })

    const [featureImage, setFeatureImage] = useState({
        content: null,
        preview: null
    })

    const masterText = <p>Master Video File</p>

    const subtitleText = <p>Subtitle File</p>

    const posterText = <p>Poster Image</p>

    const coverText = <p>Cover Photo</p>

    const featureText = <p>Feature Photo</p>

    async function handleSubmit(evt) {
        evt.preventDefault()
        console.log('handle files here')
    }

    return (
        <Container>
            <h1>Upload media for {title.titleName}</h1>
            <Form onSubmit={handleSubmit}>
            <Dropzone file={masterFile} setFile={setMasterFile} text={masterText} height='200px' width='70%'/>
            <Dropzone file={subtitleFile} setFile={setSubtitleFile} text={subtitleText} height='100px' width='70%'/>
            <Dropzone file={posterImage} setFile={setPosterImage} text={posterText} height='200px' width='100px'/>
            <Dropzone file={coverImage} setFile={setCoverImage} text={coverText} height='150px' width='350px'/>
            <Dropzone file={featureImage} setFile={setFeatureImage} text={featureText} height='200px' width='400px'/>
            <button type="submit">Save And Upload</button>
            </Form>
        </Container>
    )
}

export default UploadMedia

Dropzone.js

function Dropzone({file, setFile, height, width, text}){

    const {
        getRootProps,
        getInputProps,
    } = useDropzone({
        acceptedFiles: '',
        noClick: false,
        noKeyboard: true,
        onDrop: (acceptedFiles) => {
            setFile({
                ...file,
                content: acceptedFiles[0]
            })
        }
    });

    useEffect(
        () => {
            if(!file.content){
                setFile({
                    ...file,
                    preview: undefined
                })
                return
            }
            const objectUrl = URL.createObjectURL(file.content)
            setFile({
                ...file,
                preview: objectUrl
            })
            // this line prevents memory leaks, but also removes reference to the image URL
            // google chrome will remove this automatically when current session ends

            // return () => URL.revokeObjectURL(objectUrl)
        },
        [file.content]
    );

    return (
        <Container height={height} width={width}>
        {
        file.preview
        ?
        <img width='40px' height='40px' src={file.preview} />
        :
        <DropzoneContainer {...getRootProps()}>
        {text}
        <p>Drag file or click to upload file</p>
        <input {...getInputProps()} />
        </DropzoneContainer>
        }
        </Container>
    )
}

export default Dropzone


问:
How does Spring decide which bean to inject when there is two candidates defined with @Qualifier?
Suppose that I have two beans defined like this:

```<code>@Configuration
public class ConfigurationA {

    @Bean
    @Qualifier("restTemplateA")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
}
</code>```

```<code>@Configuration
public class ConfigurationB {

    @Bean
    @Qualifier("restTemplateB")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
}
</code>```

When I autowire restTemplate without providing @Qualifier, which bean will be injected? How is it decided?

```<code>@Service
public class someClass {

    @Autowired
    private RestTemplate restTemplate;

}
</code>```

Note:When I test, one of the bean is injected. It didn't lead any exception.

Note2: I know I can use @Qualifier to inject the bean that I want or I can use @Primary to avoid ambiguity. But I just want to understand why it is valid for Spring.

Note3: When I changed the method name in class ConfigurationB to restTemplateB, bean defined in ConfigurationA is injected. Again it didnt' lead any exception.

I tried this in Spring Boot version 1.4.4

答:
Actually, you cannot have both configuration classes, because you'll get a bean name conflict. To fix this, rename the method name:

```<code>@Bean
    @Qualifier("restTemplateB")
    public RestTemplate restTemplateB() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
</code>```

This way, two RestTemplate will be created with restTemplate and restTemplateB name respectively, and the first one will be injected in the service class.

Body:
Suppose that I have two beans defined like this:

@Configuration
public class ConfigurationA {

    @Bean
    @Qualifier("restTemplateA")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
}

@Configuration
public class ConfigurationB {

    @Bean
    @Qualifier("restTemplateB")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
}

When I autowire restTemplate without providing @Qualifier, which bean will be injected? How is it decided?

@Service
public class someClass {

    @Autowired
    private RestTemplate restTemplate;

}

Note:When I test, one of the bean is injected. It didn't lead any exception.

Note2: I know I can use @Qualifier to inject the bean that I want or I can use @Primary to avoid ambiguity. But I just want to understand why it is valid for Spring.

Note3: When I changed the method name in class ConfigurationB to restTemplateB, bean defined in ConfigurationA is injected. Again it didnt' lead any exception.

I tried this in Spring Boot version 1.4.4

Body:
Actually, you cannot have both configuration classes, because you'll get a bean name conflict. To fix this, rename the method name:

@Bean
    @Qualifier("restTemplateB")
    public RestTemplate restTemplateB() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }

This way, two RestTemplate will be created with restTemplate and restTemplateB name respectively, and the first one will be injected in the service class.


问:
Angular 8 - Lazy Loading of Module not working
As shown in https://stackblitz.com/edit/angular-qbbhgp, I am trying to achieve a very simple routing which involve lazy loading of module. When I click on the "link", it seems not working. I expected to see the word "Student Page" appear, but it did not happen.

Note that I would like the solution to involve the use of import api (the newer syntax to lazy load module)

答:
You have not provided a Routes for Student.routing.module?

Since you have directed the student.module, but you might have not provided from there what component you have been show.

If you have not created to Student.routing.module, create one and provide a default route in the same module.

```<code>const routes: Routes = [

  {path: '', component:StudentComponent } ];
</code>```

Body:
You have not provided a Routes for Student.routing.module?

Since you have directed the student.module, but you might have not provided from there what component you have been show.

If you have not created to Student.routing.module, create one and provide a default route in the same module.

const routes: Routes = [

  {path: '', component:StudentComponent } ];


问:
C# Linq create a list of derived class inside Group By
I have a method in which I call a method that performs a query returning an IEnumerable of objects, then I perform a group by Linq on this IEnumerable, and elaborate the result of the grouping to insert it in a JQGrid. In the grouping, I create an object containing a list of other objects. I want that this list is not of the base type, but I would like it to be of the derived type.
This is the call to the method that performs the query, returning the IEnumerable object:

```<code>IEnumerable documentList = ObjBase.getAll(string.IsNullOrEmpty(columnList) ? null : columnList.Split(';'), sidx, sord, sqlWhere, out totalRows, userid: userId, siteId: siteId);
</code>```

This is the class of objects that I have after the group by Linq:

```<code>public class DocumentContact : ObjBase
{
    public long? CODE_CUSTOMER_ID { get; set; }
    public long? CODE_CUSTOMERTYPEID { get; set; }
    public long? CODE_CONTRACT_ID { get; set; }
    public long CODE_SITEID { get; set; }
    public string DESC_CONTACT_NUMBER { get; set; }
    public string DESC_CONTRACT_NUMBER { get; set; }
    public string DESC_CONTRACT_STATES { get; set; }
    public List<DocumentModelDates> Documents { get; set; }
}
</code>```

This is the DocumentModel class:

```<code>public class DocumentModel : ObjBase
{
    private long _id;
    private string _documentModel;
    private long? _documentModelTypeId;
    private long? _documentModelIssuingEntityId;
    private string _documentModelFilename;
    private string _documentModelPath;
    private DateTime? _documentModelStart;
    private DateTime? _documentModelEnd;
    private string _documentModelVersion;
    private long _contractId;
    private string _contractNumber;
    private long _contractTypeId;
    private long _contractStateId;
    private string _contractState;
    private long _documentModelStateId;
    private string _documentModelValoId;
    private DateTime? _documentModelUploadDate;
    private byte[] _documentModelContent;
    private long _documentModelFilter;
    private bool _flagDeleted;
    private long _userId;
    private int _orderDocumentModel = 0;
    private string _placeOfIssue;
    private string _issuingEntity;
    private DateTime? _releaseDate;
    private int? _idOpInsert;
    private int? _idOpId;
    private long? _customerId;
    private long? _customerTypeId;
    private string _customerNumber;
    private DateTime? _documentModelInvalidated;
    private bool _flagValidating;
    private string _fileRemotePath;
    private long? _folderId;
    private string _folderName;
    protected new HELPSI_Database HELPSI_Database = Common.HELPSI_Database.HELPSI_Anag;
}
</code>```

This is the DocumentModelDates, derived from DocumentModel:

```<code>    public class DocumentModelDates : DocumentModel
{
    public long? DateStart { get; set; }
    public long? DateEnd { get; set; }
    public long? DateUpload { get; set; }

    public DocumentModelDates(DocumentModel document)
    {
        this.CODE_DOCUMENT_MODEL_ID = document.CODE_DOCUMENT_MODEL_ID;
        this.DateStart = document.DATE_DOCUMENT_MODEL_START.Value.Ticks;
        this.DateEnd = document.DATE_DOCUMENT_MODEL_END.Value.Ticks;
        this.DateUpload = document.DATE_DOCUMENT_MODEL_UPLOAD.Value.Ticks;
    }
}
</code>```

This is the Group By Linq operation on these IEnumerable:

```<code>    var documentContact = documentList.GroupBy(c => new
    {
        c.CODE_CUSTOMERID,
        c.DESC_CONTACT_NUMBER,
        c.CODE_CUSTOMERTYPEID,
        c.CODE_CONTRACT_ID,
        c.DESC_CONTRACT_NUMBER,
        c.DESC_CONTRACT_STATES,
    })
    .Select(gcs => new DocumentContact()
    {
        CODE_CUSTOMER_ID = gcs.Key.CODE_CUSTOMERID,
        DESC_CONTACT_NUMBER = gcs.Key.DESC_CONTACT_NUMBER,
        CODE_CUSTOMERTYPEID = gcs.Key.CODE_CUSTOMERTYPEID,
        CODE_CONTRACT_ID = gcs.Key.CODE_CONTRACT_ID,
        DESC_CONTRACT_NUMBER = gcs.Key.DESC_CONTRACT_NUMBER,
        DESC_CONTRACT_STATES = gcs.Key.DESC_CONTRACT_STATES,
        CODE_SITEID = siteId,
        Documents = gcs.ToList(),
    });
</code>```

If I do this, I have a conversion error: Is there a way to create a DocumentModelDates list inside this Select? Thanks.

答:
You just need:</p>

```<code>.Select(gcs => new DocumentContact()
{
    //...
    Documents = gcs.Select(i => new DocumentModelDates(i)).ToList()
});
</code>```

Body:
I have a method in which I call a method that performs a query returning an IEnumerable of objects, then I perform a group by Linq on this IEnumerable, and elaborate the result of the grouping to insert it in a JQGrid. In the grouping, I create an object containing a list of other objects. I want that this list is not of the base type, but I would like it to be of the derived type.
This is the call to the method that performs the query, returning the IEnumerable object:

IEnumerable documentList = ObjBase.getAll(string.IsNullOrEmpty(columnList) ? null : columnList.Split(';'), sidx, sord, sqlWhere, out totalRows, userid: userId, siteId: siteId);

This is the class of objects that I have after the group by Linq:

public class DocumentContact : ObjBase
{
    public long? CODE_CUSTOMER_ID { get; set; }
    public long? CODE_CUSTOMERTYPEID { get; set; }
    public long? CODE_CONTRACT_ID { get; set; }
    public long CODE_SITEID { get; set; }
    public string DESC_CONTACT_NUMBER { get; set; }
    public string DESC_CONTRACT_NUMBER { get; set; }
    public string DESC_CONTRACT_STATES { get; set; }
    public List<DocumentModelDates> Documents { get; set; }
}

This is the DocumentModel class:

public class DocumentModel : ObjBase
{
    private long _id;
    private string _documentModel;
    private long? _documentModelTypeId;
    private long? _documentModelIssuingEntityId;
    private string _documentModelFilename;
    private string _documentModelPath;
    private DateTime? _documentModelStart;
    private DateTime? _documentModelEnd;
    private string _documentModelVersion;
    private long _contractId;
    private string _contractNumber;
    private long _contractTypeId;
    private long _contractStateId;
    private string _contractState;
    private long _documentModelStateId;
    private string _documentModelValoId;
    private DateTime? _documentModelUploadDate;
    private byte[] _documentModelContent;
    private long _documentModelFilter;
    private bool _flagDeleted;
    private long _userId;
    private int _orderDocumentModel = 0;
    private string _placeOfIssue;
    private string _issuingEntity;
    private DateTime? _releaseDate;
    private int? _idOpInsert;
    private int? _idOpId;
    private long? _customerId;
    private long? _customerTypeId;
    private string _customerNumber;
    private DateTime? _documentModelInvalidated;
    private bool _flagValidating;
    private string _fileRemotePath;
    private long? _folderId;
    private string _folderName;
    protected new HELPSI_Database HELPSI_Database = Common.HELPSI_Database.HELPSI_Anag;
}

This is the DocumentModelDates, derived from DocumentModel:

    public class DocumentModelDates : DocumentModel
{
    public long? DateStart { get; set; }
    public long? DateEnd { get; set; }
    public long? DateUpload { get; set; }

    public DocumentModelDates(DocumentModel document)
    {
        this.CODE_DOCUMENT_MODEL_ID = document.CODE_DOCUMENT_MODEL_ID;
        this.DateStart = document.DATE_DOCUMENT_MODEL_START.Value.Ticks;
        this.DateEnd = document.DATE_DOCUMENT_MODEL_END.Value.Ticks;
        this.DateUpload = document.DATE_DOCUMENT_MODEL_UPLOAD.Value.Ticks;
    }
}

This is the Group By Linq operation on these IEnumerable:

    var documentContact = documentList.GroupBy(c => new
    {
        c.CODE_CUSTOMERID,
        c.DESC_CONTACT_NUMBER,
        c.CODE_CUSTOMERTYPEID,
        c.CODE_CONTRACT_ID,
        c.DESC_CONTRACT_NUMBER,
        c.DESC_CONTRACT_STATES,
    })
    .Select(gcs => new DocumentContact()
    {
        CODE_CUSTOMER_ID = gcs.Key.CODE_CUSTOMERID,
        DESC_CONTACT_NUMBER = gcs.Key.DESC_CONTACT_NUMBER,
        CODE_CUSTOMERTYPEID = gcs.Key.CODE_CUSTOMERTYPEID,
        CODE_CONTRACT_ID = gcs.Key.CODE_CONTRACT_ID,
        DESC_CONTRACT_NUMBER = gcs.Key.DESC_CONTRACT_NUMBER,
        DESC_CONTRACT_STATES = gcs.Key.DESC_CONTRACT_STATES,
        CODE_SITEID = siteId,
        Documents = gcs.ToList(),
    });

If I do this, I have a conversion error: Is there a way to create a DocumentModelDates list inside this Select? Thanks.

Body:
You just need:

.Select(gcs => new DocumentContact()
{
    //...
    Documents = gcs.Select(i => new DocumentModelDates(i)).ToList()
});


问:
Mouse over is not changing the material when hovering over game object in unity
I want to be able to hover over certain game objects and the object changes material. I cannot figure out why my game object won't change material when I hover over it. I have made sure and added the materials in the inspector. I have tried multiple ways to get it to work but still no luck. I am using unity 2018.4.16. I have tried using different examples and looked at the documentation, but alas I am stuck in the water. Any help would be very appreciated.</p>

```<code>        public Material startColor;
        public Material mouseOverColor;
        Renderer rend;

        void OnMouseOver()
        {
            rend.sharedMaterial = mouseOverColor;
        }

        void OnMouseExit()
        {
            rend.sharedMaterial = startColor;
        }

        // Start is called before the first frame update
        void Start()
        {
            rend = GetComponent<Renderer>();
            rend.enabled = true;
            rend.sharedMaterial = startColor;
        }
</code>```

答: I ended up finding a solution. I needed to add a "Rigidbody" component and then checking "Is Kinematic" in the inspector as well as adding a "mesh collider" component, and now it works for anyone who is having a similar issue.</p>

Body:
I want to be able to hover over certain game objects and the object changes material. I cannot figure out why my game object won't change material when I hover over it. I have made sure and added the materials in the inspector. I have tried multiple ways to get it to work but still no luck. I am using unity 2018.4.16. I have tried using different examples and looked at the documentation, but alas I am stuck in the water. Any help would be very appreciated.

        public Material startColor;
        public Material mouseOverColor;
        Renderer rend;

        void OnMouseOver()
        {
            rend.sharedMaterial = mouseOverColor;
        }

        void OnMouseExit()
        {
            rend.sharedMaterial = startColor;
        }

        // Start is called before the first frame update
        void Start()
        {
            rend = GetComponent<Renderer>();
            rend.enabled = true;
            rend.sharedMaterial = startColor;
        }


问:
How to use a gem method (returning strings) as custom validation in rails app
I'm new to RoR/Gems, this is a basic question.

I created a gem, MyNameGem, in order to learn the process. It contains these methods:

```<code>def returnValidationString1
  puts 'Validation String'
end
def returnValidationString2
  puts 'ANother Validation String'
end
</code>```

I included the gem in a simple rails app, everything seems to be working as expected.
I this to my model:

```<code>validates :name => MyNameGem.returnValidationString1
</code>```

What I'm trying to create is a gem that I can use inside a validation routine. So, for example, I want to do this: validates :name => (call my gem method, return a string, and use that string as the validation requirement)

答:
The function of puts is to put things to the console, so that's exactly what it will do. What your validates call is doing is kind of unusual though, and doesn't seem to make any sense. Your code evaluates to:

```<code>validates :name => (puts "MyNameGem")
</code>```

That really doesn't mean anything. puts usually returns nil.

If you want to write a custom validation routine that's stored in a gem, that's a different question.

Body:
I'm new to RoR/Gems, this is a basic question.

I created a gem, MyNameGem, in order to learn the process. It contains these methods:

def returnValidationString1
  puts 'Validation String'
end
def returnValidationString2
  puts 'ANother Validation String'
end

I included the gem in a simple rails app, everything seems to be working as expected.
I this to my model:

validates :name => MyNameGem.returnValidationString1

What I'm trying to create is a gem that I can use inside a validation routine. So, for example, I want to do this: validates :name => (call my gem method, return a string, and use that string as the validation requirement)

Body:
The function of puts is to put things to the console, so that's exactly what it will do. What your validates call is doing is kind of unusual though, and doesn't seem to make any sense. Your code evaluates to:

validates :name => (puts "MyNameGem")

That really doesn't mean anything. puts usually returns nil.

If you want to write a custom validation routine that's stored in a gem, that's a different question.


答:
I think what you will find, is if you run your application, it will log an error like requried a single bean but 2 were found.

What you can do however is remove the ambiguity using the @Qualifier where you need it injected and naming your bean definitions, i.e. for your example.

```<code>@Configuration
public class Configuration {

    @Bean(name="restTemplateA")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }

    @Bean(name="restTemplateB")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
}
</code>```

Then when you come to injecting and using the templates

```<code>@Service
public class someClass {

    @Autowired
    @Qualifer("restTemplateA")
    private RestTemplate restTemplate;

}
</code>```

However, you can also mark one of the templates as a Primary with @Primary, and this bean will then be used in each place you do not qualify your autowired.

```<code>    @Bean(name="restTemplateA")
    @Primary
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
</code>```

Title: How does Spring decide which bean to inject when there is two candidates defined with @Qualifier?

Body:
I think what you will find, is if you run your application, it will log an error like requried a single bean but 2 were found.

What you can do however is remove the ambiguity using the @Qualifier where you need it injected and naming your bean definitions, i.e. for your example.

@Configuration
public class Configuration {

    @Bean(name="restTemplateA")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }

    @Bean(name="restTemplateB")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }
}

Then when you come to injecting and using the templates

@Service
public class someClass {

    @Autowired
    @Qualifer("restTemplateA")
    private RestTemplate restTemplate;

}

However, you can also mark one of the templates as a Primary with @Primary, and this bean will then be used in each place you do not qualify your autowired.

    @Bean(name="restTemplateA")
    @Primary
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        //setting some restTemplate properties

        return restTemplate;
    }


答:
It's because you haven't added routing to your student module.

Fork of your stackblitz: https://stackblitz.com/edit/angular-zrnrxj

The student module needs to use .forChild() when declaring routes since it is a child module.

```<code>const routes:Routes = [
  { path: '', component: StudentComponent }
]

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  declarations: [StudentComponent]
})
export class StudentModule { }
</code>```

Title: Angular 8 - Lazy Loading of Module not working

Body:
As shown in https://stackblitz.com/edit/angular-qbbhgp, I am trying to achieve a very simple routing which involve lazy loading of module. When I click on the "link", it seems not working. I expected to see the word "Student Page" appear, but it did not happen.

Note that I would like the solution to involve the use of import api (the newer syntax to lazy load module)

Body:
It's because you haven't added routing to your student module.

Fork of your stackblitz: https://stackblitz.com/edit/angular-zrnrxj

The student module needs to use .forChild() when declaring routes since it is a child module.

const routes:Routes = [
  { path: '', component: StudentComponent }
]

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  declarations: [StudentComponent]
})
export class StudentModule { }


问:
How to update multiple rows using more than one CASE statement in SQL Server?
How can I use more than one CASE to update my rows in my table? I've been trying to write the script in different ways, but I'm sure the syntax is wrong. Any idea where the error is?

```<code>UPDATE NameToSplit
SET Aliases = CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 4 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 5, 0, '-')END;
              CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 5 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 6, 0, '-')END;
              CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 6 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 7, 0, '-')END;
              CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 7 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 8, 0, '-')END;
             CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 8 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 9, 0, '-')END;
             CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 9 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 10, 0, '-')END;
</code>```

The results must be like:

```<code>        Names                              Alias                  Aliases
    -------------------------------------------------------------------------
    idealink.core.usergroup            core.usergroup         core.user-group
    idealink.core.userloginhistory     core.userloginhistory  core.user-loginhistory
   idealink.core.challengecategories   core.challengecategories core.challenge-categories
   idealink.core.activitydetails       core.activitydetails    core.activity-details
</code>```

The length of the words after (core.) are different that's why I needed to create different cases to get all of them.

答:
In my humble opinion, your problem is not the CASE statement. The main problem you have here is how to split a string that contains two or more words into only two strings.

For example, you need to find a way to split strings like these:

```<code>usergroup           user group (2 words split into two strings)
userloginhistory    user loginhistory (3 words split into two strings)
challengecategories challenge categories (2 words split into two strings)
activitydetails     activity details (2 words split into two strings)
</code>```

So, somehow you need to find a common criteria. For example, at least, you need a list of all the possible starting words in your tables. In the example above these starting words are: user, challenge and activity. In that way, you can write some code to insert the dash right after one of those.

In order to you give a code solution, please let me know if getting this list of words is possible for you (I would probably put them in a temp table and use them from there).

Body:
How can I use more than one CASE to update my rows in my table? I've been trying to write the script in different ways, but I'm sure the syntax is wrong. Any idea where the error is?

UPDATE NameToSplit
SET Aliases = CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 4 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 5, 0, '-')END;
              CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 5 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 6, 0, '-')END;
              CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 6 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 7, 0, '-')END;
              CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 7 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 8, 0, '-')END;
             CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 8 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 9, 0, '-')END;
             CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 9 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 10, 0, '-')END;

The results must be like:

        Names                              Alias                  Aliases
    -------------------------------------------------------------------------
    idealink.core.usergroup            core.usergroup         core.user-group
    idealink.core.userloginhistory     core.userloginhistory  core.user-loginhistory
   idealink.core.challengecategories   core.challengecategories core.challenge-categories
   idealink.core.activitydetails       core.activitydetails    core.activity-details

The length of the words after (core.) are different that's why I needed to create different cases to get all of them.

Body:
In my humble opinion, your problem is not the CASE statement. The main problem you have here is how to split a string that contains two or more words into only two strings.

For example, you need to find a way to split strings like these:

usergroup           user group (2 words split into two strings)
userloginhistory    user loginhistory (3 words split into two strings)
challengecategories challenge categories (2 words split into two strings)
activitydetails     activity details (2 words split into two strings)

So, somehow you need to find a common criteria. For example, at least, you need a list of all the possible starting words in your tables. In the example above these starting words are: user, challenge and activity. In that way, you can write some code to insert the dash right after one of those.

In order to you give a code solution, please let me know if getting this list of words is possible for you (I would probably put them in a temp table and use them from there).


问:
How is memory deallocated in c++
I understand pointer allocation of memory fully, but deallocation of memory only on a higher level. What I'm most curious about is how C++ keeps track of what memory has already been deallocated?

```<code>int* ptr = new int;
cout << ptr;
delete ptr;
cout << ptr;
// still pointing to the same place however it knows you can't access it or delete it again
*ptr // BAD
delete ptr // BAD
</code>```

How does C++ know I deallocated that memory. If it just turns it to arbitrary garbage binary numbers, wouldn't I just be reading in that garbage number when I dereference the pointer?

Instead, of course, c++ knows that these are segfaults somehow.

答:
I take it that you wonder what delete actually does. Here it is:

First of all, it destructs the object. If the object has a destructor, it is called, and does whatever it is programmed to do.

delete then proceeds to deallocate the memory itself. This means that the deallocator function (::operator delete() in most cases in C++) typically takes the memory object, and adds it to its own, internal data structures. I.e. it makes sure that the next call to ::operator new() can find the deallocated memory slab. The next new might then reuse that memory slab for other purposes.

The entire management of memory happens by using data structures that you do not see, or need to know that they exist. How an implementation of ::operator new() and ::operator delete() organizes its internal data is strictly and fully up to the implementation. It doesn't concern you.

What concerns you is, that the language standard defines that any access to a memory object is undefined behavior after you have passed it to the delete operator. Undefined behavior does not mean that the memory needs to vanish magically, or that it becomes inaccessible, or that it is filled with garbage. Usually none of these happens immediately, because making the memory inaccessible or filling it with garbage would require explicit action from the CPU, so implementations don't generally touch what's written in the memory. You are just forbidden to make further accesses, because it's now up to system to use the memory for any other purpose it likes.

Title: How is memory deallocated in c++

Body:
I understand pointer allocation of memory fully, but deallocation of memory only on a higher level. What I'm most curious about is how C++ keeps track of what memory has already been deallocated?

int* ptr = new int;
cout << ptr;
delete ptr;
cout << ptr;
// still pointing to the same place however it knows you can't access it or delete it again
*ptr // BAD
delete ptr // BAD

How does C++ know I deallocated that memory. If it just turns it to arbitrary garbage binary numbers, wouldn't I just be reading in that garbage number when I dereference the pointer?

Instead, of course, c++ knows that these are segfaults somehow.


问:
Does events like onClick in React pollute memory heap?
I was learning React and came across events like onCLick. Before that, I read an article saying that if we use addEventListener in pure JS then it can pollute memory heap thus we need to use removeEventListener() to ensure that there is no memory heap pollution. The question is "Is it the case with React?", that is, when we use onCLick or any other event in React, will any of them pollute the memory heap?</p>

答:
The question is "Is it the case with React?", that is, when we use onCLick or any other event in React, will any of them pollute the memory heap?

No. If you use react's normal technique for event listeners, such as the onClick prop of a div, then react will cleanup those listeners for you when
the component unmounts.

For example, the following code will not cause a memory leak.

```<code>const ExampleComponent = (props) => {
  return (
    <div onClick={() => console.log('hi')}/>
  )
}
</code>```

Body:
The question is "Is it the case with React?", that is, when we use onCLick or any other event in React, will any of them pollute the memory heap?

No. If you use react's normal technique for event listeners, such as the onClick prop of a div, then react will cleanup those listeners for you when
the component unmounts.

For example, the following code will not cause a memory leak.

const ExampleComponent = (props) => {
  return (
    <div onClick={() => console.log('hi')}/>
  )
}


问:
Using double value as a score for GKLeaderboard?
I wondered if there's a way of using a double value on GKLeaderboard? It insists that I use int64_t, but I need double values to be used, as the leaderboard is for the fastest time, counting to six decimal points.

答:
Since you need a decimal number down to the millions, one solution would be to simply multiply by 1,000,000 and coerce to an int64_t:

```<code>int64_t intScore = (int64_t)1000000 * doubleScore;
</code>```

Then when you get the score back:

```<code>double doubleScore = (double)intScore / 1000000;
</code>```

Body:
Since you need a decimal number down to the millions, one solution would be to simply multiply by 1,000,000 and coerce to an int64_t:

int64_t intScore = (int64_t)1000000 * doubleScore;

Then when you get the score back:

double doubleScore = (double)intScore / 1000000;


问:
UNION to merge tables has high cost, loses connection to server
I'm trying to create a new table as a UNION of all rows of two existing tables with identical columns:

```<code>CREATE TABLE table3 AS
(SELECT * from table1
UNION
SELECT * from table2);
</code>```

After running for a while, I get "Connection to the server has been lost."
Running EXPLAIN, the operation has quite high cost:

```<code>Unique  (cost=51951688.65..57110689.45 rows=257950040 width=36)
  ->  Sort  (cost=51951688.65..52596563.75 rows=257950040 width=36)
        Sort Key: table1.id, table1.stid, table1.e5, table1.e10, table1.diesel, table1.date, table1.changed
        ->  Append  (cost=0.00..8859500.00 rows=257950040 width=36)
              ->  Seq Scan on gas_prices  (cost=0.00..1282341.56 rows=66285256 width=36)
              ->  Seq Scan on gas_prices_1620  (cost=0.00..3707907.84 rows=191664784 width=36)
JIT:
  Functions: 1
  Options: Inlining true, Optimization true, Expressions true, Deforming true
</code>```

So it's the sorting that's taking up a lot of resources.
I have set memory settings in postgresql.conf higher than default, but I'm only running on a system with 16gb of memory.
I suspect that re-indexing the existing tables could help, however I'm not sure which index to make. There is no private key on either table: No single or combination of column(s) is unique (except all columns at once).

How can I get the query to work? Thanks for your help.

答:
Use UNION ALL instead of UNION.

Best regards,

Bjarni

Body:
I'm trying to create a new table as a UNION of all rows of two existing tables with identical columns:

CREATE TABLE table3 AS
(SELECT * from table1
UNION
SELECT * from table2);

After running for a while, I get "Connection to the server has been lost."
Running EXPLAIN, the operation has quite high cost:

Unique  (cost=51951688.65..57110689.45 rows=257950040 width=36)
  ->  Sort  (cost=51951688.65..52596563.75 rows=257950040 width=36)
        Sort Key: table1.id, table1.stid, table1.e5, table1.e10, table1.diesel, table1.date, table1.changed
        ->  Append  (cost=0.00..8859500.00 rows=257950040 width=36)
              ->  Seq Scan on gas_prices  (cost=0.00..1282341.56 rows=66285256 width=36)
              ->  Seq Scan on gas_prices_1620  (cost=0.00..3707907.84 rows=191664784 width=36)
JIT:
  Functions: 1
  Options: Inlining true, Optimization true, Expressions true, Deforming true

So it's the sorting that's taking up a lot of resources.
I have set memory settings in postgresql.conf higher than default, but I'm only running on a system with 16gb of memory.
I suspect that re-indexing the existing tables could help, however I'm not sure which index to make. There is no private key on either table: No single or combination of column(s) is unique (except all columns at once).

How can I get the query to work? Thanks for your help.


问:
Specify Category specific layout updates without using Magento's administration dashboard
Is there a way to specify a layout update for a specific category (e.g. using category ID) without having to use the administration dashboard, and setting a [Custom Design > Custom Layout Update].

I am sure I can create a module that looks for a category ID and switches the layout based upon that, but I was curious if there was a naming or some other type of convention for layout files that allows for this type of granular control since Zend Framwork sometimes allows such naming conventions.

Also maybe within the catalog.xml file itself there are additional "layouts" that allow such granularity, something more specific than <catalog_category_layered />

答:
In a standard Magento install (1.4.2, but it should apply to the rest), Magento issues the following Layout handles (handles tell Magento which Layout Update XML Fragments to load from the Package Layout)

```<code><default />
<catalog_category_layered_nochildren />
<STORE_default />
<THEME_frontend_default_default />
<catalog_category_view />
<catalog_category_layered />
<CATEGORY_4 />
<customer_logged_out />
</code>```

The following layout handle

```<code><CATEGORY_4 />
</code>```

is generated based on the ID for a category.  This means you should be able to add something like the following to your local.xml, or to a custom layout XML file added via a custom module

```<code><layouts>
    <CATEGORY_4>
        <!-- your UPDATE xml here -->
    </CATEGORY_4>
</layouts>
</code>```

Body:
In a standard Magento install (1.4.2, but it should apply to the rest), Magento issues the following Layout handles (handles tell Magento which Layout Update XML Fragments to load from the Package Layout)

<default />
<catalog_category_layered_nochildren />
<STORE_default />
<THEME_frontend_default_default />
<catalog_category_view />
<catalog_category_layered />
<CATEGORY_4 />
<customer_logged_out />

The following layout handle

<CATEGORY_4 />

is generated based on the ID for a category.  This means you should be able to add something like the following to your local.xml, or to a custom layout XML file added via a custom module

<layouts>
    <CATEGORY_4>
        <!-- your UPDATE xml here -->
    </CATEGORY_4>
</layouts>


问:
How to convert a string (json with scape chars) to dynamic object?
Good day everyone, I'm trying to convert a string that looks like this:

"{\"Estado\":true,\"Token\":\"3D16C8D8-058C-4FA7-AEA2-1A764A083B72\",\"Nombre\":\"Agente COV\"}"

If I do a quick inspection when the code is running, it looks like this:

After applying the following line of code:

```<code>var Datos = JsonConvert.DeserializeObject<dynamic>(Resultado);
</code>```

It returns the object with two curly braces

```<code>{{"Estado": true, "Token": "3D16C8D8-058C-4FA7-AEA2-1A764A083B72", "Nombre": "Agente COV"}}
</code>```

How can I avoid those two curly braces after converting the string to dynamic object?

I need to use it like this at the end:

```<code>var foo = Datos.Token.Value;
</code>```

Thank you very much for your help.

答:
The effects you're seeing (escaped quotes in the string and the braces) are just how the debugger has chosen to display those values.

```<code>"{\"Estado\":true,\"Token\":\"3D16C8D8-058C-4FA7-AEA2-1A764A083B72\",\"Nombre\":\"Agente COV\"}"
</code>```

is actually a string that contains

```<code>{"Estado":true,"Token":"3D16C8D8-058C-4FA7-AEA2-1A764A083B72","Nombre":"Agente COV"}
</code>```

and

```<code>{{"Estado": true, "Token": "3D16C8D8-058C-4FA7-AEA2-1A764A083B72", "Nombre": "Agente COV"}}
</code>```

Is how the debugger has chosen to display the dynamic object with 3 properties with values

Estado - true

Token - "3D16C8D8-058C-4FA7-AEA2-1A764A083B72"

Nombre - "Agente COV"

The simplest way I'd tackle this would be to create a class for the JSON

public class MyObject{
    public bool Estado { get; set; }
    public Guid Token { get; set; }
    public string Nombre { get; set; }
}
```

<p>Then you can use Json.Net to deserialize it.</p>

<pre class="lang-cs prettyprint-override"><code>var json = "{\"Estado\":true,\"Token\":\"3D16C8D8-058C-4FA7-AEA2-1A764A083B72\",\"Nombre\":\"Agente COV\"}";
var myObject = JsonConvert.DeserializeObject<MyObject>(json);
</code>```

Then access the values like myObject.Token etc.

Body:
Good day everyone, I'm trying to convert a string that looks like this:

"{\"Estado\":true,\"Token\":\"3D16C8D8-058C-4FA7-AEA2-1A764A083B72\",\"Nombre\":\"Agente COV\"}"

If I do a quick inspection when the code is running, it looks like this:

After applying the following line of code:

var Datos = JsonConvert.DeserializeObject<dynamic>(Resultado);

It returns the object with two curly braces

{{"Estado": true, "Token": "3D16C8D8-058C-4FA7-AEA2-1A764A083B72", "Nombre": "Agente COV"}}

How can I avoid those two curly braces after converting the string to dynamic object?

I need to use it like this at the end:

var foo = Datos.Token.Value;

Thank you very much for your help.

Body:
The effects you're seeing (escaped quotes in the string and the braces) are just how the debugger has chosen to display those values.

"{\"Estado\":true,\"Token\":\"3D16C8D8-058C-4FA7-AEA2-1A764A083B72\",\"Nombre\":\"Agente COV\"}"

is actually a string that contains

{"Estado":true,"Token":"3D16C8D8-058C-4FA7-AEA2-1A764A083B72","Nombre":"Agente COV"}

and

{{"Estado": true, "Token": "3D16C8D8-058C-4FA7-AEA2-1A764A083B72", "Nombre": "Agente COV"}}

Is how the debugger has chosen to display the dynamic object with 3 properties with values

Estado - true

Token - "3D16C8D8-058C-4FA7-AEA2-1A764A083B72"

Nombre - "Agente COV"

The simplest way I'd tackle this would be to create a class for the JSON

public class MyObject{
    public bool Estado { get; set; }
    public Guid Token { get; set; }
    public string Nombre { get; set; }
}

Then you can use Json.Net to deserialize it.

var json = "{\"Estado\":true,\"Token\":\"3D16C8D8-058C-4FA7-AEA2-1A764A083B72\",\"Nombre\":\"Agente COV\"}";
var myObject = JsonConvert.DeserializeObject<MyObject>(json);

Then access the values like myObject.Token etc.