问:
Pyinstaller executable keeps opening

Background

I am working on face recognition following this link and I would like to build a standalone application using Python. My main.py script looks like the following.

```<code># main.py

# Import packages and other scripts
import tkinter as tk
...

# Some functions
def initialization():
    # OpenCV and sklearn are used here
    ...

def registration():
    # OpenCV, and sklearn are used here
    ...

def face_recognition():
    # OpenCV and sklearn are used here
    ...

# Start the Tkinter GUI
window = tk.Tk()

# Initialize the face recognition model
initialization()

# Input name for registration
tk.Label(window, text = "Name").grid(...)
entry1 = tk.Entry(window)
entry1.grid(row=0, column=1)

# When the button is clicked, different command is executed
tk.Button(window, text='Registration', command=registeration).grid(...)
tk.Button(window, text='Face Recognition', command=face_recognition).grid(...)

window.mainloop()
</code>```

Using python interpret to run the script (python main.py), everything works fine.

Problem

I use Pyinstaller to convert the scripts to a single exe with this command:

```<code>pyinstaller --onefile \
            --windowed \
            --hidden-import sklearn.neighbors.typedefs \
            main.py
</code>```

Then, I have two exe generated. The first one is in dist/main and the second one is in dist/main.app/Contents/MacOS/main

When running the exe, the exe keeps duplicate itself. I display the running process and found this result

```<code>$ ps
PID    TTY    TIME    CMD
...    ...    ...     /path/to/main -B -s -S -E -c from multiprocessing.semaphore_tracker import main:main(8)
...    ...    ...     /path/to/main -B -s -S -E -c from multiprocessing.semaphore_tracker import main:main(8)
...    ...    ...     /path/to/main -B -s -S -E -c from multiprocessing.semaphore_tracker import main:main(7)
...    ...    ...     /path/to/main -B -s -S -E -c from multiprocessing.semaphore_tracker import main:main(7)
...    ...    ...     /path/to/main -B -s -S -E -c from multiprocessing.semaphore_tracker import main:main(8)
</code>```

I have no idea what happens to the exe since I do not import multiprocessing packages in my scripts. Any idea how to fix this problem? Thanks

Update 1

I added a --log-level ERROR when using Pyinstaller and gives this result. Not sure if it is related to my problem.

```<code>Traceback (most recent call last):
  File "<string>", line 2, in <module>
ModuleNotFoundError: No module named 'Crypto.Math'
174598 INFO: MKL libraries found when importing numpy. Adding MKL to binaries
176282 ERROR: Can not find path ./libtbb.dylib (needed by /Users/user/anaconda3/lib/libmkl_tbb_thread.dylib)
</code>```

Update 2

I found out that one of the packages that I am using -- imultis VideoStream involves threading. I guess it is the reason for observing from multiprocessing.semaphore_tracker as shown above even though I do not import multiprocessing explicitly.

Then I come across with this post, suggesting to add multiprocessing.freeze_support().  It can suppress the GUI window from keep duplicating, but the background processes as shown using $ ps still keep duplicating. The problem has not fixed yet.

Update 3 (Issue located but not fix)

After debugging the code for quite a while, it turns out that the causes of this infinite looping is NOT due to the threading of imultis VideoStream (I write another script to test imultis and it is completely OK). But the problem comes from importing sklearn!!! This problem has been reported in GitHub in this link.

This GitHub link also suggest to include multiprocessing.freeze_support(). Moreover one of the responses suggests to import sklearn after multiprocessing.freeze_support() is called. I try it with a simple script but the problem is still here.

Conclusion: sklearn causes the executable keeps opening. But I have no idea why it is the case, and I do not know how to solve it. Any help would be appreciated. Thanks.

答:
This answer does a good job explaining why this happens: https://stackoverflow.com/a/55382641/109525

First try setting this before starting your program:

```<code>export JOBLIB_MULTIPROCESSING=0
</code>```

If it works, you can add a runtime hook to your program to set the environment variable automatically. See: https://pythonhosted.org/PyInstaller/when-things-go-wrong.html#changing-runtime-behavior

Title: Pyinstaller executable keeps opening

Body:
Background

I am working on face recognition following this link and I would like to build a standalone application using Python. My main.py script looks like the following.

# main.py

# Import packages and other scripts
import tkinter as tk
...

# Some functions
def initialization():
    # OpenCV and sklearn are used here
    ...

def registration():
    # OpenCV, and sklearn are used here
    ...

def face_recognition():
    # OpenCV and sklearn are used here
    ...

# Start the Tkinter GUI
window = tk.Tk()

# Initialize the face recognition model
initialization()

# Input name for registration
tk.Label(window, text = "Name").grid(...)
entry1 = tk.Entry(window)
entry1.grid(row=0, column=1)

# When the button is clicked, different command is executed
tk.Button(window, text='Registration', command=registeration).grid(...)
tk.Button(window, text='Face Recognition', command=face_recognition).grid(...)

window.mainloop()

Using python interpret to run the script (python main.py), everything works fine.

Problem

I use Pyinstaller to convert the scripts to a single exe with this command:

pyinstaller --onefile \
            --windowed \
            --hidden-import sklearn.neighbors.typedefs \
            main.py

Then, I have two exe generated. The first one is in dist/main and the second one is in dist/main.app/Contents/MacOS/main

When running the exe, the exe keeps duplicate itself. I display the running process and found this result

$ ps
PID    TTY    TIME    CMD
...    ...    ...     /path/to/main -B -s -S -E -c from multiprocessing.semaphore_tracker import main:main(8)
...    ...    ...     /path/to/main -B -s -S -E -c from multiprocessing.semaphore_tracker import main:main(8)
...    ...    ...     /path/to/main -B -s -S -E -c from multiprocessing.semaphore_tracker import main:main(7)
...    ...    ...     /path/to/main -B -s -S -E -c from multiprocessing.semaphore_tracker import main:main(7)
...    ...    ...     /path/to/main -B -s -S -E -c from multiprocessing.semaphore_tracker import main:main(8)

I have no idea what happens to the exe since I do not import multiprocessing packages in my scripts. Any idea how to fix this problem? Thanks

Update 1

I added a --log-level ERROR when using Pyinstaller and gives this result. Not sure if it is related to my problem.

Traceback (most recent call last):
  File "<string>", line 2, in <module>
ModuleNotFoundError: No module named 'Crypto.Math'
174598 INFO: MKL libraries found when importing numpy. Adding MKL to binaries
176282 ERROR: Can not find path ./libtbb.dylib (needed by /Users/user/anaconda3/lib/libmkl_tbb_thread.dylib)

Update 2

I found out that one of the packages that I am using -- imultis VideoStream involves threading. I guess it is the reason for observing from multiprocessing.semaphore_tracker as shown above even though I do not import multiprocessing explicitly.

Then I come across with this post, suggesting to add multiprocessing.freeze_support().  It can suppress the GUI window from keep duplicating, but the background processes as shown using $ ps still keep duplicating. The problem has not fixed yet.

Update 3 (Issue located but not fix)

After debugging the code for quite a while, it turns out that the causes of this infinite looping is NOT due to the threading of imultis VideoStream (I write another script to test imultis and it is completely OK). But the problem comes from importing sklearn!!! This problem has been reported in GitHub in this link.

This GitHub link also suggest to include multiprocessing.freeze_support(). Moreover one of the responses suggests to import sklearn after multiprocessing.freeze_support() is called. I try it with a simple script but the problem is still here.

Conclusion: sklearn causes the executable keeps opening. But I have no idea why it is the case, and I do not know how to solve it. Any help would be appreciated. Thanks.

Body:
This answer does a good job explaining why this happens: https://stackoverflow.com/a/55382641/109525

First try setting this before starting your program:

export JOBLIB_MULTIPROCESSING=0

If it works, you can add a runtime hook to your program to set the environment variable automatically. See: https://pythonhosted.org/PyInstaller/when-things-go-wrong.html#changing-runtime-behavior


来源: stackexchange

问:
Kubernetes cluster cannot attach and mount automatically created google cloud platform disks to worker nodes
Basically I'm trying to deploy a cluster on GCE via kubeadm with StorageClass supported (without using Google Kubernetes Engine).

Say I deployed a cluster with a master node at Tokyo, and 3 work nodes in Hong Kong, Taiwan and Oregon.

```<code>NAME              STATUS   ROLES    AGE     VERSION
k8s-node-hk       Ready    <none>   3h35m   v1.14.2
k8s-node-master   Ready    master   3h49m   v1.14.2
k8s-node-oregon   Ready    <none>   3h33m   v1.14.2
k8s-node-tw       Ready    <none>   3h34m   v1.14.2
</code>```

Kube-controller-manager and kubelet both started with cloud-provider=gce, and now I can apply StorageClass and PersistentVolumeClaim then get disks created automatically (say a disk in Taiwan) on GCP and get PV and PVC bound.

kubectl get pvc:

```<code>NAME      STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   AGE
eth-pvc   Bound    pvc-bf35e3c9-81e2-11e9-8926-42010a920002   10Gi       RWO            slow           137m
</code>```

kubectl get pv

```<code>NAME                                       CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM             STORAGECLASS   REASON   AGE
pvc-bf35e3c9-81e2-11e9-8926-42010a920002   10Gi       RWO            Delete           Bound    default/eth-pvc   slow                    137m
</code>```

However, kube-controller-manager cannot find the Taiwan node and mount the disk to the node in same zone, and it logged (we can see the zone asia-northeast1-a is not correct):

```<code>I0529 07:25:46.366500       1 reconciler.go:288] attacherDetacher.AttachVolume started for volume "pvc-bf35e3c9-81e2-11e9-8926-42010a920002" (UniqueName: "kubernetes.io/gce-pd/kubernetes-dynamic-pvc-bf35e3c9-81e2-11e9-8926-42010a920002") from node "k8s-node-tokyo"
E0529 07:25:47.296824       1 attacher.go:102] Error attaching PD "kubernetes-dynamic-pvc-bf35e3c9-81e2-11e9-8926-42010a920002" to node "k8s-node-tokyo": GCE persistent disk not found: diskName="kubernetes-dynamic-pvc-bf35e3c9-81e2-11e9-8926-42010a920002" zone="asia-northeast1-a"
</code>```

The kubelet on each node started with --cloud-provider=gce, but I didn't find how to configure the zone. And when I checked kubelet's log, I find this flag is already deprecated on kubernetes v1.14.2 (the latest in May 2019).

```<code>May 29 04:36:03 k8s-node-tw kubelet[29971]: I0529 04:36:03.623704   29971 server.go:417] Version: v1.14.2
May 29 04:36:03 k8s-node-tw kubelet[29971]: W0529 04:36:03.624039   29971 plugins.go:118] WARNING: gce built-in cloud provider is now deprecated. The GCE provider is deprecated and will be removed in a future release
</code>```

However, kubelet annotated k8s-node-tw node with the correct zone and region:

```<code>May 29 04:36:05 k8s-node-tw kubelet[29971]: I0529 04:36:05.157665   29971 kubelet_node_status.go:331] Adding node label from cloud provider: beta.kubernetes.io/instance-type=n1-standard-1
May 29 04:36:05 k8s-node-tw kubelet[29971]: I0529 04:36:05.158093   29971 kubelet_node_status.go:342] Adding node label from cloud provider: failure-domain.beta.kubernetes.io/zone=asia-east1-a
May 29 04:36:05 k8s-node-tw kubelet[29971]: I0529 04:36:05.158201   29971 kubelet_node_status.go:346] Adding node label from cloud provider: failure-domain.beta.kubernetes.io/region=asia-east1
</code>```

Thanks for reading here. My question is:

If it's possible, how can I configure kubelet or kube-controller-manager correctly to make it support GCP's storage class and the created disks attached and mounted successfully?

==================K8s config files======================

Deployment (related part):

```<code>  volumes:
  - name: data
    persistentVolumeClaim:
      claimName: eth-pvc
  - name: config
    configMap:
      name: {{ template "ethereum.fullname" . }}-geth-config
  - name: account
    secret:
      secretName: {{ template "ethereum.fullname" . }}-geth-account
</code>```

PVC:

```<code>apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: eth-pvc
spec:
  storageClassName: slow
  resources:
    requests:
      storage: 10Gi
  accessModes:
    - ReadWriteOnce
</code>```

SC:

```<code>apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: slow
provisioner: kubernetes.io/gce-pd
parameters:
  type: pd-standard
  replication-type: none
  zone: asia-east1-a
</code>```

答:
After several days' research, I found that the reason is:

Master node is in asia-northeast1-a (Tokyo)

Worker nodes are in asia-east1-a (Taiwan) and other zones

cloud-provider-gcp only search the zone in one region (normally the master node's zone, but you can specify it by setting local-zone in the cloud config file), which means it can only support one zone or multiple zones in one region by default

Conclusion:

In order to support multiple zones among multiple regions, we need to modify the gce provider code of configuration, like add another field to configure which zones should be searched.

==========================UPDATE=========================

I modified the k8s code to add a extra-zones config field like this diff on github to make it work on my use case.

ContentLicense: CC BY-SA 4.0

Body:
Basically I'm trying to deploy a cluster on GCE via kubeadm with StorageClass supported (without using Google Kubernetes Engine).

Say I deployed a cluster with a master node at Tokyo, and 3 work nodes in Hong Kong, Taiwan and Oregon.

NAME              STATUS   ROLES    AGE     VERSION
k8s-node-hk       Ready    <none>   3h35m   v1.14.2
k8s-node-master   Ready    master   3h49m   v1.14.2
k8s-node-oregon   Ready    <none>   3h33m   v1.14.2
k8s-node-tw       Ready    <none>   3h34m   v1.14.2

Kube-controller-manager and kubelet both started with cloud-provider=gce, and now I can apply StorageClass and PersistentVolumeClaim then get disks created automatically (say a disk in Taiwan) on GCP and get PV and PVC bound.

kubectl get pvc:

NAME      STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   AGE
eth-pvc   Bound    pvc-bf35e3c9-81e2-11e9-8926-42010a920002   10Gi       RWO            slow           137m

kubectl get pv

NAME                                       CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM             STORAGECLASS   REASON   AGE
pvc-bf35e3c9-81e2-11e9-8926-42010a920002   10Gi       RWO            Delete           Bound    default/eth-pvc   slow                    137m

However, kube-controller-manager cannot find the Taiwan node and mount the disk to the node in same zone, and it logged (we can see the zone asia-northeast1-a is not correct):

I0529 07:25:46.366500       1 reconciler.go:288] attacherDetacher.AttachVolume started for volume "pvc-bf35e3c9-81e2-11e9-8926-42010a920002" (UniqueName: "kubernetes.io/gce-pd/kubernetes-dynamic-pvc-bf35e3c9-81e2-11e9-8926-42010a920002") from node "k8s-node-tokyo"
E0529 07:25:47.296824       1 attacher.go:102] Error attaching PD "kubernetes-dynamic-pvc-bf35e3c9-81e2-11e9-8926-42010a920002" to node "k8s-node-tokyo": GCE persistent disk not found: diskName="kubernetes-dynamic-pvc-bf35e3c9-81e2-11e9-8926-42010a920002" zone="asia-northeast1-a"

The kubelet on each node started with --cloud-provider=gce, but I didn't find how to configure the zone. And when I checked kubelet's log, I find this flag is already deprecated on kubernetes v1.14.2 (the latest in May 2019).

May 29 04:36:03 k8s-node-tw kubelet[29971]: I0529 04:36:03.623704   29971 server.go:417] Version: v1.14.2
May 29 04:36:03 k8s-node-tw kubelet[29971]: W0529 04:36:03.624039   29971 plugins.go:118] WARNING: gce built-in cloud provider is now deprecated. The GCE provider is deprecated and will be removed in a future release

However, kubelet annotated k8s-node-tw node with the correct zone and region:

May 29 04:36:05 k8s-node-tw kubelet[29971]: I0529 04:36:05.157665   29971 kubelet_node_status.go:331] Adding node label from cloud provider: beta.kubernetes.io/instance-type=n1-standard-1
May 29 04:36:05 k8s-node-tw kubelet[29971]: I0529 04:36:05.158093   29971 kubelet_node_status.go:342] Adding node label from cloud provider: failure-domain.beta.kubernetes.io/zone=asia-east1-a
May 29 04:36:05 k8s-node-tw kubelet[29971]: I0529 04:36:05.158201   29971 kubelet_node_status.go:346] Adding node label from cloud provider: failure-domain.beta.kubernetes.io/region=asia-east1

Thanks for reading here. My question is:

If it's possible, how can I configure kubelet or kube-controller-manager correctly to make it support GCP's storage class and the created disks attached and mounted successfully?

==================K8s config files======================

Deployment (related part):

  volumes:
  - name: data
    persistentVolumeClaim:
      claimName: eth-pvc
  - name: config
    configMap:
      name: {{ template "ethereum.fullname" . }}-geth-config
  - name: account
    secret:
      secretName: {{ template "ethereum.fullname" . }}-geth-account

PVC:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: eth-pvc
spec:
  storageClassName: slow
  resources:
    requests:
      storage: 10Gi
  accessModes:
    - ReadWriteOnce

SC:

apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: slow
provisioner: kubernetes.io/gce-pd
parameters:
  type: pd-standard
  replication-type: none
  zone: asia-east1-a


问:
instrumentation test for Room
"I have a room database and it works normally, I want to test it now but my test doesn't work and I don't see any assert when its run.
in this code Im adding a new record and initializing it, then assert if record is added"

```<code>@RunWith(AndroidJUnit4.class)
public class PatientDaoTest {
private PatientDao patientDao;
private PatientDatabase db;
public int patient_db_ID;
public int bed_number;

@Before
public void createDb(){
Context context = ApplicationProvider.getApplicationContext();
db = Room.inMemoryDatabaseBuilder(context, PatientDatabase.class).buil();
patientDao = db.patientDao();}

@After
public void closeDb() throws IOException {
db.close();
}

@Test
public void InsertNewPatient() throws Exception {
PatientRecordEntity newPatient = new PatientRecordEntity();
newPatient.setPatient_db_ID("123456");
newPatient.setPatient_race("chines");
newPatient.setBed_number("123");
newPatient.setReal_bed_number("1234");
newPatient.setRegister_date("5/28/2019");
newPatient.setRegister_time("3:35:02");
newPatient.setPatient_age(12);
newPatient.setPatient_gender(1);

boolean pin = false;
int newRowId = 0;
newRowId = (int) db.patientDao().addNewPatient(newPatient);
if(newRowId == 0){
pin= true;
}

assertTrue("test is true",pin);
}}
</code>```

"It s my Dao query:"

```<code>@Insert
long addNewPatient(PatientRecordEntity newPatient);
</code>```

"and this is that function that use this query of dao. I don't no if my @test is true or not"

```<code>public static int AddPatientToDB() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String formatedDate = sdf.format(new Date());
sdf = new SimpleDateFormat("HH-mm-ssZ", Locale.getDefault());
String formatedTime = sdf.format(new Date());
PatientRecordEntity newPatient = new PatientRecordEntity();
newPatient.setBed_number(bed_no);
newPatient.setPatient_db_ID(patient_id);
newPatient.setRegister_time(formatedTime);
newPatient.setRegister_date(formatedDate);
int newRowId = 0;
newRowId = (int) pDatabase.patientDao().addNewPatient(newPatient);
current_patient_record_entity = newPatient;
current_patient_record_entity.pid = newRowId;
current_patient_record_entity.sessionID = Repo.currentSessionID;
current_wound_record_entity = new WoundRecordEntity();
current_wound_record_entity.patient_key = (int) newRowId;
current_sample_no = newRowId;

return newRowId;
}
</code>```

答:
You have 3 choices to run your test

1) Run in menu -> Run -> Сhoose your test instead of app

2) Alt + Shift + F10. It will open run menu

3) Click on your test in this menu

If you want to run all tests of your_project right click on your "test" or "androidTest" folder and choose Run tests in "your_project"

Title: instrumentation test for Room

Body:
"I have a room database and it works normally, I want to test it now but my test doesn't work and I don't see any assert when its run.
in this code Im adding a new record and initializing it, then assert if record is added"

@RunWith(AndroidJUnit4.class)
public class PatientDaoTest {
private PatientDao patientDao;
private PatientDatabase db;
public int patient_db_ID;
public int bed_number;

@Before
public void createDb(){
Context context = ApplicationProvider.getApplicationContext();
db = Room.inMemoryDatabaseBuilder(context, PatientDatabase.class).buil();
patientDao = db.patientDao();}

@After
public void closeDb() throws IOException {
db.close();
}

@Test
public void InsertNewPatient() throws Exception {
PatientRecordEntity newPatient = new PatientRecordEntity();
newPatient.setPatient_db_ID("123456");
newPatient.setPatient_race("chines");
newPatient.setBed_number("123");
newPatient.setReal_bed_number("1234");
newPatient.setRegister_date("5/28/2019");
newPatient.setRegister_time("3:35:02");
newPatient.setPatient_age(12);
newPatient.setPatient_gender(1);

boolean pin = false;
int newRowId = 0;
newRowId = (int) db.patientDao().addNewPatient(newPatient);
if(newRowId == 0){
pin= true;
}

assertTrue("test is true",pin);
}}

"It s my Dao query:"

@Insert
long addNewPatient(PatientRecordEntity newPatient);

"and this is that function that use this query of dao. I don't no if my @test is true or not"

public static int AddPatientToDB() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String formatedDate = sdf.format(new Date());
sdf = new SimpleDateFormat("HH-mm-ssZ", Locale.getDefault());
String formatedTime = sdf.format(new Date());
PatientRecordEntity newPatient = new PatientRecordEntity();
newPatient.setBed_number(bed_no);
newPatient.setPatient_db_ID(patient_id);
newPatient.setRegister_time(formatedTime);
newPatient.setRegister_date(formatedDate);
int newRowId = 0;
newRowId = (int) pDatabase.patientDao().addNewPatient(newPatient);
current_patient_record_entity = newPatient;
current_patient_record_entity.pid = newRowId;
current_patient_record_entity.sessionID = Repo.currentSessionID;
current_wound_record_entity = new WoundRecordEntity();
current_wound_record_entity.patient_key = (int) newRowId;
current_sample_no = newRowId;

return newRowId;
}


问:
Can service principal with owner access to a subscription access the active directory
I have an azure service principal with owner access that is able to add contributors at the resource or resource group level.
But when i use the same service principal to access Azure AD it fails and throws a 403 forbidden error.
Is it possible that a service principal with owner access to a subscription fails to access azure ad in the same subscription?</p>

答:
The subscription is under the azure ad tenant, the owner role is an RBAC role which manages the resources in the subscription, not the azure ad tenant.

For more details about the roles, refer to Classic subscription administrator roles, Azure RBAC roles, and Azure AD administrator roles.

If you want to fix the error to call the Microsoft graph to list users/get a user in the tenant, navigate to your AD App in the App registrations in the prortal -> API permissions -> Add a permission -> select Microsoft Graph -> Application permissions -> User.Read.All -> click Add permissions -> click Grant admin consent for xxx, then it will work.


问:
Set iframe height from inside body
I have Iframe created dynamically on click, and the src file loaded by iframe contains huge dropdown list, I set iframe height dynamically using this method, now inside the iframe if the user click on dropdown the values are not shown completely

So, onclicking the dropdowns I will set the iframe height to show all dropdown values by calling a function

```<code><a href="javascript(0)" id="dp1" onclick="setIframeHeight(this.id)">sources</a>
</code>```

my javsctip looks like :

```<code>function setIframeHeight(no){
    var iFrameID = window.frameElement.id; // diplays exact id of iframe
        window.parent.document.getElementById(iFrameID).height  = '1500px';
}

/* as i get iframe id, how to set the height of the iframe. */
</code>```

答:
It should be

```<code>window.parent.document.getElementById(iFrameID).style.height  = '1500px';
</code>```

However, if you are trying to set the iFrame height from within the guest content AND guest_origin !== host_origin, you will have to run a function of the host to make the frame adjustment work.

Title: Set iframe height from inside body

Body:
I have Iframe created dynamically on click, and the src file loaded by iframe contains huge dropdown list, I set iframe height dynamically using this method, now inside the iframe if the user click on dropdown the values are not shown completely

So, onclicking the dropdowns I will set the iframe height to show all dropdown values by calling a function

sources

my javsctip looks like :

function setIframeHeight(no){
    var iFrameID = window.frameElement.id; // diplays exact id of iframe
        window.parent.document.getElementById(iFrameID).height  = '1500px';
}

/* as i get iframe id, how to set the height of the iframe. */

Body:
It should be

window.parent.document.getElementById(iFrameID).style.height  = '1500px';

However, if you are trying to set the iFrame height from within the guest content AND guest_origin !== host_origin, you will have to run a function of the host to make the frame adjustment work.


问:
Validating password with validates_format_of
EDIT: I realized the comments about there not being a difference with :save already covered were correct, and was able to work through some errors. However, it still appears the regex validation is failing for :password.

I'm a little confused, and think the problem might be related to there being only :password_digest in the table itself, while we use password and password_confirmation as attributes in the model. But I'm also guessing Rails has this all worked out and takes care of everything with the has_secure_password function.

validates_format_of :password, :with => /\A[a-zA-Z]\z/, :on => :create, :update fails with the string password.

Obviously, this doesn't make sense and matches fine in the console (using =~ or .match(). Also notice if I set allow_nil: true for :password other tests involving the user start failing (which doesn't make sense, as the password should never be nil anyways).

答:
According to rails docs

The default behavior for all the built-in validation helpers is to be run on save (both when you're creating a new record and when you're updating it). If you want to change it, you can use on: :create to run the validation only when a new record is created or on: :update to run the validation only when a record is updated.

So, you should not use :on option in your validation


问:
Which OpenGL version is most stable and currently used?
I've been thinking of making an additional wrapper for my project to use OpenGL rather then Allegro. I was not sure which OpenGL version to go for since I know that some computers cannot run recent versions such as v4.4. Also, I need a version which compiles no problem in Linux, Windows, Mac.</p>

答:
Then you need to use OpenGL 1.1, and use needed (and supported) functions through the use of wglGetProcAddress (on windows) or glXGetProcAddress (on linux).

Instead of using those two functions, you can use GLEW library, which does that for you and is cross platform.

ContentLicense: CC BY-SA 3.0


问:
How to update a database using DataGrid C# WPF?
I want to update a database (SQLite) with the dataGrid.
I can change values in the dataGrid but changes don't apply to the database
that why I want to add a button "save" to save all changes applied in the dataGrid,

I searched about the problem but I couldn't find an answer

this is my C# code to fill the DataGrid:

SQLiteConnection sQLiteConnection = new SQLiteConnection("Data source = dataSet.db ; version = 3 ;");
        SQLiteCommand sQLiteCommand;
        SQLiteDataAdapter sQLiteDataAdapter;
        System.Data.DataTable dataTable = new System.Data.DataTable("Naamaa");
        SQLiteCommandBuilder cmd;
        DataSet ds;
        public ManipulateData(string wilaya, int theme)
        {
            InitializeComponent();

            try
            {
                sQLiteConnection.Open();
                sQLiteCommand = new SQLiteCommand(sQLiteConnection);
                sQLiteCommand.CommandText = "SELECT * FROM " + wilaya + " ;";
                sQLiteCommand.ExecuteNonQuery();
                sQLiteDataAdapter = new SQLiteDataAdapter(sQLiteCommand);
                sQLiteDataAdapter.Fill(dataTable);

                McDataGrid.ItemsSource = dataTable.DefaultView;

            }catch
            {
                MessageBox.Show("Error");
            }
        }
```

<p>and this is the xaml code :</p>

<pre class="lang-xml prettyprint-override"><code><Grid Background="White">
        <DataGrid x:Name="McDataGrid"  />
</Grid>
</code>```

答:
I'm working on something quite similar at the moment, only that I'm using Postgres.

One easy way to do this is set the DataGridView.ReadOnly property to true, then when user selects a row in DataGridView, you can launch a Windows Form with all the data in from that selected row and a "Save" button to update data in DataBase. Then from that button you only need to launch an update query to database with data collected from the form.

If you want to modify data on the DataGridView itself, things get more complex as you need to keep track of which rows have been edited on DataGridView (unless you don't care about optimization and can just do an update for every single row, no matter if it has been edited or not). You can use a list of DataGridViewRow for all modified rows.

Was that understandable? Not very used to write english, specially on quite complex matters.

Body:
I want to update a database (SQLite) with the dataGrid.
I can change values in the dataGrid but changes don't apply to the database
that why I want to add a button "save" to save all changes applied in the dataGrid,

I searched about the problem but I couldn't find an answer

this is my C# code to fill the DataGrid:

SQLiteConnection sQLiteConnection = new SQLiteConnection("Data source = dataSet.db ; version = 3 ;");
        SQLiteCommand sQLiteCommand;
        SQLiteDataAdapter sQLiteDataAdapter;
        System.Data.DataTable dataTable = new System.Data.DataTable("Naamaa");
        SQLiteCommandBuilder cmd;
        DataSet ds;
        public ManipulateData(string wilaya, int theme)
        {
            InitializeComponent();

            try
            {
                sQLiteConnection.Open();
                sQLiteCommand = new SQLiteCommand(sQLiteConnection);
                sQLiteCommand.CommandText = "SELECT * FROM " + wilaya + " ;";
                sQLiteCommand.ExecuteNonQuery();
                sQLiteDataAdapter = new SQLiteDataAdapter(sQLiteCommand);
                sQLiteDataAdapter.Fill(dataTable);

                McDataGrid.ItemsSource = dataTable.DefaultView;

            }catch
            {
                MessageBox.Show("Error");
            }
        }

and this is the xaml code :

<Grid Background="White">
        <DataGrid x:Name="McDataGrid"  />
</Grid>


问:
I have a two node js servers. second server is for the socket connection. How do I establish a connection between these two servers?
I'm setting up another nodejs server for the socketio, which is index.js. so I have two servers one is app.js and other one is index.js. so how do i establish a connection between these two servers?</p>

答:
If I correctly get what you wanted to do. You wanted to separate the file of the recieving of socket. Here's my code below.

on your app.js

```<code>var app = Express();
var server = require('http').createServer(app);
var io = SocketIo.listen(server);

server.listen(function(){
   require('/path/of/your/index.js')(io);
})
</code>```

and on your index.js

```<code>module.exports = function(io){
  io.on('connection', function(socket){
    *your codes here*
  });
}
</code>```

Body:
If I correctly get what you wanted to do. You wanted to separate the file of the recieving of socket. Here's my code below.

on your app.js

var app = Express();
var server = require('http').createServer(app);
var io = SocketIo.listen(server);

server.listen(function(){
   require('/path/of/your/index.js')(io);
})

and on your index.js

module.exports = function(io){
  io.on('connection', function(socket){
    *your codes here*
  });
}


问:
azure rest api file creation .failed to authenticate the request. formed correctly including the signature. Response code : 403 this error
```<code>import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import com.microsoft.azure.storage.core.Base64;

public class TestCloudStorage {
private static final String account = "account-name";
private static final String key = "key";

 public static void main(String args[]) throws Exception {
  createFile();
 }

 public static void createFile() throws Exception {
  System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
  String urlString = "https://" + account + ".file.core.windows.net/myfileshare/mydirectory/myfile";
  System.setProperty("https.proxyHost", "proxy");
  System.setProperty("https.proxyPort", "8080");
  HttpURLConnection connection = (HttpURLConnection)(new URL(urlString)).openConnection();
  getFileRq(connection, account, key);
  connection.connect();
  System.out.println("Response message : " + connection.getResponseMessage());
  System.out.println("Response code : " + connection.getResponseCode());
  BufferedReader br = null;

  if (connection.getResponseCode() != 200 && connection.getResponseCode() != 201) {
   br = new BufferedReader(new InputStreamReader((connection.getErrorStream())));
  }

  else {
   br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
  }
  System.out.println("Response body : " + br.readLine());
 }

 public static void getFileRq(HttpURLConnection request, String account, String key) throws Exception {
  SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
  fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
  String date = fmt.format(Calendar.getInstance().getTime()) + " GMT";
  String stringToSign = "PUT" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\nx-ms-content-length:1024" + "\nx-ms-date:" + date + "\nx-ms-type:file" + "\nx-ms-version:" + "2015-02-21" + +"/" + account + request.getURL().getPath();
  System.out.println("stringToSign : " + stringToSign);
  String auth = getAuthenticationString(stringToSign);
  System.out.println(auth);
  request.setRequestMethod("PUT");
  request.setRequestProperty("x-ms-version", "2015-02-21");
  request.setRequestProperty("x-ms-date", date);
  request.setRequestProperty("Content-Type", "application/octet-stream");
  request.setRequestProperty("x-ms-content-length", "1024");
  request.setRequestProperty("Authorization", auth);
  request.setRequestProperty("x-ms-type", "file");
  request.setRequestProperty("Content-Length", "0");
 }

 private static String getAuthenticationString(String stringToSign) throws Exception {
  Mac mac = Mac.getInstance("HmacSHA256");
  mac.init(new SecretKeySpec(Base64.decode(key), "HmacSHA256"));
  String authKey = new String(Base64.encode(mac.doFinal(stringToSign.getBytes("UTF-8"))));
  String auth = "SharedKey " + account + ":" + authKey;
  return auth;
 }
}
</code>```

答:
I believe the reason you're getting this error is because you're specifying Content-Type with application/octet-stream value in your request header but not in your stringToSign. Please change your stringToSign to something like:

```<code>String stringToSign = "PUT" + "\n" + "\n" + "\n" + "\n" + "\n" + "application/octet-stream\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\nx-ms-content-length:1024" + "\nx-ms-date:" + date + "\nx-ms-type:file" + "\nx-ms-version:" + "2015-02-21" + +"/" + account + request.getURL().getPath();
</code>```

or you could remove Content-Type from your request headers as by default the content type would be application/octet-stream.

UPDATE

I also noticed a missing new line character after 2015-02-21 (value of x-ms-version). Can you add that?

```<code>String stringToSign = "PUT" + "\n" + "\n" + "\n" + "\n" + "\n" + "application/octet-stream\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\nx-ms-content-length:1024" + "\nx-ms-date:" + date + "\nx-ms-type:file" + "\nx-ms-version:" + "2015-02-21" + "\n/" + account + request.getURL().getPath();
</code>```

Body:
I believe the reason you're getting this error is because you're specifying Content-Type with application/octet-stream value in your request header but not in your stringToSign. Please change your stringToSign to something like:

String stringToSign = "PUT" + "\n" + "\n" + "\n" + "\n" + "\n" + "application/octet-stream\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\nx-ms-content-length:1024" + "\nx-ms-date:" + date + "\nx-ms-type:file" + "\nx-ms-version:" + "2015-02-21" + +"/" + account + request.getURL().getPath();

or you could remove Content-Type from your request headers as by default the content type would be application/octet-stream.

UPDATE

I also noticed a missing new line character after 2015-02-21 (value of x-ms-version). Can you add that?

String stringToSign = "PUT" + "\n" + "\n" + "\n" + "\n" + "\n" + "application/octet-stream\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\nx-ms-content-length:1024" + "\nx-ms-date:" + date + "\nx-ms-type:file" + "\nx-ms-version:" + "2015-02-21" + "\n/" + account + request.getURL().getPath();


问:
Conditional If Statement applied to dataframe
I am trying to iterate in a pythonic way (i.e. without a loop) through a dataframe in order to create a new columns based on whether the condition was met. In particular, given a dataframe of daily returns, I would like to create a new column that tells me whether either an upper limit or lower limit was crossed (limit is symmetric, but stock specific, so each row might have a different limit, called std in the df below) , something like this:

```<code>import pandas as pd
dict = [
        {'ticker':'jpm','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{ 'ticker':'ge','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'fb', 'date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'aapl', 'date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'msft','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'amzn','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'jpm','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'ge', 'date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'fb','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'aapl','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'msft','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'amzn','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'}
]
df = pd.DataFrame(dict)
df['date']      = pd.to_datetime(df1['date'])
df=df.set_index(['date','ticker'], drop=True)
</code>```

That should be transformed, such that I obtain a new column which contains the respective day's return, if the upper/lower threshold was crossed, if it wasn't crossed, it should just contain the last day's return (so returns2).

```<code>dict2 = [
        {'ticker':'jpm','date': '2016-11-28','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{ 'ticker':'ge','date': '2016-11-28','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'fb', 'date': '2016-11-28','returns': '0.05','returns2': '-0.3','std': '0.1','sl': '-0.3'},
{'ticker':'aapl', 'date': '2016-11-28','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'msft','date': '2016-11-28','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'amzn','date': '2016-11-28','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'jpm','date': '2016-11-29','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'ge', 'date': '2016-11-29','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'fb','date': '2016-11-29','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'aapl','date': '2016-11-29','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'msft','date': '2016-11-29','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'amzn','date': '2016-11-29','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'}
]
df2 = pd.DataFrame(dict2)
df2['date']      = pd.to_datetime(df2['date'])
df2=df2.set_index(['date','ticker'], drop=False)
</code>```

I am trying to keep this flexible (so it works for more than just 2 columns with returns) and efficient (so that it works on very large dfs.

Can anyone suggest an approach?

Body:
I am trying to iterate in a pythonic way (i.e. without a loop) through a dataframe in order to create a new columns based on whether the condition was met. In particular, given a dataframe of daily returns, I would like to create a new column that tells me whether either an upper limit or lower limit was crossed (limit is symmetric, but stock specific, so each row might have a different limit, called std in the df below) , something like this:

import pandas as pd
dict = [
        {'ticker':'jpm','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{ 'ticker':'ge','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'fb', 'date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'aapl', 'date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'msft','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'amzn','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'jpm','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'ge', 'date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'fb','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'aapl','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'msft','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'amzn','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'}
]
df = pd.DataFrame(dict)
df['date']      = pd.to_datetime(df1['date'])
df=df.set_index(['date','ticker'], drop=True)

That should be transformed, such that I obtain a new column which contains the respective day's return, if the upper/lower threshold was crossed, if it wasn't crossed, it should just contain the last day's return (so returns2).

dict2 = [
        {'ticker':'jpm','date': '2016-11-28','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{ 'ticker':'ge','date': '2016-11-28','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'fb', 'date': '2016-11-28','returns': '0.05','returns2': '-0.3','std': '0.1','sl': '-0.3'},
{'ticker':'aapl', 'date': '2016-11-28','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'msft','date': '2016-11-28','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'amzn','date': '2016-11-28','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'jpm','date': '2016-11-29','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'ge', 'date': '2016-11-29','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'fb','date': '2016-11-29','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'aapl','date': '2016-11-29','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'msft','date': '2016-11-29','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'amzn','date': '2016-11-29','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'}
]
df2 = pd.DataFrame(dict2)
df2['date']      = pd.to_datetime(df2['date'])
df2=df2.set_index(['date','ticker'], drop=False)

I am trying to keep this flexible (so it works for more than just 2 columns with returns) and efficient (so that it works on very large dfs.

Can anyone suggest an approach?

Body:
I would use numpy:

dict1 = [
        {'ticker':'jpm','date': '2016-11-28','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{ 'ticker':'ge','date': '2016-11-28','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'fb', 'date': '2016-11-28','returns': '0.05','returns2': '-0.3','std': '0.1','sl': '-0.3'},
{'ticker':'aapl', 'date': '2016-11-28','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'msft','date': '2016-11-28','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'amzn','date': '2016-11-28','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'jpm','date': '2016-11-29','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'ge', 'date': '2016-11-29','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'fb','date': '2016-11-29','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'aapl','date': '2016-11-29','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'msft','date': '2016-11-29','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'amzn','date': '2016-11-29','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'}
]
df = pd.DataFrame(dict1)
df['date']      = pd.to_datetime(df['date'])
df=df.set_index(['date','ticker'], drop=True)

ret1 = pd.to_numeric(df.returns).values
ret2 =  pd.to_numeric(df.returns2).values
std =  pd.to_numeric(df['std']).values

mask = np.abs(ret1) >= std
out = mask*ret1 + (1-mask)*ret2
print(out)
# prints [ 0.2 -0.2 -0.3 -0.2  0.2 -0.2  0.2 -0.2  0.2 -0.2  0.2 -0.2]

#then just add the column to df:
df['my_out'] = pd.DataFrame(out, index=df.index)


问:
PyCharm won't find pytz
While I'm SURE pytz is installed in my virtualenv, as well as I'm SURE that my PyCharm's project is using the said virtualenv, the IDE is constantly complaining:

And when I check in the virtualenv:

```<code>(my-project-venv)anto@~/d/m/myproject$ pip freeze | grep pytz
pytz==2014.4
(my-project-venv)anto@~/d/m/myproject$ python -c "import pytz; print pytz"
<module 'pytz' from '/home/anto/.virtualenvs/my-project-venv/local/lib/python2.7/site-packages/pytz/__init__.pyc'>
</code>```

What am I missing?

答: I had the issue resolved by keeping my virtualenv outside my working project folder. Im not sure why it resolved the issue but it did miraculously.</p>

Title: PyCharm won't find pytz

Body:
While I'm SURE pytz is installed in my virtualenv, as well as I'm SURE that my PyCharm's project is using the said virtualenv, the IDE is constantly complaining:

And when I check in the virtualenv:

(my-project-venv)anto@~/d/m/myproject$ pip freeze | grep pytz
pytz==2014.4
(my-project-venv)anto@~/d/m/myproject$ python -c "import pytz; print pytz"
<module 'pytz' from '/home/anto/.virtualenvs/my-project-venv/local/lib/python2.7/site-packages/pytz/__init__.pyc'>

What am I missing?


问:
How to change the color of spinner and its arrow in android studio
I want to add a color to the spinner as well as a color to the arrow of spinner how do I do this in android studio without adding a dependency</p>

答:
I got solution for this, Create a new xml spinner_style.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<TextView
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:textColor="@color/Black" />
</code>```

And fix this layout as your spinner style in your activity:

```<code> ArrayAdapter<String> genderAdapter = new ArrayAdapter<String> (getActivity(), R.layout.spinner_style, gender_spinner);
</code>```

Body:
I got solution for this, Create a new xml spinner_style.xml

<?xml version="1.0" encoding="UTF-8"?>
<TextView
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:textColor="@color/Black" />

And fix this layout as your spinner style in your activity:

 ArrayAdapter<String> genderAdapter = new ArrayAdapter<String> (getActivity(), R.layout.spinner_style, gender_spinner);


问:
Selecting a QListWidgetItem when adding it
I have a QListWidget in a Form with a QListWidgetItem displaying "Add new". When I click on it, I'd like a serie of things to happen:

A QInputDialog::getText asks for the content of the new item.

A new item is added to the list with the given text.

The list is sorted, except for the "Add new" that stays at the end (this is done by removing the "Add new" item, sorting, and adding the removed item again).

The new item is selected.

That last part is the one I'm having trouble. I've tried many different approaches, all leading to the same result: the item I want selected has a dashed border and it understood as selected (by ui->list->selectedItems() for example), but the selection color stays on the last item before the "Add new".

What I tried

item->setSelected(true);

ui->list->setCurrentItem(item);

ui->list->setCurrentRow(ui->list->row(item);

What I noticed

When the debugger is on with a breakpoint that slowly goes through those steps, I notice everything seems to work nicely, but the UI isn't updated before the function I'm calling is done.

Also, when I want to select a given item from the list from a slot called by another button click, it works correctly with item->setSelected(true); (and the others too).

My guess: I can't select the item in the same function I add it because I can't graphically select something that isn't there yet.

Any guess on how to achieve this?

Note

If you're experiencing the same problem, please read the comment on the selected answer, it was actually a signal problem!

答:
If you can select item from regular slot so just emit dummy signal from very short timer. Like this</p>

```<code>//add item
//...
QTimer::singleShot(1, this, SLOT(MySlotForSelectItem())); // 1 ms timer

MainWindow::MySlotForSelectItem()
{
     //select item
}
</code>```

Body:
If you can select item from regular slot so just emit dummy signal from very short timer. Like this

//add item
//...
QTimer::singleShot(1, this, SLOT(MySlotForSelectItem())); // 1 ms timer

MainWindow::MySlotForSelectItem()
{
     //select item
}


问:
Given a managed reference to a struct, how to obtain a managed reference to a field at offset?
I am trying to implement fixed size arrays in C#, that are parametrized by hacky type-level numerics. See GitHub

I want to implement a method, that would work like this:

```<code>static ref T Ref(this ref TContainer container, int index)
  where T: unmanaged
  where TContainer: unmanaged
  => ref container[index];
</code>```

Now the problem is: I know, that TContainer internally consists of N fields of type T. But it does not actually implement the indexing operation (or any interface whatsoever).

What I can do is:

```<code>CheckIndex(index);
fixed (TContainer* self = &container) {
    T* data = (T*)self;
    return ref data[index];
}
</code>```

This compiles with unsafe, but I have two questions:

Will the lifetime of the managed reference retrieved like this be tracked properly?

Does use of fixed in this context have any performance cost? (e.g. GC pinning, aliasing issues, etc)

Additionally, the example with fixed and return ref from above also compiles even when I replace the parameter type ref TContainer with just TContainer, or, which should be the same, just declare it as an instance member instead of an extension method. It even works in a sample test case, but I can't see why it does, because under normal circumstances one can't return ref this.field from a struct instance method.

答:
In answer to your questions:

yes, because you reconstruct the unmanaged pointer back into a managed pointer while it is pinned; at no point can the managed pointer be invalid

no, fixed uses a very-low overhead mechanism - basically, fixed just marks a local variable as having special meaning; when the GC runs, it is already walking the stack-frames, and when it does so it looks for these locals and notes that the value of them should be considered pinned

However! It sounds like the concept you're really after here is Span<T> (or Memory<T>) - a Span<T> is basically a "range" using managed pointers.

Here's a version that doesn't use unsafe:

```<code>public static ref T Ref<T, TContainer>(this ref TContainer container, int index)
    where TContainer : unmanaged
    where T : unmanaged
{
    if (index < 0 || Unsafe.SizeOf<T>() * (index + 1) > Unsafe.SizeOf<TContainer>())
        throw new ArgumentOutOfRangeException(nameof(index));
    ref T first = ref Unsafe.As<TContainer, T>(ref container);
    return ref Unsafe.Add<T>(ref first, index);
}
</code>```

Note that it is still "unsafe", though.

Body:
I am trying to implement fixed size arrays in C#, that are parametrized by hacky type-level numerics. See GitHub

I want to implement a method, that would work like this:

static ref T Ref(this ref TContainer container, int index)
  where T: unmanaged
  where TContainer: unmanaged
  => ref container[index];

Now the problem is: I know, that TContainer internally consists of N fields of type T. But it does not actually implement the indexing operation (or any interface whatsoever).

What I can do is:

CheckIndex(index);
fixed (TContainer* self = &container) {
    T* data = (T*)self;
    return ref data[index];
}

This compiles with unsafe, but I have two questions:

Will the lifetime of the managed reference retrieved like this be tracked properly?

Does use of fixed in this context have any performance cost? (e.g. GC pinning, aliasing issues, etc)

Additionally, the example with fixed and return ref from above also compiles even when I replace the parameter type ref TContainer with just TContainer, or, which should be the same, just declare it as an instance member instead of an extension method. It even works in a sample test case, but I can't see why it does, because under normal circumstances one can't return ref this.field from a struct instance method.

Body:
In answer to your questions:

yes, because you reconstruct the unmanaged pointer back into a managed pointer while it is pinned; at no point can the managed pointer be invalid

no, fixed uses a very-low overhead mechanism - basically, fixed just marks a local variable as having special meaning; when the GC runs, it is already walking the stack-frames, and when it does so it looks for these locals and notes that the value of them should be considered pinned

However! It sounds like the concept you're really after here is Span<T> (or Memory<T>) - a Span<T> is basically a "range" using managed pointers.

Here's a version that doesn't use unsafe:

public static ref T Ref<T, TContainer>(this ref TContainer container, int index)
    where TContainer : unmanaged
    where T : unmanaged
{
    if (index < 0 || Unsafe.SizeOf<T>() * (index + 1) > Unsafe.SizeOf<TContainer>())
        throw new ArgumentOutOfRangeException(nameof(index));
    ref T first = ref Unsafe.As<TContainer, T>(ref container);
    return ref Unsafe.Add<T>(ref first, index);
}

Note that it is still "unsafe", though.


问:
Allocating more memory to an existing Global memory array
is it possible to add memory to a previously allocated array in global memory?

what i need to do is this:

```<code>//cudamalloc memory for d_A
int n=0;int N=100;
do
{
 Kernel<<< , >>> (d_A,n++);
 //add N memory to d_A
 while(n!=5)}
</code>```

does doing another cudamalloc removes the values of the previously allocated array? in my case the values of the previous allocated array should be kept...

答:
First, cudaMalloc behaves like malloc, not realloc. This means that cudaMalloc will allocate totally new device memory at a new location. There is no realloc function in the cuda API.

Secondly, as a workaround, you can just use cudaMalloc again to allocate more more memory. Remember to free the device pointer with cudaFree before you assign a new address to d_a. The following code is functionally what you want.

```<code>int n=0;int N=100;

//set the initial memory size
size = <something>;

do
{
    //allocate just enough memory
    cudaMalloc((void**) &d_A, size);

    Kernel<<< ... >>> (d_A,n++);

    //free memory allocated for d_A
    cudaFree(d_A);

    //increase the memory size
    size+=N;

while(n!=5)}
</code>```

Thirdly, cudaMalloc can be an expensive operation, and I expect the above code will be rather slow. I think you should consider why you want to grow the array. Can you allocate memory for d_A one time with enough memory for the largest use case? There is likely no reason to allocate only 100 bytes if you know you need 1,000 bytes later on!

```<code>//calculate the max memory requirement
MAX_SIZE = <something>;

//allocate only once
cudaMalloc((void**) &d_A, MAX_SIZE);

//use for loops when they are appropriate
for(n=0; n<5; n++)
{
    Kernel<<< ... >>> (d_A,n);
}
</code>```

Body:
is it possible to add memory to a previously allocated array in global memory?

what i need to do is this:

//cudamalloc memory for d_A
int n=0;int N=100;
do
{
 Kernel<<< , >>> (d_A,n++);
 //add N memory to d_A
 while(n!=5)}

does doing another cudamalloc removes the values of the previously allocated array? in my case the values of the previous allocated array should be kept...

Body:
First, cudaMalloc behaves like malloc, not realloc. This means that cudaMalloc will allocate totally new device memory at a new location. There is no realloc function in the cuda API.

Secondly, as a workaround, you can just use cudaMalloc again to allocate more more memory. Remember to free the device pointer with cudaFree before you assign a new address to d_a. The following code is functionally what you want.

int n=0;int N=100;

//set the initial memory size
size = <something>;

do
{
    //allocate just enough memory
    cudaMalloc((void**) &d_A, size);

    Kernel<<< ... >>> (d_A,n++);

    //free memory allocated for d_A
    cudaFree(d_A);

    //increase the memory size
    size+=N;

while(n!=5)}

Thirdly, cudaMalloc can be an expensive operation, and I expect the above code will be rather slow. I think you should consider why you want to grow the array. Can you allocate memory for d_A one time with enough memory for the largest use case? There is likely no reason to allocate only 100 bytes if you know you need 1,000 bytes later on!

//calculate the max memory requirement
MAX_SIZE = <something>;

//allocate only once
cudaMalloc((void**) &d_A, MAX_SIZE);

//use for loops when they are appropriate
for(n=0; n<5; n++)
{
    Kernel<<< ... >>> (d_A,n);
}


问:
Domain Specific Languages (DSL) and Domain Driven Design (DDD)
What is the differences and similarities between Domain Specific Languages (DSL) and Domain Driven Design (DDD)?</p>

答:
Wikipedia (https://en.wikipedia.org/wiki/Domain-driven_design) has a good answer:

DDD does not specifically require the use of a DSL, though it could be
  used to help define a DSL and support methods like domain-specific
  multimodeling.

OwnerDisplayName: Bo

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: David Hall


问:
What does it actually mean by Task Planning?
I have just started studying robotics. This is my first question to get started with robotics. Pardon me if this question is too naive.

What does it actually mean by Task Planning in case of robotics?

How is it different from conventional "robot control"?

答:
Robot Motion control is generally dealt with low-level navigation like localization (what is the current location of the robot), path planning (chose a path from a to b by avoiding obstacles).

Tasking planning is generally dealing with high-level planning. For example, task for a robot with a manipulator is to clean the desk (go to desk, find objects on desk and choose the order to pickup items, move the picked items to dusbin).


问:
SwiftLint Rule for Braces on next line but with some exceptions
I want to modify .swiftlint.yml to add some custom rules for enforcing braces on next line. This works for me ...

```<code>  opening_braces:
    name: "Opening Braces not on Next Line"
    message: "Opening braces should be placed on the next line."
    include: "*.swift"
    regex: '\S[ \t]*\{'
    severity: warning
</code>```

However there are some cases where I want to allow braces on the same line, e.g. something like this:

```<code>override var cornerRadius: CGFloat
{
    get { return layer.cornerRadius }
    set { layer.cornerRadius = newValue }
}
</code>```

How do I change my regexp to allow for same line for one-line getters/setters?

答:
I suggest using

```<code>regex: '^(?![ \t]*[sg]et[ \t]+\{.*\}).*\S[ \t]*\{'
</code>```

Or, its alternative with \h matching horizontal whitespace:

```<code>regex: '^(?!\h*[sg]et\h+\{.*\}).*\S\h*\{'
</code>```

See the regex demo (or this one).

Details

^ - start of string

(?!\h*[sg]et\h+\{.*\}) - a location in string that should not be immediately followed with

\h* - 0+ horizontal whitespaces

[sg]et - set or get

\h+ - 1+ horizontal whitespaces

\{.*\} - {, any 0+ chars, as many as possible, and }

.* - any 0+ chars, as many as possible

\S - a non-whitespace char

\h* - 0+ horizontal whitespaces

\{ - a { char.

Body:
I want to modify .swiftlint.yml to add some custom rules for enforcing braces on next line. This works for me ...

  opening_braces:
    name: "Opening Braces not on Next Line"
    message: "Opening braces should be placed on the next line."
    include: "*.swift"
    regex: '\S[ \t]*\{'
    severity: warning

However there are some cases where I want to allow braces on the same line, e.g. something like this:

override var cornerRadius: CGFloat
{
    get { return layer.cornerRadius }
    set { layer.cornerRadius = newValue }
}

How do I change my regexp to allow for same line for one-line getters/setters?

Body:
I suggest using

regex: '^(?![ \t]*[sg]et[ \t]+\{.*\}).*\S[ \t]*\{'

Or, its alternative with \h matching horizontal whitespace:

regex: '^(?!\h*[sg]et\h+\{.*\}).*\S\h*\{'

See the regex demo (or this one).

Details

^ - start of string

(?!\h*[sg]et\h+\{.*\}) - a location in string that should not be immediately followed with

\h* - 0+ horizontal whitespaces

[sg]et - set or get

\h+ - 1+ horizontal whitespaces

\{.*\} - {, any 0+ chars, as many as possible, and }

.* - any 0+ chars, as many as possible

\S - a non-whitespace char

\h* - 0+ horizontal whitespaces

\{ - a { char.


问:
Kendo UI modal with Gaussian blur
It is possible if I wanted to substitute the default grey background of the modal kendo window with a nice gaussian blur like in the image below? Here I provide Demo in Dojo

How to achieve this?

答:
You have to give your main content (the div that contains all the text) a class too, and then blur that class when  the window is opened:

```<code><div id="maincontent">This is the main body text</div>

function onOpen() {
    let main = document.getElementById("maincontent")
    main.style.filter = "blur(2px)"
}
</code>```

In your code snippet I have used the P tag to blur:

Title: Kendo UI modal with Gaussian blur

Body:
You have to give your main content (the div that contains all the text) a class too, and then blur that class when  the window is opened:

<div id="maincontent">This is the main body text</div>

function onOpen() {
    let main = document.getElementById("maincontent")
    main.style.filter = "blur(2px)"
}

In your code snippet I have used the P tag to blur:


问:
How can I count how many horizontal brush strokes are required to draw an array of buildings?
By given an array of integers, each element represents a building. For example: int buildings[] = {1, 4, 3, 2, 3, 1}.

If I drew the buildings horizontally with a brush, how many brush strike I would use?

I should write a function that returns the number of these brush strokes.  For example 5.

I can do it easily on run time O(n^2), by using 2 loops.

The external loop running on the levels of each building (according to the highest building).

The inner loop is running on the array from 0 to n, and compares the difference of the height (0 or 1) between two near elements.

How can I do this in the O(n) time and O(n) space?

答:
Counting from the end of the array use the last element as the initial value of the result, and compare the previous one with the current one.

If they are the same value then, the result increase one;
 if the previous one is smaller than the current one, do nothing;
 if the previous one is bigger than the current one then, result = result +previous-current

```<code>int i=sizeof buildings;
int t=buildings[i];
while(i>0){
  if(buildings[i-1]-buildings[i]>0) t+=(buildings[i-1]-buildings[i]);
  else if(buildings[i-1]-buildings[i]==0) ++t;
  --i;
}
return t;
</code>```

Body:
Counting from the end of the array use the last element as the initial value of the result, and compare the previous one with the current one.

If they are the same value then, the result increase one;
 if the previous one is smaller than the current one, do nothing;
 if the previous one is bigger than the current one then, result = result +previous-current

int i=sizeof buildings;
int t=buildings[i];
while(i>0){
  if(buildings[i-1]-buildings[i]>0) t+=(buildings[i-1]-buildings[i]);
  else if(buildings[i-1]-buildings[i]==0) ++t;
  --i;
}
return t;


问:
Authentication in .net Core with ReactJS SPA
I trying add authentication to .net Core 2.1 application.
Starting from scratch: We can create new web application with react using VS template.

In this tempate we can see:

```<code>app.UseSpa(spa =>
{
    spa.Options.SourcePath = "ClientApp";
    spa.ApplicationBuilder.UseAuthentication();

    if (env.IsDevelopment())
    {
        spa.UseReactDevelopmentServer(npmScript: "start");
    }
});
</code>```

I also added Auth controller and views with login/register endpoints.

How can I add logic which will reject access to SPA untill we will login to application?

I know how to use asp.net identity regullary but with this SPA I need advice.

答:
In Middleware you can check whether user is authenticated , for example :</p>

```<code>app.UseSpa(spa =>
{
    spa.ApplicationBuilder.MapWhen(
        (context)=>!context.User.Identity.IsAuthenticated,
        ab => {
            ab.Run(async (ctx )=> {
                ctx.Response.StatusCode = 401;
                //redirect to login page
                ctx.Response.Headers.Add("Location", "....");
                //await ctx.Response.WriteAsync("Authecation Failed");
            });
        }
    );

    spa.Options.SourcePath = "ClientApp";

    if (env.IsDevelopment())
    {
        spa.UseReactDevelopmentServer(npmScript: "start");
    }
});
</code>```

Body:
I trying add authentication to .net Core 2.1 application.
Starting from scratch: We can create new web application with react using VS template.

In this tempate we can see:

app.UseSpa(spa =>
{
    spa.Options.SourcePath = "ClientApp";
    spa.ApplicationBuilder.UseAuthentication();

    if (env.IsDevelopment())
    {
        spa.UseReactDevelopmentServer(npmScript: "start");
    }
});

I also added Auth controller and views with login/register endpoints.

How can I add logic which will reject access to SPA untill we will login to application?

I know how to use asp.net identity regullary but with this SPA I need advice.

Body:
In Middleware you can check whether user is authenticated , for example :

app.UseSpa(spa =>
{
    spa.ApplicationBuilder.MapWhen(
        (context)=>!context.User.Identity.IsAuthenticated,
        ab => {
            ab.Run(async (ctx )=> {
                ctx.Response.StatusCode = 401;
                //redirect to login page
                ctx.Response.Headers.Add("Location", "....");
                //await ctx.Response.WriteAsync("Authecation Failed");
            });
        }
    );

    spa.Options.SourcePath = "ClientApp";

    if (env.IsDevelopment())
    {
        spa.UseReactDevelopmentServer(npmScript: "start");
    }
});


问:
Showing 404 error page in crud examplewith CI
I am new in Codeigniter. I have followed the tutorial to create a crud system.
http://www.expertphp.in/article/php-codeigniter-3-basic-crud-operation-with-mysql-database-with-example

I am using Linux Mint system. I have done all permission related things. Still i am getting 404 error page. when i go to

http://localhost/codeign/myapp/products

Here i made the products controller like this

```<code>class Products extends CI_Controller
{

    function __construct(argument)
    {
        parent::__construct();
        $this->load->model('ProductsModel');
    }

    public function index()
    {
        $Products = new ProductsModel;
        $data['data'] = $Products->get_poducts();
        $this->load->view('includes/header');
        $this->load->view('products/list',$data);
        $this->load->view('includes/footer');
    }
</code>```

Still i am getting 404 Not found page. can i know the fault i have done ? Thanks in advance.

答:
Paste this in .htaccess in your app directory (in same level to applications) and will works :</p>

```<code>RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</code>```

Body:
I am new in Codeigniter. I have followed the tutorial to create a crud system.
http://www.expertphp.in/article/php-codeigniter-3-basic-crud-operation-with-mysql-database-with-example

I am using Linux Mint system. I have done all permission related things. Still i am getting 404 error page. when i go to

http://localhost/codeign/myapp/products

Here i made the products controller like this

class Products extends CI_Controller
{

    function __construct(argument)
    {
        parent::__construct();
        $this->load->model('ProductsModel');
    }

    public function index()
    {
        $Products = new ProductsModel;
        $data['data'] = $Products->get_poducts();
        $this->load->view('includes/header');
        $this->load->view('products/list',$data);
        $this->load->view('includes/footer');
    }

Still i am getting 404 Not found page. can i know the fault i have done ? Thanks in advance.

Body:
Paste this in .htaccess in your app directory (in same level to applications) and will works :

RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]


问:
how to open specific/different Activity in the recyclerview whose data is from json using volley
I want to open new activity that is different in each recyclerview item.

I have read and I do not need an image item here  : How to open a different activity on recyclerView item onclick

This is my Adapter

public class B001Adapter extends RecyclerView.Adapter {

```<code>private Context context;
private LayoutInflater inflater;
List<B001Data> udata = Collections.emptyList();

public B001Adapter(Context context, List<B001Data> data) {
    this.context = context;
    inflater = LayoutInflater.from(context);
    this.udata = data;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.datab001, parent, false);
    MyHolder holder = new MyHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    MyHolder myHolder = (MyHolder) holder;
    final B001Data current = udata.get(position);

    myHolder.device_name.setText(current.device_name);
    myHolder.mac_address.setText(current.mac_address);
    myHolder.status.setText("Status:" + String.valueOf(current.status));
}

@Override
public int getItemCount() {
    return udata.size();

}
class MyHolder extends RecyclerView.ViewHolder {

    TextView device_name, mac_address, status;

    public MyHolder(View itemView) {
        super(itemView);
        context = itemView.getContext();
        device_name = (TextView) itemView.findViewById(R.id.txt_device_name);
        mac_address = (TextView) itemView.findViewById(R.id.txt_mac_address);
        status = (TextView) itemView.findViewById(R.id.txt_status);
    }

    public void onClick(AdapterView<?> parent, View view, int position {

        final Intent intent;
        switch (getAdapterPosition()){
            case 0:
                intent =  new Intent(context, MainActivity.class);
                break;

            case 1:
                intent =  new Intent(context, B001FacilityM.class);
                break;

            case 2:
                intent =  new Intent(context, B001HRD.class);
                break;
            default:
                intent =  new Intent(context, B001home.class);
                break;
        }
        context.startActivity(intent);
    }
}
</code>```

}

I use volley to get Json data displayed on the recyclerView. Looking for your advice. Thanks

答:
First You Should assign id to layout file (R.layout.datab001),
 find out id using findViewsById in MyHolder() constructor
and then set onClickListener to layout like myHolder.layout.setOnClickListener(....);
in onBindViewHolder().

or check other answer
RecyclerView onClick

Body:
I want to open new activity that is different in each recyclerview item.

I have read and I do not need an image item here  : How to open a different activity on recyclerView item onclick

This is my Adapter

public class B001Adapter extends RecyclerView.Adapter {

private Context context;
private LayoutInflater inflater;
List<B001Data> udata = Collections.emptyList();

public B001Adapter(Context context, List<B001Data> data) {
    this.context = context;
    inflater = LayoutInflater.from(context);
    this.udata = data;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.datab001, parent, false);
    MyHolder holder = new MyHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    MyHolder myHolder = (MyHolder) holder;
    final B001Data current = udata.get(position);

    myHolder.device_name.setText(current.device_name);
    myHolder.mac_address.setText(current.mac_address);
    myHolder.status.setText("Status:" + String.valueOf(current.status));
}

@Override
public int getItemCount() {
    return udata.size();

}
class MyHolder extends RecyclerView.ViewHolder {

    TextView device_name, mac_address, status;

    public MyHolder(View itemView) {
        super(itemView);
        context = itemView.getContext();
        device_name = (TextView) itemView.findViewById(R.id.txt_device_name);
        mac_address = (TextView) itemView.findViewById(R.id.txt_mac_address);
        status = (TextView) itemView.findViewById(R.id.txt_status);
    }

    public void onClick(AdapterView<?> parent, View view, int position {

        final Intent intent;
        switch (getAdapterPosition()){
            case 0:
                intent =  new Intent(context, MainActivity.class);
                break;

            case 1:
                intent =  new Intent(context, B001FacilityM.class);
                break;

            case 2:
                intent =  new Intent(context, B001HRD.class);
                break;
            default:
                intent =  new Intent(context, B001home.class);
                break;
        }
        context.startActivity(intent);
    }
}

}

I use volley to get Json data displayed on the recyclerView. Looking for your advice. Thanks


问:
Oracle PL/SQL Swapping a for loop for dynamic SQL, assistance with syntax changes
I have a for loop, here:

```<code>BEGIN

for rws in (

select /*+parallel (4)*/ a.owner,a.table_name, round(sum(b.sum_bytes),2) TOT_OBJECT_SIZE_MB, EST_ONE_ROW_MB
from dba_tables@DB1 a, MV_PRD_SEG_DATA b
where a.table_name = b.segment_name
and a.table_name in
(select table_name from MV_PDU_TABLE where driver_table is null)
and a.owner in (select distinct productionschema from MV_PDU_TABLE c)
group by a.owner,a.table_name
order by a.table_name
)
loop
</code>```

Data is pulled out of the loop as follows by referencing rws. :

```<code>execute immediate' select /*+parallel (4)*/ count(*) from ' ||rws.owner||'.'||rws.table_name || '@' || dblink into TOTAL_ROW_COUNT;
</code>```

I now have to change some of the hard coded table references in the select statement to variables. (I will be declaring these earlier in the code.)

As I understand it, I must now switch to dynamic SQL.

In doing so, you can see here how the hard coded tables are now referred to as variables:

```<code>BEGIN

v_sql1 := 'select /*+parallel (4)*/ a.owner,a.table_name, round(sum(b.sum_bytes),2) TOT_OBJECT_SIZE_MB, EST_ONE_ROW_MB
from dba_tables@NAB1 a, '|| v_Mv_name ||' b
where a.table_name = b.segment_name
and a.table_name in
(select table_name from '|| v_Mv_name ||' where driver_table is null)
and a.owner in (select distinct productionschema from '|| v_Mv_name ||' c)
group by a.owner,a.table_name
order by a.table_name';
</code>```

The issue is... how do I now manage getting the data out of the loop? I think I would loop, just using the variable containing the SQL?:

```<code>for rws in (v_sql1)

loop
</code>```

If so, what would now go here?

```<code>execute immediate' select /*+parallel (4)*/ count(*) from ' <NO_IDEA_HOW_TO_REFERENCE_THE_DATA_IN_THE_LOOP_NOW> ' into TOTAL_ROW_COUNT;
</code>```

答:
You may do a BULK COLLECT  into collection of record you wish to return and then loop through the collection.

You may be able to use this example readily into your script.

```<code>DECLARE
 TYPE sizerec is RECORD ( owner dba_tables.owner%type,
  table_name dba_tables.table_name%type,
  tot_object_size_mb number);
  TYPE srectab  is TABLE OF  sizerec;
  srec srectab;
  l_tab_name varchar2(40) := 'dba_tables';
BEGIN

EXECUTE IMMEDIATE
'SELECT a.owner,a.table_name,round(SUM(b.bytes),2) tot_object_size_mb
  FROM '||l_tab_name||' a
JOIN dba_segments b ON a.table_name = b.segment_name where rownum < 10
GROUP BY a.owner,a.table_name ' BULK COLLECT INTO srec;

for i in srec.first..srec.last
loop
  dbms_output.put_line(srec(i).owner||','||srec(i).table_name
                                    ||','||srec(i).tot_object_size_mb);
end loop;

END;
/
</code>```

Output

```<code>PL/SQL procedure successfully completed.

SYS,BOOTSTRAP$,65536
SYS,FILE$,65536
SYS,OBJERROR$,65536
SYS,UNDO$,65536
SYS,PROXY_DATA$,65536
SYS,OBJ$,10485760
SYS,PROXY_ROLE_DATA$,65536
SYS,OBJAUTH$,2097152
SYS,CON$,262144
</code>```

Body:
I have a for loop, here:

BEGIN

for rws in (

select /*+parallel (4)*/ a.owner,a.table_name, round(sum(b.sum_bytes),2) TOT_OBJECT_SIZE_MB, EST_ONE_ROW_MB
from dba_tables@DB1 a, MV_PRD_SEG_DATA b
where a.table_name = b.segment_name
and a.table_name in
(select table_name from MV_PDU_TABLE where driver_table is null)
and a.owner in (select distinct productionschema from MV_PDU_TABLE c)
group by a.owner,a.table_name
order by a.table_name
)
loop

Data is pulled out of the loop as follows by referencing rws. :

execute immediate' select /*+parallel (4)*/ count(*) from ' ||rws.owner||'.'||rws.table_name || '@' || dblink into TOTAL_ROW_COUNT;

I now have to change some of the hard coded table references in the select statement to variables. (I will be declaring these earlier in the code.)

As I understand it, I must now switch to dynamic SQL.

In doing so, you can see here how the hard coded tables are now referred to as variables:

BEGIN

v_sql1 := 'select /*+parallel (4)*/ a.owner,a.table_name, round(sum(b.sum_bytes),2) TOT_OBJECT_SIZE_MB, EST_ONE_ROW_MB
from dba_tables@NAB1 a, '|| v_Mv_name ||' b
where a.table_name = b.segment_name
and a.table_name in
(select table_name from '|| v_Mv_name ||' where driver_table is null)
and a.owner in (select distinct productionschema from '|| v_Mv_name ||' c)
group by a.owner,a.table_name
order by a.table_name';

The issue is... how do I now manage getting the data out of the loop? I think I would loop, just using the variable containing the SQL?:

for rws in (v_sql1)

loop

If so, what would now go here?

execute immediate' select /*+parallel (4)*/ count(*) from ' <NO_IDEA_HOW_TO_REFERENCE_THE_DATA_IN_THE_LOOP_NOW> ' into TOTAL_ROW_COUNT;

Body:
You may do a BULK COLLECT  into collection of record you wish to return and then loop through the collection.

You may be able to use this example readily into your script.

DECLARE
 TYPE sizerec is RECORD ( owner dba_tables.owner%type,
  table_name dba_tables.table_name%type,
  tot_object_size_mb number);
  TYPE srectab  is TABLE OF  sizerec;
  srec srectab;
  l_tab_name varchar2(40) := 'dba_tables';
BEGIN

EXECUTE IMMEDIATE
'SELECT a.owner,a.table_name,round(SUM(b.bytes),2) tot_object_size_mb
  FROM '||l_tab_name||' a
JOIN dba_segments b ON a.table_name = b.segment_name where rownum < 10
GROUP BY a.owner,a.table_name ' BULK COLLECT INTO srec;

for i in srec.first..srec.last
loop
  dbms_output.put_line(srec(i).owner||','||srec(i).table_name
                                    ||','||srec(i).tot_object_size_mb);
end loop;

END;
/

Output

PL/SQL procedure successfully completed.

SYS,BOOTSTRAP$,65536
SYS,FILE$,65536
SYS,OBJERROR$,65536
SYS,UNDO$,65536
SYS,PROXY_DATA$,65536
SYS,OBJ$,10485760
SYS,PROXY_ROLE_DATA$,65536
SYS,OBJAUTH$,2097152
SYS,CON$,262144


问:
OBJ-C: Getting the minimum/maximum value in a NSMutableArray
I want to get the maximum and minimum values of a NSMutableArray so I can create a core-plot plotspace and graph based around those max and min values.

My code is as follows:

```<code>NSMutableArray *contentArray = [NSMutableArray arrayWithCapacity:100];
NSUInteger i;
for (i=0; i<60; i++){
id x = [NSNumber numberWithFloat:i*0.05];
id y = [NSNumber numberWithFloat:1.2*rand()/(float)RAND_Max + 0.6];
[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, @"x", y, @"y", nil]];
}

self.dataForPlot = contentArray;

CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat() length:CPDecimalFromFloat()];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat() length:CPDecimalFromFloat()];
</code>```

What do I fill in the blanks for xRange and yRange assignment if I want the graph to span only the space of what's specified in contentArray?

答:
//This gives Max and Min Value in NSMutableArrray
-(void)FindingMinAndMaxValueInNSMutableArray{

```<code>NSMutableArray *array=[[NSMutableArray alloc]initWithObjects:@"0.987",@"0.951",@"0.881",@"0.784",@"0.662",@"0.522",@"0.381",@"-0.265",@"-0.197", @"0.189",@"-0.233",@"0.310",@"0.402",@"0.402",@"0.988",@"0.633",@"0.661",@"0.656",@"0.617",@"0.634",@"0.690",@"0.767",@"0.836",nil];

NSLog(@"The Array Value is %@",array);
NSLog(@"The Array Count is %lu",(unsigned long)array.count);

NSNumber *maxValue = [array valueForKeyPath:@"@max.doubleValue"];
NSLog(@"The maxValue is %@",maxValue);
NSString *str=[NSString stringWithFormat:@"%@",maxValue];
NSInteger path=[array indexOfObject:str];
NSIndexPath *indexpath=[NSIndexPath indexPathForItem:path inSection:0];
NSLog(@"Max Value = %@ and index = %ld",maxValue,(long)indexpath.row);

NSNumber *minValue = [array valueForKeyPath:@"@min.doubleValue"];
NSLog(@"The minValue is %@",minValue);
NSString *str1 = [NSString stringWithFormat:@"%@",minValue];
NSInteger path1 = [array indexOfObject:str1];
NSIndexPath *indexPath1 = [NSIndexPath indexPathForItem:path1 inSection:0];
NSLog(@"Min Value =%@ and index = %ld",minValue,(long)indexPath1.row);
</code>```

}

Body:
I want to get the maximum and minimum values of a NSMutableArray so I can create a core-plot plotspace and graph based around those max and min values.

My code is as follows:

NSMutableArray *contentArray = [NSMutableArray arrayWithCapacity:100];
NSUInteger i;
for (i=0; i<60; i++){
id x = [NSNumber numberWithFloat:i*0.05];
id y = [NSNumber numberWithFloat:1.2*rand()/(float)RAND_Max + 0.6];
[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, @"x", y, @"y", nil]];
}

self.dataForPlot = contentArray;

CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat() length:CPDecimalFromFloat()];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat() length:CPDecimalFromFloat()];

What do I fill in the blanks for xRange and yRange assignment if I want the graph to span only the space of what's specified in contentArray?

Body:
//This gives Max and Min Value in NSMutableArrray
-(void)FindingMinAndMaxValueInNSMutableArray{

NSMutableArray *array=[[NSMutableArray alloc]initWithObjects:@"0.987",@"0.951",@"0.881",@"0.784",@"0.662",@"0.522",@"0.381",@"-0.265",@"-0.197", @"0.189",@"-0.233",@"0.310",@"0.402",@"0.402",@"0.988",@"0.633",@"0.661",@"0.656",@"0.617",@"0.634",@"0.690",@"0.767",@"0.836",nil];

NSLog(@"The Array Value is %@",array);
NSLog(@"The Array Count is %lu",(unsigned long)array.count);

NSNumber *maxValue = [array valueForKeyPath:@"@max.doubleValue"];
NSLog(@"The maxValue is %@",maxValue);
NSString *str=[NSString stringWithFormat:@"%@",maxValue];
NSInteger path=[array indexOfObject:str];
NSIndexPath *indexpath=[NSIndexPath indexPathForItem:path inSection:0];
NSLog(@"Max Value = %@ and index = %ld",maxValue,(long)indexpath.row);

NSNumber *minValue = [array valueForKeyPath:@"@min.doubleValue"];
NSLog(@"The minValue is %@",minValue);
NSString *str1 = [NSString stringWithFormat:@"%@",minValue];
NSInteger path1 = [array indexOfObject:str1];
NSIndexPath *indexPath1 = [NSIndexPath indexPathForItem:path1 inSection:0];
NSLog(@"Min Value =%@ and index = %ld",minValue,(long)indexPath1.row);

}


问:
Pivoting tables in SQL Server in 2019 year and future
Are there any ways to achieve dynamic pivoting tables in SQL Server through an elegant function? Pivoting tables is a basic utility which theoretically might be done in one line of code. All we need is to define parameters: column variable to pivot (change its values into column names), variable to aggregate, aggregate function, and table on which we perform the pivoting.

I look for alternatives to the syntax Microsoft proposes for pivoting tables in SQL Server in the 2019 year.

A practical alternative I found here:
https://stackoverflow.com/a/45065584/1903793

All complex code is wrapped with a stored procedure. In this elegant one-liner, we define all parameters which are needed for pivoting.

```<code>exec [dbo].[USP_DYNAMIC_PIVOT] 'date','category','amount','dbo.temp','sum'
</code>```

But the caveat of that solution is that it is a stored procedure so it requires a static table as input and it outputs also a static table. Would be better if it might be a sort of TVF from which we can select.

Update after comments.
Until I started using SQL Server I did not even know that pivoting might be static. The need is to do dynamic pivoting. Lots of other applications do pivoting tables on the fly (Excel, Power BI, R) without constraint that column names must be known apriori. It might be a problem in 2005 to realize that pivoting might be done as a function with parameters. But, hey, we are going to the future, and it is ridiculous that we are heading next decades with the complex constrained syntax for this basic table transformation utility.

答:
SQL Server is a relational database management system. The concept of a relation is at the foundation of its design. All relational database management systems are designed under assumption that the schema of the database is stable. In other words, all RDBMSs assume that the list of tables and their columns are static. They are designed to work efficiently when data is structured in this way.

It looks like you have some expectations from a tool that it wasn't designed for.

I don't have experience with non-relational DBMSs. Nowadays there are tons of them and some may be a better fit for your tasks than RDBMS.

With RDBMS there is often a separation of data and its representation to the end user.

The task of the RDBMS is to efficiently find and aggregate the required subset of data within the large database that resides on the server and return the small result set to the client. The task of the client reporting tool is to take this resulting dataset and format it in a way that the end user wants. For example, show dollar sign in front of money amounts, round the values to the necessary precision, print out values in the form of crosstabs with subtotals, etc. Pivoting is a common wide-spread need and there are plenty of reporting tools that can format small subsets of data in any way you like, but these tools are not database management systems.

Yes, RDBMSs in general and SQL Server in particular have some capabilities to work with dynamic database schema, but they are often clunky and ugly, such as dynamic SQL and PIVOT syntax. They were not designed for it.

Body:
Are there any ways to achieve dynamic pivoting tables in SQL Server through an elegant function? Pivoting tables is a basic utility which theoretically might be done in one line of code. All we need is to define parameters: column variable to pivot (change its values into column names), variable to aggregate, aggregate function, and table on which we perform the pivoting.

I look for alternatives to the syntax Microsoft proposes for pivoting tables in SQL Server in the 2019 year.

A practical alternative I found here:
https://stackoverflow.com/a/45065584/1903793

All complex code is wrapped with a stored procedure. In this elegant one-liner, we define all parameters which are needed for pivoting.

exec [dbo].[USP_DYNAMIC_PIVOT] 'date','category','amount','dbo.temp','sum'

But the caveat of that solution is that it is a stored procedure so it requires a static table as input and it outputs also a static table. Would be better if it might be a sort of TVF from which we can select.

Update after comments.
Until I started using SQL Server I did not even know that pivoting might be static. The need is to do dynamic pivoting. Lots of other applications do pivoting tables on the fly (Excel, Power BI, R) without constraint that column names must be known apriori. It might be a problem in 2005 to realize that pivoting might be done as a function with parameters. But, hey, we are going to the future, and it is ridiculous that we are heading next decades with the complex constrained syntax for this basic table transformation utility.


问:
React Material UI Checkbox: How to check/uncheck other boxes in group by checking a different box?
I have 3 checkboxes set up, (Not Started, In Progress, Completed), that I would like allow only one to be checked at a certain time.

So if Not Started is automatically checked to begin with, how would I cause it uncheck 'Not Started' if I check 'Completed'?

Heres my code for now:

In App.js:

```<code>  const newGame = {
     id: uuid.v4(),
     title: title,
     hours: hours,
     notStarted: true,
     inProgress: false,
     completed: false,

  }

  notStarted = (id) => {
    this.setState({games: this.state.games.map(game => {
      if(game.id === id){

        game.notStarted = !game.notStarted
        game.inProgress = false;
        game.completed = false;
      }
    return game;
  })})
};

  markCompleted = (id) => {
this.setState({games: this.state.games.map(game => {
  if(game.id === id){

    game.completed = !game.completed
    game.notStarted = false;
    game.inProgress = false;
  }
  return game;
})})
};
</code>```

And in the render() method:

```<code><Backlog games={this.state.games}
        markCompleted={this.markCompleted}
        inProgress={this.inProgress}
        notStarted={this.notStarted}
/>
</code>```

And this is the checkboxes in Game.js

```<code><FormControlLabel
      control={
         <Checkbox
              color="primary"
              onChange={this.props.notStarted.bind(this, id)}
          />
      }
      label="Not Started"
/>
<FormControlLabel
      control={
         <Checkbox
              color="primary"
              onChange={this.props.markCompleted.bind(this, id)}
          />
      }
      label="Completed"
/>
</code>```

As of now, I can successfully change the state of the props, but I'm unsure how to make the box check/uncheck according to the state?

答:
With using Prop [checked] of FormControlLabel from here

```<code>this.state.games.checked
</code>```

If true, the component appears selected.

Body:
I have 3 checkboxes set up, (Not Started, In Progress, Completed), that I would like allow only one to be checked at a certain time.

So if Not Started is automatically checked to begin with, how would I cause it uncheck 'Not Started' if I check 'Completed'?

Heres my code for now:

In App.js:

  const newGame = {
     id: uuid.v4(),
     title: title,
     hours: hours,
     notStarted: true,
     inProgress: false,
     completed: false,

  }

  notStarted = (id) => {
    this.setState({games: this.state.games.map(game => {
      if(game.id === id){

        game.notStarted = !game.notStarted
        game.inProgress = false;
        game.completed = false;
      }
    return game;
  })})
};

  markCompleted = (id) => {
this.setState({games: this.state.games.map(game => {
  if(game.id === id){

    game.completed = !game.completed
    game.notStarted = false;
    game.inProgress = false;
  }
  return game;
})})
};

And in the render() method:

<Backlog games={this.state.games}
        markCompleted={this.markCompleted}
        inProgress={this.inProgress}
        notStarted={this.notStarted}
/>

And this is the checkboxes in Game.js

<FormControlLabel
      control={
         <Checkbox
              color="primary"
              onChange={this.props.notStarted.bind(this, id)}
          />
      }
      label="Not Started"
/>
<FormControlLabel
      control={
         <Checkbox
              color="primary"
              onChange={this.props.markCompleted.bind(this, id)}
          />
      }
      label="Completed"
/>

As of now, I can successfully change the state of the props, but I'm unsure how to make the box check/uncheck according to the state?

Body:
With using Prop [checked] of FormControlLabel from here

this.state.games.checked

If true, the component appears selected.


问:
Google Cloud Build - View logs permissions
I am the owner of a project and want to give Permissions to another user to view Logs of Google Cloud Build, but I can not figure out which Role / Permission this user needs.

Roles I've unsuccessfully tried are:
Cloud Build Editor,
Cloud Build Viewer,
Stackdriver Debugger Agent,
Stackdriver Debugger User,
Cloud Trace Admin,
Logging Admin,
Private Logs Viewer,
Logs Viewer,
Monitoring Admin

答: If you add the project viewer role then this will resolve the issue. But, it seems like this is an issue (or maybe a feature request - to add the necessary permission to the Logs Viewer so that logs outside of the Stackdriver logging page can be viewed in other UIs as well), looking at the documentation it says "roles/viewer (Project Viewer) gives members the same permissions as roles/logging.viewer at the project level. " which means that by just assigning the Logs Viewer then it should have given the user the necessary permission to view the logs at the Cloud Build UI.