问:
Python- Wireless Controller & List of Addends/Values
Hardware: RPi4 4GB, SteelSeries Stratus Duo WiFi/BTLE wireless controller

Long Term Goal: Perform multiple tasks (i.e., move/zero the toolhead, start/pause/stop the program, etc.) using the wireless controller which will interface with the RPi that is running a server that controls a CNC router.

Short Term Goal: Determine which combination of buttons are being pressed without using an ungodly number of if/elif statements.

Summary: I have already figured out how to read the output from the wireless controller using PyUSB. I've altered/added code to that which was included with PyUSB to produce some human-readable results. The output is formatted in a list, with each item's value being determined by some sort of button combination. (I know it says "array", but Python appears to treat it as a list.)

This is the output when no buttons are pressed (Default):

```<code>array('B', [0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
</code>```

The first two values (...[0, 20,...]) seem to be some sort of identifiers, and those never change. Multiple buttons, however, utilize the same indexed location in the list. They all have different values, and are summed when pressed simultaneously. No combination of button values generate the same output for the indexed location. Examples:

Button A: array('B', [0, 20, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Top Left: array('B', [0, 20, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Top Left & A: array('B', [0, 20, 0, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Here is my current program, and as you can see the if/elif statements are starting to get a little out of hand.:

```<code>#!/usr/bin/python
from __future__ import division

import usb.core
import usb.util
import time
import os
import sys
#import csv

USB_IF      = 0 # Interface
USB_TIMEOUT = 5 # Timeout in MS

USB_VENDOR  = 0x1038 # SteelSeries
USB_PRODUCT = 0x1430 # Stratus Duo

dev = usb.core.find(idVendor=USB_VENDOR, idProduct=USB_PRODUCT)

endpoint = dev[0][(0,0)][0]

if dev.is_kernel_driver_active(USB_IF) is True:
    dev.detach_kernel_driver(USB_IF)

usb.util.claim_interface(dev, USB_IF)

while True:
    control = None

    try:
        control = dev.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize, USB_TIMEOUT)
        CtrlA = control[2]      #Directional Pad, Start/Select, L/R Stick Press
        CtrlB = control[3]      #Top Left/Top Right, Center, A, B, X, Y
        CtrlC = control[4]      #Left Trigger (0-255)
        CtrlD = control[5]      #Right Trigger (0-255)
        CtrlEH = control[6:10]  #Left Stick
        CtrlIL = control[10:14] #Right Stick
        print control
        if CtrlA ==0:
            print "No Input"
        elif CtrlA == 1:
            print "Directional Pad: Up"
        elif CtrlA == 2:
            print "Directional Pad: Down"
        elif CtrlA == 4:
            print "Directional Pad: Left"
        elif CtrlA == 8:
            print "Directional Pad: Right"
        elif CtrlA == 16:
            print "Right Center Button"
        elif CtrlA == 32:
            print "Left Center Button"
        elif CtrlA == 64:
            print "Left Stick Pressed"
        elif CtrlA == 128:
            print "Right Stick Pressed"
        elif CtrlA == 192:
            print "Right & Left Sticks Pressed"
        else:
            break

        if CtrlC == 0:
            print "Left Trigger: No Input"
        elif 1 <= CtrlC <=254:
            print "Left Trigger: " + "{:.0%}".format(CtrlC/255)
        elif CtrlC == 255:
            print "Left Trigger: Max"
        else:
            break

        if CtrlD == 0:
            print "Right Trigger: No Input"
        elif 1 <= CtrlD <=254:
            print "Right Trigger: " + "{:.0%}".format(CtrlD/255)
        elif CtrlD == 255:
            print "Right Trigger: Max"
        else:
            break

except:
pass

#Let Ctrl+C actually exit.
time.sleep(0.01)
</code>```

Again, my desired result would be for the program to determine the combination of buttons being pressed- For instance, if the value for control[3] is 17, is there a way to efficiently have the program determine that it is a combination of the assigned values of 16 and 1 (The 'A' button & the 'Top Left' button)?

I've looked into possibly using a CSV file, itertools(permutations, combinations, etc.), embedded lists, and other such possible solutions. At first glance, all of these appear to be somewhere in the ballpark of what I want to do. Unfortunately, none of these (at least by themselves) appear to accomplish the goal. This is a completely uncharted area of programming for me, and any guidance would be greatly appreciated.

答:
If the value for control[3] is 17, is there a way to efficiently have the program determine that it is a combination of the assigned values of 16 and 1

This is the interesting bit of the question.  And the answer is "yes".  You may have noticed that the individual values (1, 2, 4, 8, 16, 32, 64...) are powers of 2 (2**1, 2**2, 2**3...).  This means that the combined values can be thought of as binary digits. So if I gave you 40, the only way to represent that using powers of 2 is 32 + 8.  In binary, this is 101000.  If you want to get this in Python then (at least in Python3) you can do bin(40), which prints the string '0b10001'.

In terms of how to make the most of this, I shall defer to art-solopov's answer.

Body:
Hardware: RPi4 4GB, SteelSeries Stratus Duo WiFi/BTLE wireless controller

Long Term Goal: Perform multiple tasks (i.e., move/zero the toolhead, start/pause/stop the program, etc.) using the wireless controller which will interface with the RPi that is running a server that controls a CNC router.

Short Term Goal: Determine which combination of buttons are being pressed without using an ungodly number of if/elif statements.

Summary: I have already figured out how to read the output from the wireless controller using PyUSB. I've altered/added code to that which was included with PyUSB to produce some human-readable results. The output is formatted in a list, with each item's value being determined by some sort of button combination. (I know it says "array", but Python appears to treat it as a list.)

This is the output when no buttons are pressed (Default):

array('B', [0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

The first two values (...[0, 20,...]) seem to be some sort of identifiers, and those never change. Multiple buttons, however, utilize the same indexed location in the list. They all have different values, and are summed when pressed simultaneously. No combination of button values generate the same output for the indexed location. Examples:

Button A: array('B', [0, 20, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Top Left: array('B', [0, 20, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Top Left & A: array('B', [0, 20, 0, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Here is my current program, and as you can see the if/elif statements are starting to get a little out of hand.:

#!/usr/bin/python
from __future__ import division

import usb.core
import usb.util
import time
import os
import sys
#import csv

USB_IF      = 0 # Interface
USB_TIMEOUT = 5 # Timeout in MS

USB_VENDOR  = 0x1038 # SteelSeries
USB_PRODUCT = 0x1430 # Stratus Duo

dev = usb.core.find(idVendor=USB_VENDOR, idProduct=USB_PRODUCT)

endpoint = dev[0][(0,0)][0]

if dev.is_kernel_driver_active(USB_IF) is True:
    dev.detach_kernel_driver(USB_IF)

usb.util.claim_interface(dev, USB_IF)

while True:
    control = None

    try:
        control = dev.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize, USB_TIMEOUT)
        CtrlA = control[2]      #Directional Pad, Start/Select, L/R Stick Press
        CtrlB = control[3]      #Top Left/Top Right, Center, A, B, X, Y
        CtrlC = control[4]      #Left Trigger (0-255)
        CtrlD = control[5]      #Right Trigger (0-255)
        CtrlEH = control[6:10]  #Left Stick
        CtrlIL = control[10:14] #Right Stick
        print control
        if CtrlA ==0:
            print "No Input"
        elif CtrlA == 1:
            print "Directional Pad: Up"
        elif CtrlA == 2:
            print "Directional Pad: Down"
        elif CtrlA == 4:
            print "Directional Pad: Left"
        elif CtrlA == 8:
            print "Directional Pad: Right"
        elif CtrlA == 16:
            print "Right Center Button"
        elif CtrlA == 32:
            print "Left Center Button"
        elif CtrlA == 64:
            print "Left Stick Pressed"
        elif CtrlA == 128:
            print "Right Stick Pressed"
        elif CtrlA == 192:
            print "Right & Left Sticks Pressed"
        else:
            break

        if CtrlC == 0:
            print "Left Trigger: No Input"
        elif 1 <= CtrlC <=254:
            print "Left Trigger: " + "{:.0%}".format(CtrlC/255)
        elif CtrlC == 255:
            print "Left Trigger: Max"
        else:
            break

        if CtrlD == 0:
            print "Right Trigger: No Input"
        elif 1 <= CtrlD <=254:
            print "Right Trigger: " + "{:.0%}".format(CtrlD/255)
        elif CtrlD == 255:
            print "Right Trigger: Max"
        else:
            break

except:
pass

#Let Ctrl+C actually exit.
time.sleep(0.01)

Again, my desired result would be for the program to determine the combination of buttons being pressed- For instance, if the value for control[3] is 17, is there a way to efficiently have the program determine that it is a combination of the assigned values of 16 and 1 (The 'A' button & the 'Top Left' button)?

I've looked into possibly using a CSV file, itertools(permutations, combinations, etc.), embedded lists, and other such possible solutions. At first glance, all of these appear to be somewhere in the ballpark of what I want to do. Unfortunately, none of these (at least by themselves) appear to accomplish the goal. This is a completely uncharted area of programming for me, and any guidance would be greatly appreciated.


来源: stackexchange

问:
Arbitary choosen values as std/mean for normalizatio. why?
I have a question regarding the z-score normalization method.

This method uses the z-score to normalize the values of the dataset and needs a mean/std.

I know that you are normally supposed to use the mean/std of the dataset.

But I have seen multiple tutorials on pytorch.org and the net who just use the 0.5 for mean/std which seems completely arbitrary to me.

And I was wondering why they didn't use the mean/std of the dataset?

Example Tutorials where they just use 0.5 as mean/std:
https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html

https://medium.com/ai-society/gans-from-scratch-1-a-deep-introduction-with-code-in-pytorch-and-tensorflow-cb03cdcdba0f

https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py

答:
If you use the std/mean of your dataset to normalize the same dataset you are going to have after the normalization a mean of 0 and an std of 1.

Where the min/max values of the normalized dataset are not in a certain range.

If you use mean/std of 0.5 as a parameter for normalization of your dataset you are going to have a dataset in the range of -1 to 1.

And the mean of the normalized dataset will be close to zero and the std of the normalized dataset will be close to 0.5.

So to answer my question you use 0.5 as mean/std when you want that your dataset is in a range of -1 to 1.

Which would be beneficial when using, for example, a tanh activation function in a neural network.

ContentLicense: CC BY-SA 4.0


问:
MongoDb in a container seed with multiple collections
I'm trying to feed my mongo running in a container with existing collections living outside the container.

docker-compose.yml looks like this:

```<code>version: "3"
services:
    webapi:
      image: webapp:develop
      container_name: web_api
      build:
        args:
          buildconfig: Debug
        context: ../src/api
        dockerfile: Dockerfile
      environment:
        - ASPNETCORE_ENVIRONMENT=Development
        - ASPNETCORE_URLS=http://+:5003
      ports:
        - "5003:5003"
      depends_on:
        - mongodb
    mongodb:
      image: mongo:latest
      container_name: mongodb
      ports:
        - "27017:27017"
    mongo-seed:
      build: ./mongo-seed
      links:
        - mongodb
</code>```

mongo-seed/Dockerfile:

```<code>FROM mongo

COPY initA.json /initA.json
CMD mongoimport --host mongodb --db Database --collection A --type json --file /initA.json --jsonArray --mode merge

FROM mongo

COPY initB.json /initB.json
CMD mongoimport --host mongodb --db TestListDb --collection B --type json --file /initB.json --jsonArray --mode merge
</code>```

But this doesn't do the trick as it overwrites the database with the last collection, so maintains only 'B' collection in this case.

How can I import multiple collections to one database?

答:
I found a solution for that.

Also the answer shows how to configure network so the webapp can see the mongodb container.

Structure of files:

```<code>Web.Application
.
+-- docker_compose.yml
+-- mongo
|   +-- dump
|       +-- DatabaseDb
|   +-- Dockerfile
|   +-- restore.sh
</code>```

docker-compose.yml

```<code>version: '3.4'
services:
  webapp:
    container_name: webapp
    image: ${DOCKER_REGISTRY-}webapp
    build:
      context: ./Web.Application/
      dockerfile: Dockerfile
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
    depends_on:
      - mongo
    networks:
      clusternetwork:
        ipv4_address: 1.1.0.1
  mongo:
    container_name: mongo
    build:
      context: ./Web.Application/mongo/
      dockerfile: Dockerfile
    networks:
      clusternetwork:
        ipv4_address: 1.1.0.12
networks:
  clusternetwork:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 1.1.0.0/24
</code>```

./Web.Application/mongo/Dockerfile:

```<code>FROM mongo AS start

COPY . .

COPY restore.sh /docker-entrypoint-initdb.d/
</code>```

./Web.Application/mongo/restore.sh:

```<code>#!/bin/bash
mongorestore  --db DatabaseDb ./dump/DatabaseDb
</code>```

Body:
I'm trying to feed my mongo running in a container with existing collections living outside the container.

docker-compose.yml looks like this:

version: "3"
services:
    webapi:
      image: webapp:develop
      container_name: web_api
      build:
        args:
          buildconfig: Debug
        context: ../src/api
        dockerfile: Dockerfile
      environment:
        - ASPNETCORE_ENVIRONMENT=Development
        - ASPNETCORE_URLS=http://+:5003
      ports:
        - "5003:5003"
      depends_on:
        - mongodb
    mongodb:
      image: mongo:latest
      container_name: mongodb
      ports:
        - "27017:27017"
    mongo-seed:
      build: ./mongo-seed
      links:
        - mongodb

mongo-seed/Dockerfile:

FROM mongo

COPY initA.json /initA.json
CMD mongoimport --host mongodb --db Database --collection A --type json --file /initA.json --jsonArray --mode merge

FROM mongo

COPY initB.json /initB.json
CMD mongoimport --host mongodb --db TestListDb --collection B --type json --file /initB.json --jsonArray --mode merge

But this doesn't do the trick as it overwrites the database with the last collection, so maintains only 'B' collection in this case.

How can I import multiple collections to one database?

Body:
I found a solution for that.

Also the answer shows how to configure network so the webapp can see the mongodb container.

Structure of files:

Web.Application
.
+-- docker_compose.yml
+-- mongo
|   +-- dump
|       +-- DatabaseDb
|   +-- Dockerfile
|   +-- restore.sh

docker-compose.yml

version: '3.4'
services:
  webapp:
    container_name: webapp
    image: ${DOCKER_REGISTRY-}webapp
    build:
      context: ./Web.Application/
      dockerfile: Dockerfile
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
    depends_on:
      - mongo
    networks:
      clusternetwork:
        ipv4_address: 1.1.0.1
  mongo:
    container_name: mongo
    build:
      context: ./Web.Application/mongo/
      dockerfile: Dockerfile
    networks:
      clusternetwork:
        ipv4_address: 1.1.0.12
networks:
  clusternetwork:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 1.1.0.0/24

./Web.Application/mongo/Dockerfile:

FROM mongo AS start

COPY . .

COPY restore.sh /docker-entrypoint-initdb.d/

./Web.Application/mongo/restore.sh:

#!/bin/bash
mongorestore  --db DatabaseDb ./dump/DatabaseDb


问:
How can I create info array or list of all the doors objects?
```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectsReplace : MonoBehaviour
{
    public class TransformInfo
    {
        public Vector3 pos;
        public Quaternion rot;
        public Vector3 scale;
    }

    public void GetDoors()
    {
        var DoorsLeft = GameObject.FindGameObjectsWithTag("Door_Left");
        var DoorsRight = GameObject.FindGameObjectsWithTag("Door_Right");

        TransformInfo[] trnfrm = new TransformInfo[DoorsLeft.Length];

        for (int i = 0; i < trnfrm.Length; i++)
        {
            trnfrm[i] = new TransformInfo();

            trnfrm[i].pos = DoorsLeft[i].transform.position;
            trnfrm[i].rot = DoorsLeft[i].transform.rotation;
            trnfrm[i].scale = DoorsLeft[i].transform.localScale;
        }
    }
}
</code>```

This is working fine for the DoorsLeft but I want that trnfrm will include also the info of the objects from DoorsRight so the array or list trnfrm structure will be something like that :

```<code>DoorLeft 0...info inside
DoorLeft 1...info inside
.
.
.
DoorRight 0...info inside
DoorRight 1...info inside
</code>```

This is how the array looks like now :

I want it to include also the DoorRight and to add some id like a string to know what door info is belong to for example :

```<code>DoorLeft 0...info inside
DoorLeft 1...info inside
.
.
.
DoorRight 0...info inside
DoorRight 1...info inside
</code>```

And how to read the info back into GameObjects ?

The main goal is to Instantiate a prefab at the doors positions and same doors rotations and scaling.

So this is what I did :

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

public class ObjectsReplace : MonoBehaviour
{
    public struct TransformInfo
    {
        public string ID;
        public Transform Transform;

        public Vector3 pos;
        public Quaternion rot;
        public Vector3 scale;

        public TransformInfo(Transform transform, string id)
        {
            Transform = transform;
            ID = id;
            // For this kind of stuff I always prefer working on the local values
            pos = transform.localPosition;
            rot = transform.localRotation;
            scale = transform.localScale;
        }

        public void Apply()
        {
            Transform.localPosition = pos;
            Transform.localRotation = rot;
            Transform.localScale = scale;
        }

        public void Apply(Transform transform)
        {
            transform.localPosition = pos;
            transform.localRotation = rot;
            transform.localScale = scale;
        }
    }

    public GameObject prefabToInit;

    // Note your method should probably return something
    public TransformInfo[] GetDoors()
    {
        var DoorsLeft = GameObject.FindGameObjectsWithTag("Door_Left");
        var DoorsRight = GameObject.FindGameObjectsWithTag("Door_Right");

        TransformInfo[] trnfrm = new TransformInfo[DoorsLeft.Length * 2];

        int trnfrmIndex = 0;
        for (int i = 0; i < DoorsLeft.Length; i++)
        {
            trnfrm[trnfrmIndex] = new TransformInfo(DoorsLeft[i].transform, $"{i}_L");
            trnfrm[trnfrmIndex + 1] = new TransformInfo(DoorsRight[i].transform, $"{i}_R");

            trnfrmIndex += 2;
        }

        return trnfrm;
    }

    public void ApplyDoors()
    {
        foreach (var info in GetDoors())
        {
            info.Apply(Instantiate(prefabToInit.transform));
        }
    }
}
</code>```

And calling this ApplyDoors from a editor script :

```<code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

[CustomEditor(typeof(ObjectsReplace))]
public class ObjectsReplaceEditor : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        ObjectsReplace myScript = (ObjectsReplace)target;

        if (GUILayout.Button("Add"))
        {
            myScript.ApplyDoors();
        }
    }
}
</code>```

The problem is that it's Instantiating the prefab many times at the main hierarchy node and not as the doors as childs so it put all the prefabs at the same area instead where the doors are :

But now I see that it's changing the original source prefab asset to a cube :

But the original prefab source asset scaling was :

Not sure why it's changed the prefab it self scaling to 1,1,1

And this is a screenshot of my scene game and example on the right of how the doors should be placed and on the left far other places with doors that this prefab should be Instantiated at. I don't want to destroy the doors but to Instantiate the prefab on the doors at the doors positions with the right rotations like the doors are :

The doors in green at the right are doors left and right that I manually add the DoorShieldFXLocked Variant prefab. And this is how all the doots should look like after Instantiating the DoorShieldFXLocked prefab.

Each door is built with Door_Left and Door_Right and on each door it should be Instantiating the DoorShieldFXLocked but instead it's changing the DoorShieldFXLocked scale to 1,1,1 and put all the Instantiated DoorShieldFXLocked's at other area almost at the same place.

And this is a screenshot in the Hierarchy of example of how a door is built the structure of a door :

Each door is a child of a prefab. It's just the prefab I could not fit it in the screenshot but above all this there is a prefab. So I wonder if there is a way also the apply the prefab of each door ? But this is a door structure example :

答:
Okey before wasn't clear what you wanted so here the updated answer:

The problem was that

This would apply the exact same local rotation, position and scale to the DoorShieldFX objects .. this is not what you want since these positions and rotations would be relative to it's parents. So yeah in this case you rather wanted the global transforms.

You spawn all of them into the scene root, not as children of according doors.

What you rather want to do in this case is

```<code>public struct TransformInfo
{
    public Transform Transform;

    public Vector3 pos;
    public Quaternion rot;
    public Vector3 scale;

    public TransformInfo(Transform transform)
    {
        Transform = transform;

        pos = transform.position;
        rot = transform.rotation;
        scale = transform.scale;
    }

    public void Apply(Transform transform)
    {
        // First of all it is important that
        // this new FX is a child of the according door so
        transform.SetParent(Transform, false);

        // Then you can put it in position if it is still needed
        // since actually SetParent with worldPositionStays = false
        // should actually already do that anyway.
        transform.position = pos;
        transform.rotation = rot;
        // Not sure about the scale since it would be relative to the door
        // depends on your case
    }
}
</code>```

Then in order to get the infos from both lists you could simply do e.g. (assuming the amount is equal for left and right)

```<code>// Note your method should probably return something
public TransformInfo[] GetDoors()
{
    var DoorsLeft = GameObject.FindGameObjectsWithTag("Door_Left");
    var DoorsRight = GameObject.FindGameObjectsWithTag("Door_Right");

    TransformInfo[] trnfrm = new TransformInfo[DoorsLeft.Length * 2];

    trnfrmIndex = 0;
    for (int i = 0; i < DoorsLeft.Length; i++)
    {
        trnfrm[trnfrmIndex] = new TransformInfo(DoorsLeft[i]);
        trnfrm[trnfrmIndex+1] = new TransformInfo(DoorsRight[i]);

        trnfrmIndex += 2;
    }

    return trnfrm;
}
</code>```

Then for reapply these to all doors you can do

```<code>foreach(var info in transformInfos)
{
    info.Apply(Instantiate (prefabToInit).transform);
}
</code>```

The ID is then actually not needed anymore.

However

Well actually the entire script is not needed for your goal since you could also simply iterate over the two arrays like

```<code>public void ApplyDoors()
{
    var DoorsLeft = GameObject.FindGameObjectsWithTag("Door_Left");
    var DoorsRight = GameObject.FindGameObjectsWithTag("Door_Right");

    foreach(var door in DoorsLeft)
    {
        Instantiate(prefabToInit, door.transform.position, door.transform.rotation, door.transform);
    }

    foreach(var door in DoorsRight)
    {
        Instantiate(prefabToInit, door.transform.position, door.transform.rotation, door.transform);
    }
}
</code>```

without the need of any in-between class!

Body:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectsReplace : MonoBehaviour
{
    public class TransformInfo
    {
        public Vector3 pos;
        public Quaternion rot;
        public Vector3 scale;
    }

    public void GetDoors()
    {
        var DoorsLeft = GameObject.FindGameObjectsWithTag("Door_Left");
        var DoorsRight = GameObject.FindGameObjectsWithTag("Door_Right");

        TransformInfo[] trnfrm = new TransformInfo[DoorsLeft.Length];

        for (int i = 0; i < trnfrm.Length; i++)
        {
            trnfrm[i] = new TransformInfo();

            trnfrm[i].pos = DoorsLeft[i].transform.position;
            trnfrm[i].rot = DoorsLeft[i].transform.rotation;
            trnfrm[i].scale = DoorsLeft[i].transform.localScale;
        }
    }
}

This is working fine for the DoorsLeft but I want that trnfrm will include also the info of the objects from DoorsRight so the array or list trnfrm structure will be something like that :

DoorLeft 0...info inside
DoorLeft 1...info inside
.
.
.
DoorRight 0...info inside
DoorRight 1...info inside

This is how the array looks like now :

I want it to include also the DoorRight and to add some id like a string to know what door info is belong to for example :

DoorLeft 0...info inside
DoorLeft 1...info inside
.
.
.
DoorRight 0...info inside
DoorRight 1...info inside

And how to read the info back into GameObjects ?

The main goal is to Instantiate a prefab at the doors positions and same doors rotations and scaling.

So this is what I did :

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

public class ObjectsReplace : MonoBehaviour
{
    public struct TransformInfo
    {
        public string ID;
        public Transform Transform;

        public Vector3 pos;
        public Quaternion rot;
        public Vector3 scale;

        public TransformInfo(Transform transform, string id)
        {
            Transform = transform;
            ID = id;
            // For this kind of stuff I always prefer working on the local values
            pos = transform.localPosition;
            rot = transform.localRotation;
            scale = transform.localScale;
        }

        public void Apply()
        {
            Transform.localPosition = pos;
            Transform.localRotation = rot;
            Transform.localScale = scale;
        }

        public void Apply(Transform transform)
        {
            transform.localPosition = pos;
            transform.localRotation = rot;
            transform.localScale = scale;
        }
    }

    public GameObject prefabToInit;

    // Note your method should probably return something
    public TransformInfo[] GetDoors()
    {
        var DoorsLeft = GameObject.FindGameObjectsWithTag("Door_Left");
        var DoorsRight = GameObject.FindGameObjectsWithTag("Door_Right");

        TransformInfo[] trnfrm = new TransformInfo[DoorsLeft.Length * 2];

        int trnfrmIndex = 0;
        for (int i = 0; i < DoorsLeft.Length; i++)
        {
            trnfrm[trnfrmIndex] = new TransformInfo(DoorsLeft[i].transform, $"{i}_L");
            trnfrm[trnfrmIndex + 1] = new TransformInfo(DoorsRight[i].transform, $"{i}_R");

            trnfrmIndex += 2;
        }

        return trnfrm;
    }

    public void ApplyDoors()
    {
        foreach (var info in GetDoors())
        {
            info.Apply(Instantiate(prefabToInit.transform));
        }
    }
}

And calling this ApplyDoors from a editor script :

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

[CustomEditor(typeof(ObjectsReplace))]
public class ObjectsReplaceEditor : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        ObjectsReplace myScript = (ObjectsReplace)target;

        if (GUILayout.Button("Add"))
        {
            myScript.ApplyDoors();
        }
    }
}

The problem is that it's Instantiating the prefab many times at the main hierarchy node and not as the doors as childs so it put all the prefabs at the same area instead where the doors are :

But now I see that it's changing the original source prefab asset to a cube :

But the original prefab source asset scaling was :

Not sure why it's changed the prefab it self scaling to 1,1,1

And this is a screenshot of my scene game and example on the right of how the doors should be placed and on the left far other places with doors that this prefab should be Instantiated at. I don't want to destroy the doors but to Instantiate the prefab on the doors at the doors positions with the right rotations like the doors are :

The doors in green at the right are doors left and right that I manually add the DoorShieldFXLocked Variant prefab. And this is how all the doots should look like after Instantiating the DoorShieldFXLocked prefab.

Each door is built with Door_Left and Door_Right and on each door it should be Instantiating the DoorShieldFXLocked but instead it's changing the DoorShieldFXLocked scale to 1,1,1 and put all the Instantiated DoorShieldFXLocked's at other area almost at the same place.

And this is a screenshot in the Hierarchy of example of how a door is built the structure of a door :

Each door is a child of a prefab. It's just the prefab I could not fit it in the screenshot but above all this there is a prefab. So I wonder if there is a way also the apply the prefab of each door ? But this is a door structure example :

Body:
Okey before wasn't clear what you wanted so here the updated answer:

The problem was that

This would apply the exact same local rotation, position and scale to the DoorShieldFX objects .. this is not what you want since these positions and rotations would be relative to it's parents. So yeah in this case you rather wanted the global transforms.

You spawn all of them into the scene root, not as children of according doors.

What you rather want to do in this case is

public struct TransformInfo
{
    public Transform Transform;

    public Vector3 pos;
    public Quaternion rot;
    public Vector3 scale;

    public TransformInfo(Transform transform)
    {
        Transform = transform;

        pos = transform.position;
        rot = transform.rotation;
        scale = transform.scale;
    }

    public void Apply(Transform transform)
    {
        // First of all it is important that
        // this new FX is a child of the according door so
        transform.SetParent(Transform, false);

        // Then you can put it in position if it is still needed
        // since actually SetParent with worldPositionStays = false
        // should actually already do that anyway.
        transform.position = pos;
        transform.rotation = rot;
        // Not sure about the scale since it would be relative to the door
        // depends on your case
    }
}

Then in order to get the infos from both lists you could simply do e.g. (assuming the amount is equal for left and right)

// Note your method should probably return something
public TransformInfo[] GetDoors()
{
    var DoorsLeft = GameObject.FindGameObjectsWithTag("Door_Left");
    var DoorsRight = GameObject.FindGameObjectsWithTag("Door_Right");

    TransformInfo[] trnfrm = new TransformInfo[DoorsLeft.Length * 2];

    trnfrmIndex = 0;
    for (int i = 0; i < DoorsLeft.Length; i++)
    {
        trnfrm[trnfrmIndex] = new TransformInfo(DoorsLeft[i]);
        trnfrm[trnfrmIndex+1] = new TransformInfo(DoorsRight[i]);

        trnfrmIndex += 2;
    }

    return trnfrm;
}

Then for reapply these to all doors you can do

foreach(var info in transformInfos)
{
    info.Apply(Instantiate (prefabToInit).transform);
}

The ID is then actually not needed anymore.

However

Well actually the entire script is not needed for your goal since you could also simply iterate over the two arrays like

public void ApplyDoors()
{
    var DoorsLeft = GameObject.FindGameObjectsWithTag("Door_Left");
    var DoorsRight = GameObject.FindGameObjectsWithTag("Door_Right");

    foreach(var door in DoorsLeft)
    {
        Instantiate(prefabToInit, door.transform.position, door.transform.rotation, door.transform);
    }

    foreach(var door in DoorsRight)
    {
        Instantiate(prefabToInit, door.transform.position, door.transform.rotation, door.transform);
    }
}

without the need of any in-between class!


问:
Alignment Issue Appbar
How can I place the name closer to the "Welcome Back" text? I've tried to do this with centerTitle: true, and textAlign: TextAlign.center but no luck so far? What am I missing out on?

```<code> return new Scaffold(
      appBar: new AppBar(
          brightness: Brightness.light,
          backgroundColor: Colors.white,
          elevation: 0,
          centerTitle: true,
          title: Text(
            "Welcome Back,",
            textAlign: TextAlign.center,
            style: TextStyle(
                color: Color.fromRGBO(49, 39, 79, 1),
                fontWeight: FontWeight.bold,
                fontSize: 20),
          ),
          actions: <Widget>[
            Row(
              children: <Widget>[
                Container(
                    child: Text(name,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            color: Color.fromRGBO(49, 39, 79, 1),
                            fontWeight: FontWeight.bold,
                            fontSize: 20))),
</code>```

答:
Just customize left: in Padding():

```<code>actions: <Widget>[
  Row(
    children: <Widget>[
    Container(
      child: Text(name, style: TextStyle(color: Color.fromRGBO(49, 39, 79, 1), fontWeight: FontWeight.bold,fontSize: 20))
    ),
    /// Play with the parameter `left: ...`
    Padding(padding: const EdgeInsets.only(left: 30, right: 8.0, top: 8.0, bottom: 8.0),
      child: CircleAvatar(
               backgroundImage: NetworkImage(imageUrl)),
      ),
    ],
  ),
]
</code>```

Another solution: Use the variable name in the AppBar-Title:

```<code>title: Text("Welcome Back, $name", style: TextStyle(color: Color.fromRGBO(49, 39, 79, 1), fontWeight: FontWeight.bold,fontSize: 20),),
actions: <Widget>[
  Row(
    children: <Widget>[
    /// Play with the parameter `left: ...`
    Padding(padding: const EdgeInsets.only(left: 30, right: 8.0, top: 8.0, bottom: 8.0),
      child: CircleAvatar(
               backgroundImage: NetworkImage(imageUrl)),
      ),
    ],
  ),
]
</code>```

Result:

Title: Alignment Issue Appbar

Body:
How can I place the name closer to the "Welcome Back" text? I've tried to do this with centerTitle: true, and textAlign: TextAlign.center but no luck so far? What am I missing out on?

 return new Scaffold(
      appBar: new AppBar(
          brightness: Brightness.light,
          backgroundColor: Colors.white,
          elevation: 0,
          centerTitle: true,
          title: Text(
            "Welcome Back,",
            textAlign: TextAlign.center,
            style: TextStyle(
                color: Color.fromRGBO(49, 39, 79, 1),
                fontWeight: FontWeight.bold,
                fontSize: 20),
          ),
          actions: <Widget>[
            Row(
              children: <Widget>[
                Container(
                    child: Text(name,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            color: Color.fromRGBO(49, 39, 79, 1),
                            fontWeight: FontWeight.bold,
                            fontSize: 20))),

Body:
Just customize left: in Padding():

actions: <Widget>[
  Row(
    children: <Widget>[
    Container(
      child: Text(name, style: TextStyle(color: Color.fromRGBO(49, 39, 79, 1), fontWeight: FontWeight.bold,fontSize: 20))
    ),
    /// Play with the parameter `left: ...`
    Padding(padding: const EdgeInsets.only(left: 30, right: 8.0, top: 8.0, bottom: 8.0),
      child: CircleAvatar(
               backgroundImage: NetworkImage(imageUrl)),
      ),
    ],
  ),
]

Another solution: Use the variable name in the AppBar-Title:

title: Text("Welcome Back, $name", style: TextStyle(color: Color.fromRGBO(49, 39, 79, 1), fontWeight: FontWeight.bold,fontSize: 20),),
actions: <Widget>[
  Row(
    children: <Widget>[
    /// Play with the parameter `left: ...`
    Padding(padding: const EdgeInsets.only(left: 30, right: 8.0, top: 8.0, bottom: 8.0),
      child: CircleAvatar(
               backgroundImage: NetworkImage(imageUrl)),
      ),
    ],
  ),
]

Result:


问:
How to delete all keys from redis cluster
I want to delete all keys from redis cluster by using fast process. I know how to delete the keys by using "redis-cli FLUSHALL". But this command can be slow when the data set is large. I heard that all keys can be cleared from redis cache by re-starting the redis service. I am testing this process on my local mac laptop. I am performing following steps:-

Setting many number of keys on my local redis server by using example command redis-cli SET mykey1 "Hello"

Then Re-starting the redis service "brew services restart redis" in the hope that all keys will be deleted when the service will be back up

Then getting the keys by giving "redis-cli KEYS '*'" command

I still see the keys after step-3

The keys are gone only when I give this command--> redis-cli FLUSHALL? How I can clear the keys by re-starting the redis service locally on my mac laptop first then I will try on QA servers?

答: Thank you for links. These were very helpful. I was able to achieve the result by making changes to my redis.conf file with--> redis-server --save "" and --appendonly no. So after these changes, when I now re-start redis service nothing is saved.</p>


问:
Big Data Processing At the Click of a Button
If you have an application that performs some heavy calculation on a large data set, and the results must be returned as quickly as possible at the click of a button, what are some architectural designs that are used to make this work large scale?

For example, an application runs a simulation to predict future results, and then does some statistical analysis on that data along with historical data. There is a good amount of CPU to run the simulation and DB heavy with inserting, then lots of big DB reads to collect historical data, and more CPU to do statistical analyses.

In essence, there is lots of data to process (both CPU and IO intensive), and the results should theoretically be shown at the click of a button.

I understand that this is not always a realistic goal depending on the intensity, but what are some typical architectures to accomplish such a task?

答:
Google does this to return search results.

Check out Hadoop - http://hadoop.apache.org/ - and specifically, MapReduce.

"Hadoop MapReduce is a programming model and software framework for writing applications that rapidly process vast amounts of data in parallel on large clusters of compute nodes."

ContentLicense: CC BY-SA 3.0


问:
What is the best way to use commits in vuex?
I use vue and vuex daily to create my projects, sometimes when making http requests it is not necessary to create mutations to the state. I use this way:

```<code>actions:{
   theAction({},payload){
      // bla bla
   }
}
</code>```

This way I get a warning, however I can perform the action. I have been able to observe to avoid this warning some people recommend to create this action inside the component, for my it is tedious since the ideal thing is to handle the logic from the state

My question is, what's the best practice for creating this kind of action?

答:
Maybe something useful to add.

When using a framework like NUXT you are able to provide plugins. So in the case of API calls which are not related to store mutations but are practical in different components a plugin will be a obvious solution.

nuxt.config.js

```<code>  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
    '@/plugins/register-api',
  ],
</code>```

~/plugin/register-api.js

```<code>import Vue from 'vue';
import api from '~/api';

export default function ({ store }) {
  store.$api = api;

  const ApiUtilityPlugin = {
    install() {
      Vue.prototype.$api = api;
    },
  };

  Vue.use(ApiUtilityPlugin);
}
</code>```

~/api/index.js

```<code>import { service } from 'package'

export default function () {
  return {
    async getValue() {
      await service.getValue();
    },
  };
}
</code>```

Vue Component

```<code><script>
export default {
 methods: {
  callAPI() {
   this.$api.getValue();
 },
};
</script>
</code>```

So in this way you are able to call different API's from all over your app without misusing the store.

Body:
I use vue and vuex daily to create my projects, sometimes when making http requests it is not necessary to create mutations to the state. I use this way:

actions:{
   theAction({},payload){
      // bla bla
   }
}

This way I get a warning, however I can perform the action. I have been able to observe to avoid this warning some people recommend to create this action inside the component, for my it is tedious since the ideal thing is to handle the logic from the state

My question is, what's the best practice for creating this kind of action?

Body:
Maybe something useful to add.

When using a framework like NUXT you are able to provide plugins. So in the case of API calls which are not related to store mutations but are practical in different components a plugin will be a obvious solution.

nuxt.config.js

  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
    '@/plugins/register-api',
  ],

~/plugin/register-api.js

import Vue from 'vue';
import api from '~/api';

export default function ({ store }) {
  store.$api = api;

  const ApiUtilityPlugin = {
    install() {
      Vue.prototype.$api = api;
    },
  };

  Vue.use(ApiUtilityPlugin);
}

~/api/index.js

import { service } from 'package'

export default function () {
  return {
    async getValue() {
      await service.getValue();
    },
  };
}

Vue Component

<script>
export default {
 methods: {
  callAPI() {
   this.$api.getValue();
 },
};
</script>

So in this way you are able to call different API's from all over your app without misusing the store.


问:
C# Add-In (VSTO .NET): Add domain name to outlook junk-email list
With the Outlook UI you can add an email address to your junk-email list, you can add a domain name as trusted domain, but you can't add a domain name to your junk-email list. You must manually edit the email address in your junk-email list to achieve that, so I wrote an Add-In to do this for me, but cant find the method to do that. Apparently the Outlook object model doesn't provide anything for that.

Is there a code workaround for this fatal limitation?

答:
That is correct. Outlook Object Model does not provide any means to access or manipulate Junk Email settings.

You can try to use Extended MAPI (C++ or Delphi) to build the MAPI server side rule that lists all the blocked senders, but it is definitely not for the faint-hearted.

If using Redemption (I am its author) is an option, it exposes RDOJunkEmailOptions object (returned from RDOSession.JunkEmailOptions, RDOAccount.JunkEmailOptions, RDOExchangeMailboxStore.JunkEmailOptions), which allow to add blocked senders using RDOJunkEmailOptions.BlockedSenders.Add.


问:
How to filter and select multiple columns in pandas
I can't select and filter multiple columns together in Pandas. 'Name' and 'Year of Rank' are column names. Thank you!

```<code>dw[dw.Name=='El Toro' & dw['Name', 'Year of Rank']]
</code>```

答:
The following code should work:</p>

```<code>dw[dw['Name'] == 'El Toro'][['Name','Year of Rank']]
</code>```

Body:
I can't select and filter multiple columns together in Pandas. 'Name' and 'Year of Rank' are column names. Thank you!

dw[dw.Name=='El Toro' & dw['Name', 'Year of Rank']]

Body:
The following code should work:

dw[dw['Name'] == 'El Toro'][['Name','Year of Rank']]


问:
Mocking moment() and moment().format using jest
I'm unable to mock moment() or moment().format functions. I have states where, currentDateMoment and currentDateFormatted are getting set as below.

```<code>currentDateMoment: moment() //2019-04-23T17:45:26.339Z
currentDateFormatted: moment().format('MM-DD-YYYY').valueOf() //"04-23-2019"
</code>```

Trying to mock both moment() and moment().format in my snapshot tests to return a particular date, but was unable to. Tried below.

```<code>jest.mock('moment', () => () => '2018–01–30T12:34:56+00:00');

jest.mock('moment', () => ({
  constructor: () => '2018–01–30T12:34:56+00:00'
}));

jest.mock('moment', () => () => ({ format: () => '01–30-2018' }));
</code>```

答:
I was still getting some errors because I was using moment-timezone, too. So, here's what I did to fix that:

let diffMins = updateThreshold + 1;
jest.mock('moment', () => {
  const mMoment = {
    diff: jest.fn(() => diffMins),
  };
  const fn = jest.fn(() => mMoment);
  fn.version = '2.24';
  fn.tz = jest.fn();
  fn.fn = jest.fn();
  return fn;
});```

Body:
I'm unable to mock moment() or moment().format functions. I have states where, currentDateMoment and currentDateFormatted are getting set as below.

currentDateMoment: moment() //2019-04-23T17:45:26.339Z
currentDateFormatted: moment().format('MM-DD-YYYY').valueOf() //"04-23-2019"

Trying to mock both moment() and moment().format in my snapshot tests to return a particular date, but was unable to. Tried below.

jest.mock('moment', () => () => '2018–01–30T12:34:56+00:00');

jest.mock('moment', () => ({
  constructor: () => '2018–01–30T12:34:56+00:00'
}));

jest.mock('moment', () => () => ({ format: () => '01–30-2018' }));


问:
Displaying all results of execution
When I execute a python program, the results starts to appear quickly and I can't read it all. It just flushes over my screen.

When the execution ends, I can no longer see the first displays, because the terminal display space is limited.

How save the output, so I can read all of it?

答:
May be platform dependant.

On Linux you can also pipe your program output into your favorite pager (less for example) if you don't want to write it to a file.

    python file.py | less
```

Title: Displaying all results of execution


问:
Importing SVG in powerpoint with vba
I am trying to import SVG file in my presentation with the help of below given script, but its importing in all the slides instead of importing in active slide only.

```<code>Sub InsertLogoOnEveryPage()

Dim Sld As Slide
Dim Shp As Shape
Dim sFontName As String
Dim oTop As Single

' font:
sFontName = "Times"

For Each Sld In ActivePresentation.Slides

    Debug.Print Sld.Name
    'Insert logo.
    Sld.Shapes.AddPicture FileName:="C:\G-Tools\logo\GEP LOGO 2017-01.svg", _
        LinkToFile:=msoFalse, _
        SaveWithDocument:=msoTrue, Left:=357, Top:=240

Next Sld

End Sub
</code>```

Can anyone please help me to solve this issue.

Thanks alot in advance.

答:
Change:

```<code>For Each Sld In ActivePresentation.Slides
</code>```

to:

```<code>Set Sld = Application.ActiveWindow.View.Slide
</code>```

and delete the Next Sld statment near the end.

Title: Importing SVG in powerpoint with vba

Body:
I am trying to import SVG file in my presentation with the help of below given script, but its importing in all the slides instead of importing in active slide only.

Sub InsertLogoOnEveryPage()

Dim Sld As Slide
Dim Shp As Shape
Dim sFontName As String
Dim oTop As Single

' font:
sFontName = "Times"

For Each Sld In ActivePresentation.Slides

    Debug.Print Sld.Name
    'Insert logo.
    Sld.Shapes.AddPicture FileName:="C:\G-Tools\logo\GEP LOGO 2017-01.svg", _
        LinkToFile:=msoFalse, _
        SaveWithDocument:=msoTrue, Left:=357, Top:=240

Next Sld

End Sub

Can anyone please help me to solve this issue.

Thanks alot in advance.

Body:
Change:

For Each Sld In ActivePresentation.Slides

to:

Set Sld = Application.ActiveWindow.View.Slide

and delete the Next Sld statment near the end.


问:
Embed the main window of a qt/C++ application in a wpf/mvvm application
I need to embed a qt/c++ application in a wpf mvvm application. The window of this qt/C++ has to be integrated in a wpf page displayed in a tab page.

The page Control is the following :

```<code><page x:Class="Wpf_HostExe.Page1"
    xmlns:="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Page1"
    Loaded="OnLoaded">
    <Grid>
        <Border x:Name="HostUi" Background="White"
            HorizontalAlignment="Stretch"
            VerticalAlignment="Stretch"  />
    </Grid>
</Page>
</code>```

I start the app to be hosted with the instructions below :

```<code>public static Process StartProcess()
{
    System.Diagnostics.ProcessStartInfo processStartInfo = new System.Diagnostics.ProcessStartInfo();
    processStartInfo.WorkingDirectory = "C:\\ChildApp\\";
    processStartInfo.fileName = "ChildApp.exe";
    processStartInfo.Arguments = "";

    System.Diagnostics.Process proc = System.Diagnostics.Process.Start(processStartInfo);
    proc.WaitForInputIdle();

    return proc;
}
</code>```

The external window is reparented by the following instructions :

```<code>public class ApplicationHost : HwndHost
{
    private const uint LBS_NOTIFY = 0x00000001;
    private const uint WS_BORDER = 0x00800000;
    private const int SWP_NO_ACTIVATE = 0x0010;
    private const int GWL_STYLE = -16;
    private const int WS_CAPTION = 0x00C00000;
    private const int WS_THICKFRAME = 0x00040000;
    private const uint WS_VISIBLE = 0x10000000;

    [DllImport("user32.dll")]
    private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

    [DllImport("user32.dll"), SetLastError = true]
    private static extern int GetWindowLong(IntPtr hwnd, int nIndex);

    [DllImport("user32.dll")]
    private static extern IntPtr SetParent(IntPtr hWnd, IntPtr hWndParent);

    [DllImport("user32.dll")]
    private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);

    public IntPtr ApplicationHandle { get; set; }
    ...
    protected override HandleRef BuildWindowCore (HandleRef hwndParent)
    {
        var result = new HandleRef(this, ApplicationHandle);
        if (ApplicationHandle.ToInt32() == 0)
        {
            return result;
        }

        var oldParent = SetParent(ApplicationHandle, hwndParent.Handle);

        var styles = GetWindowLong(ApplicationHandle, GWL_STYLE);
        styles |= WS_CHILD | WS_VISIBLE | WS_BORDER | LBS_NOTIFY;
        styles &= ~WS_CAPTION;
        SetWindowLong32(ApplicationHandle, GWL_STYLE, styles);

        return result;
    }
    ...
}
</code>```

I also tried the following version :

```<code>    ...
    protected override HandleRef BuildWindowCore (HandleRef hwndParent)
    {
        SetParent(ApplicationHandle, hwndParent.Handle);

        int style = GetWindowLong(ApplicationHandle, GWL_STYLE);
        style = style & ~WS_CAPTION & ~WS_THICKFRAME;
        SetWindowLong(ApplicationHandle, GWL_STYLE, style);
    }
    ...
</code>```

The process of the app to be hosted start without problem but the SetParent doesn't seem to work and I get the following message while the method BuildWindowCore has been passed whatever the way the setParent is done :

```<code>"An unhandled exception of type 'System.InvalidOperationException' occured in PresentationFramework.dll"
Additional Information : Hosted HWND must be a child window of the specified parent. "
</code>```

I tried a lot of things found on stackoverflow but I still have this same InvalidOperationException thrown and have no clue on how to fix that.

Could you please help me ?

Regards,

答: I presume that you have the source to the Qt application. In that code, you must create a function that will render() the widget on a QImage. Call that function from WPF, and copy the image from QImage's data() to a WriteableBitmap, and show that using a control. You can also forward the mouse and keyboard clicks in the opposite direction, and have a function that then synthesizes the QEvents to interact with the widget.

Body:
I need to embed a qt/c++ application in a wpf mvvm application. The window of this qt/C++ has to be integrated in a wpf page displayed in a tab page.

The page Control is the following :

<page x:Class="Wpf_HostExe.Page1"
    xmlns:="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Page1"
    Loaded="OnLoaded">
    <Grid>
        <Border x:Name="HostUi" Background="White"
            HorizontalAlignment="Stretch"
            VerticalAlignment="Stretch"  />
    </Grid>
</Page>

I start the app to be hosted with the instructions below :

public static Process StartProcess()
{
    System.Diagnostics.ProcessStartInfo processStartInfo = new System.Diagnostics.ProcessStartInfo();
    processStartInfo.WorkingDirectory = "C:\\ChildApp\\";
    processStartInfo.fileName = "ChildApp.exe";
    processStartInfo.Arguments = "";

    System.Diagnostics.Process proc = System.Diagnostics.Process.Start(processStartInfo);
    proc.WaitForInputIdle();

    return proc;
}

The external window is reparented by the following instructions :

public class ApplicationHost : HwndHost
{
    private const uint LBS_NOTIFY = 0x00000001;
    private const uint WS_BORDER = 0x00800000;
    private const int SWP_NO_ACTIVATE = 0x0010;
    private const int GWL_STYLE = -16;
    private const int WS_CAPTION = 0x00C00000;
    private const int WS_THICKFRAME = 0x00040000;
    private const uint WS_VISIBLE = 0x10000000;

    [DllImport("user32.dll")]
    private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

    [DllImport("user32.dll"), SetLastError = true]
    private static extern int GetWindowLong(IntPtr hwnd, int nIndex);

    [DllImport("user32.dll")]
    private static extern IntPtr SetParent(IntPtr hWnd, IntPtr hWndParent);

    [DllImport("user32.dll")]
    private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);

    public IntPtr ApplicationHandle { get; set; }
    ...
    protected override HandleRef BuildWindowCore (HandleRef hwndParent)
    {
        var result = new HandleRef(this, ApplicationHandle);
        if (ApplicationHandle.ToInt32() == 0)
        {
            return result;
        }

        var oldParent = SetParent(ApplicationHandle, hwndParent.Handle);

        var styles = GetWindowLong(ApplicationHandle, GWL_STYLE);
        styles |= WS_CHILD | WS_VISIBLE | WS_BORDER | LBS_NOTIFY;
        styles &= ~WS_CAPTION;
        SetWindowLong32(ApplicationHandle, GWL_STYLE, styles);

        return result;
    }
    ...
}

I also tried the following version :

    ...
    protected override HandleRef BuildWindowCore (HandleRef hwndParent)
    {
        SetParent(ApplicationHandle, hwndParent.Handle);

        int style = GetWindowLong(ApplicationHandle, GWL_STYLE);
        style = style & ~WS_CAPTION & ~WS_THICKFRAME;
        SetWindowLong(ApplicationHandle, GWL_STYLE, style);
    }
    ...

The process of the app to be hosted start without problem but the SetParent doesn't seem to work and I get the following message while the method BuildWindowCore has been passed whatever the way the setParent is done :

"An unhandled exception of type 'System.InvalidOperationException' occured in PresentationFramework.dll"
Additional Information : Hosted HWND must be a child window of the specified parent. "

I tried a lot of things found on stackoverflow but I still have this same InvalidOperationException thrown and have no clue on how to fix that.

Could you please help me ?

Regards,


问:
HAProxy with public IP Adress
I have many servers in another internet data center. Can i use haproxy for load balance each website in them. Follow the documentation in the backend only using private IP how to use public IP like below. If it can't have any app can do that? Thanks.

These are my settings:
haproxy.cfg

```<code>global
    daemon
    maxconn 256
    user        haproxy
    group       haproxy
    chroot      /var/lib/haproxy

defaults
    mode http
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms

frontend http
    bind *:80
    default_backend servers

backend servers
    server server public ip?
    server server public ip?
    server server public ip?
</code>```

答:
You can do like this:

```<code>global
    daemon
    maxconn 256
    user        haproxy
    group       haproxy
    chroot      /var/lib/haproxy

defaults
    mode http
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms

frontend http
    bind *:80
    default_backend servers

backend servers
    balance roundrobin
    mode http
    option forwardfor
    option httpchk GET /
    server server1 public.com check
    server server2 123.123.123.123 check
    server server3 public.com check
</code>```

HAProxy support IP and DNS

Title: HAProxy with public IP Adress

Body:
I have many servers in another internet data center. Can i use haproxy for load balance each website in them. Follow the documentation in the backend only using private IP how to use public IP like below. If it can't have any app can do that? Thanks.

These are my settings:
haproxy.cfg

global
    daemon
    maxconn 256
    user        haproxy
    group       haproxy
    chroot      /var/lib/haproxy

defaults
    mode http
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms

frontend http
    bind *:80
    default_backend servers

backend servers
    server server public ip?
    server server public ip?
    server server public ip?

Body:
You can do like this:

global
    daemon
    maxconn 256
    user        haproxy
    group       haproxy
    chroot      /var/lib/haproxy

defaults
    mode http
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms

frontend http
    bind *:80
    default_backend servers

backend servers
    balance roundrobin
    mode http
    option forwardfor
    option httpchk GET /
    server server1 public.com check
    server server2 123.123.123.123 check
    server server3 public.com check

HAProxy support IP and DNS


问:
Using the Android RecognizerIntent with a bluetooth headset
I use the following code to launch speech recognition in Android:

```<code>PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);

if (activities.size() == 0) {
    displayWarning("This device does not support speech recognition");
    return;
}

Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);

startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
</code>```

This works fine. However, it doesn't seem to accept voice input from a bluetooth headset that is paired and connected using the "Phone audio" profile.

I can use an app called SoundAbout to force "Media Audio" to "Bluetooth (mono) (SCO)". With this app set, my voice recognition now works taking my speech input from my headset.

How can I use RecognizerIntent and get speech input from a bluetooth headset?

I see in API level 16 there is a new intent action ACTION_VOICE_SEARCH_HANDS_FREE. This is too new for me to use, but would this solve my problem?

Do I have to muck around in the AudioManager (like I assume SoundAbout is doing) to route the audio input using setBluetoothScoOn() or startBluetoothSco()?

答:
Add these permissions:

```<code><uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
</code>```

Then create a Broadcast Receiver for Bluetooth.

```<code>public class BTReceiver extends BroadcastReceiver {
    private static final String TAG = "BTReceiver";
    int state = 0;
    AudioManager audioManager;

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("Z", "Received: Bluetooth");
        try {
            Bundle extras = intent.getExtras();
            if (extras != null) { //Do something
                audioManager = (AudioManager) context.getSystemService(AUDIO_SERVICE);

                String action = intent.getAction();
                Toast.makeText(context, action, Toast.LENGTH_LONG).show();
                int state;
                if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) {
                    state = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE,
                            BluetoothHeadset.STATE_DISCONNECTED);
                    Log.d(TAG, "\nAction = " + action + "\nState = " + state); //$NON-NLS-1$ //$NON-NLS-2$
                    if (state == BluetoothHeadset.STATE_CONNECTED) {
                        setModeBluetooth();
                    } else if (state == BluetoothHeadset.STATE_DISCONNECTED) {
                        // Calling stopVoiceRecognition always returns false here
                        // as it should since the headset is no longer connected.
                        setModeNormal();

                        Log.d(TAG, "Headset disconnected"); //$NON-NLS-1$
                    }
                } else // audio
                {
                    state = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
                    Log.d(TAG, "\nAction = " + action + "\nState = " + state); //$NON-NLS-1$ //$NON-NLS-2$
                    if (state == BluetoothHeadset.STATE_AUDIO_CONNECTED) {
                        Log.d(TAG, "\nHeadset audio connected");  //$NON-NLS-1$
                        setModeBluetooth();
                    } else if (state == BluetoothHeadset.STATE_AUDIO_DISCONNECTED) {
                        setModeNormal();
                        Log.d(TAG, "Headset audio disconnected"); //$NON-NLS-1$
                    }
                }
            }
        } catch (Exception e) {
            Log.d("Exception", "Exception " + e.toString());
        }
    }

    private void setModeBluetooth() {
        try {

            audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
            audioManager.startBluetoothSco();
            audioManager.setBluetoothScoOn(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setModeNormal() {
        try {
            audioManager.setMode(AudioManager.MODE_NORMAL);
            audioManager.stopBluetoothSco();
            audioManager.setBluetoothScoOn(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
</code>```

Register the receiver in Manifest:

```<code> <receiver
            android:name=".speech.BTReceiver"
            android:enabled="true"
            android:permission="android.permission.BLUETOOTH">
            <intent-filter>
                <action android:name="android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED" />
            </intent-filter>
        </receiver>
</code>```

In your activity Register and UnRegister this receiver:

First initialize it, in onCreate

```<code> mHeadsetBroadcastReceiver = new BTReceiver();
</code>```

then

```<code>@Override
protected void onResume() {
    super.onResume();

    registerReceiver(mHeadsetBroadcastReceiver,
            new IntentFilter(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED));
    // Calling startVoiceRecognition does not result in immediate audio connection.
    // So register for broadcast of audio connection states. This broadcast will
    // only be sent if startVoiceRecognition returns true.
    registerReceiver(mHeadsetBroadcastReceiver,
            new IntentFilter(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED));
}

@Override
protected void onPause() {
    unregisterReceiver(mHeadsetBroadcastReceiver);

    super.onPause();
}
</code>```

Body:
I use the following code to launch speech recognition in Android:

PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);

if (activities.size() == 0) {
    displayWarning("This device does not support speech recognition");
    return;
}

Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);

startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);

This works fine. However, it doesn't seem to accept voice input from a bluetooth headset that is paired and connected using the "Phone audio" profile.

I can use an app called SoundAbout to force "Media Audio" to "Bluetooth (mono) (SCO)". With this app set, my voice recognition now works taking my speech input from my headset.

How can I use RecognizerIntent and get speech input from a bluetooth headset?

I see in API level 16 there is a new intent action ACTION_VOICE_SEARCH_HANDS_FREE. This is too new for me to use, but would this solve my problem?

Do I have to muck around in the AudioManager (like I assume SoundAbout is doing) to route the audio input using setBluetoothScoOn() or startBluetoothSco()?

Body:
Add these permissions:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

Then create a Broadcast Receiver for Bluetooth.

public class BTReceiver extends BroadcastReceiver {
    private static final String TAG = "BTReceiver";
    int state = 0;
    AudioManager audioManager;

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("Z", "Received: Bluetooth");
        try {
            Bundle extras = intent.getExtras();
            if (extras != null) { //Do something
                audioManager = (AudioManager) context.getSystemService(AUDIO_SERVICE);

                String action = intent.getAction();
                Toast.makeText(context, action, Toast.LENGTH_LONG).show();
                int state;
                if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) {
                    state = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE,
                            BluetoothHeadset.STATE_DISCONNECTED);
                    Log.d(TAG, "\nAction = " + action + "\nState = " + state); //$NON-NLS-1$ //$NON-NLS-2$
                    if (state == BluetoothHeadset.STATE_CONNECTED) {
                        setModeBluetooth();
                    } else if (state == BluetoothHeadset.STATE_DISCONNECTED) {
                        // Calling stopVoiceRecognition always returns false here
                        // as it should since the headset is no longer connected.
                        setModeNormal();

                        Log.d(TAG, "Headset disconnected"); //$NON-NLS-1$
                    }
                } else // audio
                {
                    state = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
                    Log.d(TAG, "\nAction = " + action + "\nState = " + state); //$NON-NLS-1$ //$NON-NLS-2$
                    if (state == BluetoothHeadset.STATE_AUDIO_CONNECTED) {
                        Log.d(TAG, "\nHeadset audio connected");  //$NON-NLS-1$
                        setModeBluetooth();
                    } else if (state == BluetoothHeadset.STATE_AUDIO_DISCONNECTED) {
                        setModeNormal();
                        Log.d(TAG, "Headset audio disconnected"); //$NON-NLS-1$
                    }
                }
            }
        } catch (Exception e) {
            Log.d("Exception", "Exception " + e.toString());
        }
    }

    private void setModeBluetooth() {
        try {

            audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
            audioManager.startBluetoothSco();
            audioManager.setBluetoothScoOn(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setModeNormal() {
        try {
            audioManager.setMode(AudioManager.MODE_NORMAL);
            audioManager.stopBluetoothSco();
            audioManager.setBluetoothScoOn(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Register the receiver in Manifest:

 <receiver
            android:name=".speech.BTReceiver"
            android:enabled="true"
            android:permission="android.permission.BLUETOOTH">
            <intent-filter>
                <action android:name="android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED" />
            </intent-filter>
        </receiver>

In your activity Register and UnRegister this receiver:

First initialize it, in onCreate

 mHeadsetBroadcastReceiver = new BTReceiver();

then

@Override
protected void onResume() {
    super.onResume();

    registerReceiver(mHeadsetBroadcastReceiver,
            new IntentFilter(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED));
    // Calling startVoiceRecognition does not result in immediate audio connection.
    // So register for broadcast of audio connection states. This broadcast will
    // only be sent if startVoiceRecognition returns true.
    registerReceiver(mHeadsetBroadcastReceiver,
            new IntentFilter(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED));
}

@Override
protected void onPause() {
    unregisterReceiver(mHeadsetBroadcastReceiver);

    super.onPause();
}


问:
How to use local xsd for EhCache with Spring
We are facing one issue about EhCache and Spring, when we point XSD file in ehcache.xml to  http://ehcache.org/ehcache.xsd, everything is ok, our application can startup correct.
    But our server can't access external website, so we changed XSD location to local as below, but the application can't startup with following exception (already copy ehcache.xsd to classes folder, same as ehcache.xml).
    I have googled many solution, but it still can't be fixed. I need your help about this. Thank you very much.

Spring: 3.1.0
EhCache: 2.4.2
Server: Tomcat 6.0
Java  :  1.6

Config:

```<code><ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="ehcache.xsd"
    updateCheck="false" monitoring="autodetect" dynamicConfig="true">
</code>```

Exception:

```<code>2012-11-07 16:54:42,003 WARN [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - <Ignored XML validation warning>
org.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document 'ehcache.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.warning(ErrorHandlerWrapper.java:96)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:380)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:318)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.findSchemaGrammar(XMLSchemaValidator.java:2440)
    ... more
2012-11-07 16:54:42,007 ERROR [org.springframework.web.context.ContextLoader] - <Context initialization failed>
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 3 in XML document from ServletContext resource [/WEB-INF/classes/META-INF/ehcache.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'ehcache'.
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
    ... more
Caused by: org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'ehcache'.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:131)

    ...  more
</code>```

答:
In my case just downloading the file from http://ehcache.org/ehcache.xsd into src/main/resources solves the problem

```<code>cd src/main/resources
wget http://ehcache.org/ehcache.xsd
</code>```

Body:
We are facing one issue about EhCache and Spring, when we point XSD file in ehcache.xml to  http://ehcache.org/ehcache.xsd, everything is ok, our application can startup correct.
    But our server can't access external website, so we changed XSD location to local as below, but the application can't startup with following exception (already copy ehcache.xsd to classes folder, same as ehcache.xml).
    I have googled many solution, but it still can't be fixed. I need your help about this. Thank you very much.

Spring: 3.1.0
EhCache: 2.4.2
Server: Tomcat 6.0
Java  :  1.6

Config:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="ehcache.xsd"
    updateCheck="false" monitoring="autodetect" dynamicConfig="true">

Exception:

2012-11-07 16:54:42,003 WARN [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - <Ignored XML validation warning>
org.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document 'ehcache.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.warning(ErrorHandlerWrapper.java:96)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:380)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:318)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.findSchemaGrammar(XMLSchemaValidator.java:2440)
    ... more
2012-11-07 16:54:42,007 ERROR [org.springframework.web.context.ContextLoader] - <Context initialization failed>
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 3 in XML document from ServletContext resource [/WEB-INF/classes/META-INF/ehcache.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'ehcache'.
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
    ... more
Caused by: org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'ehcache'.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:131)

    ...  more

Body:
In my case just downloading the file from http://ehcache.org/ehcache.xsd into src/main/resources solves the problem

cd src/main/resources
wget http://ehcache.org/ehcache.xsd


问:
How to combine css with selectors
I need to clean up my CSS file and remove some bloat.  I know it's possible to combine classes and ids by separating them with commas.  However, I'm not sure how to go about combining them when they have more complex selectors like the ones below.

Any help would be appreciated.  Thank you.

```<code>body #gform_wrapper_14 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}
body #gform_wrapper_15 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}
body #gform_wrapper_17 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}
</code>```

or

```<code>@media only screen and (min-width: 641px) {
    body #gform_wrapper_14 {
      max-width: 80%;
      margin: 0 auto;
     }
    body #gform_wrapper_15 {
      max-width: 80%;
      margin: 0 auto;
     }
    body #gform_wrapper_17 {
      max-width: 80%;
      margin: 0 auto;
     }
    .hor-address {
        width:500px;
    }
}
</code>```

Clarification:  I have multiple #gform_wrapper_xx objects (generated by 3rd party Wordpress plugin) and but I don't want to change all of them.  I just want to change these 3.

答:
To don't generate the same css bloat do:</p>

```<code>body .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}
</code>```

Title: How to combine css with selectors

Body:
I need to clean up my CSS file and remove some bloat.  I know it's possible to combine classes and ids by separating them with commas.  However, I'm not sure how to go about combining them when they have more complex selectors like the ones below.

Any help would be appreciated.  Thank you.

body #gform_wrapper_14 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}
body #gform_wrapper_15 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}
body #gform_wrapper_17 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}

or

@media only screen and (min-width: 641px) {
    body #gform_wrapper_14 {
      max-width: 80%;
      margin: 0 auto;
     }
    body #gform_wrapper_15 {
      max-width: 80%;
      margin: 0 auto;
     }
    body #gform_wrapper_17 {
      max-width: 80%;
      margin: 0 auto;
     }
    .hor-address {
        width:500px;
    }
}

Clarification:  I have multiple #gform_wrapper_xx objects (generated by 3rd party Wordpress plugin) and but I don't want to change all of them.  I just want to change these 3.

Body:
To don't generate the same css bloat do:

body .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}


问:
Please help with adding sound to my website- on mouse-click
I am trying to add sound to my web-site, when a link is clicked.
I added this javascript into the head of my doc:

```<code><script language="javascript" type="text/javascript">
 function playSound('Swoosh 3-SoundBible.com-1573211927.wav') {
 document.getElementById("dummy").innerHTML=
 "embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
 }
</script>
</code>```

And I added this code into the body:
span id="dummy">

And this is what I added by the li that I want the sound to be heard on:
 onclick="playSound('Swoosh 3-SoundBible.com-1573211927.wav');

I got this from http://webdesign.about.com/od/sound/a/play_sound_oncl.htm. But this does NOT work when I tested it my browser. NO sound is heard on the mouse-click.
Can anyone help please?
Thank you!

答:
Here is a way to do it using the HTML5 audio element.
To make this work in as many browsers as possible, you should have an .mp3 and a .ogg version of your sound.
For simplicity, I'm using jQuery to do the event handling.

The markup

```<code><audio id='clicksound' style='display:none'>
<source src='mysound.ogg'>
<source src='mysound.mp3'>
</audio>
</code>```

the JavaScript

```<code>$(document).ready(function(){
    $('.soundonclick').click(function(){
        document.getElementById('clicksound').play();
    });
});
</code>```

Body:
I am trying to add sound to my web-site, when a link is clicked.
I added this javascript into the head of my doc:

And I added this code into the body:
span id="dummy">

And this is what I added by the li that I want the sound to be heard on:
 onclick="playSound('Swoosh 3-SoundBible.com-1573211927.wav');

I got this from http://webdesign.about.com/od/sound/a/play_sound_oncl.htm. But this does NOT work when I tested it my browser. NO sound is heard on the mouse-click.
Can anyone help please?
Thank you!

Body:
Here is a way to do it using the HTML5 audio element.
To make this work in as many browsers as possible, you should have an .mp3 and a .ogg version of your sound.
For simplicity, I'm using jQuery to do the event handling.

The markup

<audio id='clicksound' style='display:none'>
<source src='mysound.ogg'>
<source src='mysound.mp3'>
</audio>

the JavaScript

$(document).ready(function(){
    $('.soundonclick').click(function(){
        document.getElementById('clicksound').play();
    });
});


问:
Taking the last five digits of a number from user input in REACT.jsx
Basically, I am currently using this.props.x (which is the user input) to get information from another page. So this.props.x is a number, for example "12345 12345 54321" in three groups of 5 digits. I want to replace the first 10 digits with asterisks and keep the last 5 digits. How do I manipulate this.props.x in such a way that I can make this possible?

Thanks.

This is what I've tried.

```<code>{this.props.x ? (
              <p>
                Card number: <br />
                {"***** *****" + this.props.x}
              </p>
            ) : (
              ""
            )
</code>```

I want the end result to look like
***** ***** 54321

答:
For string use -

```<code>{this.props.x ? (
          <p>
            Card number: <br />
            {"***** *****" + this.props.x.slice(-5)}
          </p>
        ) : (
          ""
        )
}
</code>```

For number use -

```<code>{this.props.x ? (
          <p>
            Card number: <br />
            {"***** *****" + this.props.x%100000}
          </p>
        ) : (
          ""
        )
}
</code>```

Hope this helps!

Body:
Basically, I am currently using this.props.x (which is the user input) to get information from another page. So this.props.x is a number, for example "12345 12345 54321" in three groups of 5 digits. I want to replace the first 10 digits with asterisks and keep the last 5 digits. How do I manipulate this.props.x in such a way that I can make this possible?

Thanks.

This is what I've tried.

{this.props.x ? (

                Card number:

                {"***** *****" + this.props.x}

            ) : (
              ""
            )

I want the end result to look like
***** ***** 54321

Body:
For string use -

{this.props.x ? (
          <p>
            Card number: <br />
            {"***** *****" + this.props.x.slice(-5)}
          </p>
        ) : (
          ""
        )
}

For number use -

{this.props.x ? (
          <p>
            Card number: <br />
            {"***** *****" + this.props.x%100000}
          </p>
        ) : (
          ""
        )
}

Hope this helps!


问:
Recursive data in JSON object
```<code>{
"groups": [
    {
        "name": "Event",
        "groups": [
            {
                "name": "Service",
                "subscriptions": [
                    {
                        "topic": "SERVICE_STATUS_PRESETS"
                    },
                    {
                        "topic": "AIRCRAFT_ACTIVATION",

                    },
                    {
                        "topic": "OUT_OF_SERVICE",

                    }
                ]
            }
        ]
    },
    {
        "name": "Enquiries",
        "groups": [
            {
                "name": "Service-related",
                "subscriptions": [
                    {

                        "topic": "PROMO_CODES_REQUESTS",

                    }
                ]
            }
        ]
    }
],
"subscriptions": [
    {
        "topic": "BANNERS",
    },
    {
        "topic": "DOCUMENTS",
    },
    {
        "topic": "USER",
    }
]
</code>```

}

OK guys I have such JSON structure what I need is to: return all topics in array, in this example it will be:

["SERVICE_STATUS_PRESETS", "AIRCRAFT_ACTIVATION", "OUT_OF_SERVICE", "PROMO_CODES_REQUESTS", "BANNERS", "DOCUMENTS", "USER"]

I try recursive calls like this, though I only get last three records:

```<code>getRecursive() {
if (Array.isArray(data)) {
       for (let i = 0; i < data.length; i++) {
         if (data[i].subscriptions) {
           return data[i].subscriptions.map((val: SubscriptionGroupDetails) => val.topic);
         } else if (data[i].groups) {
           return this.getAllTopics(data[i].groups);
         }
       }
     }
     if (data && data.groups) {
      return this.getAllTopics(data.groups);
     }
     return data.subscriptions.map((val: SubscriptionGroupDetails) => val.topic);
}
</code>```

答:
You could take a recursive approach and check

if the handed over data is not an object for checking, then return with empty array,

if the object has the wanted property, then return an array with the value of topic,

or get the values and make a recursive call with the function and return an array with the result of it.

function getTopics(object) {
    if (!object || typeof object !== 'object') return [];
    if ('topic' in object) return [object.topic];
    return Object.values(object).reduce((r, v) => [...r, ...getTopics(v)], []);
}

var data = { groups: [{ name: "Event", groups: [{ name: "Service", subscriptions: [{ topic: "SERVICE_STATUS_PRESETS" }, { topic: "AIRCRAFT_ACTIVATION" }, { topic: "OUT_OF_SERVICE" }] }] }, { name: "Enquiries", groups: [{ name: "Service-related", subscriptions: [{ topic: "PROMO_CODES_REQUESTS" }] }] }], subscriptions: [{ topic: "BANNERS" }, { topic: "DOCUMENTS" }, { topic: "USER" }] },
    result = getTopics(data);

console.log(result);```

Title: Recursive data in JSON object

Body:
{
"groups": [
    {
        "name": "Event",
        "groups": [
            {
                "name": "Service",
                "subscriptions": [
                    {
                        "topic": "SERVICE_STATUS_PRESETS"
                    },
                    {
                        "topic": "AIRCRAFT_ACTIVATION",

                    },
                    {
                        "topic": "OUT_OF_SERVICE",

                    }
                ]
            }
        ]
    },
    {
        "name": "Enquiries",
        "groups": [
            {
                "name": "Service-related",
                "subscriptions": [
                    {

                        "topic": "PROMO_CODES_REQUESTS",

                    }
                ]
            }
        ]
    }
],
"subscriptions": [
    {
        "topic": "BANNERS",
    },
    {
        "topic": "DOCUMENTS",
    },
    {
        "topic": "USER",
    }
]

}

OK guys I have such JSON structure what I need is to: return all topics in array, in this example it will be:

["SERVICE_STATUS_PRESETS", "AIRCRAFT_ACTIVATION", "OUT_OF_SERVICE", "PROMO_CODES_REQUESTS", "BANNERS", "DOCUMENTS", "USER"]

I try recursive calls like this, though I only get last three records:

getRecursive() {
if (Array.isArray(data)) {
       for (let i = 0; i < data.length; i++) {
         if (data[i].subscriptions) {
           return data[i].subscriptions.map((val: SubscriptionGroupDetails) => val.topic);
         } else if (data[i].groups) {
           return this.getAllTopics(data[i].groups);
         }
       }
     }
     if (data && data.groups) {
      return this.getAllTopics(data.groups);
     }
     return data.subscriptions.map((val: SubscriptionGroupDetails) => val.topic);
}


问:
Django Saving and loading messages
i am making chat app using django, and i follow the tutorial in youtube and documentation and i follow everything they say, but i still get the error

```<code>chat/
    __init__.py
    consumers.py
    routing.py
    templates/
    urls.py
    views.py
</code>```

This is my code in consumers.py

this is the script in my room.html, i already have script in ReconnectingWebSocket.js

```<code><script>
    var roomName = {{ room_name_json }};
    var username = {{ username }};

    var chatSocket = new ReconnectingWebSocket(
        'ws://' + window.location.host +
        '/ws/chat/' + roomName + '/');

    chatSocket.onmessage = function(e) {
        var data = JSON.parse(e.data);
        var message = data['message'];
        var author = message['author'];

        var msgListTag = document.createElement('li');
        var pTag = document.createElement('p');
        pTag.textContent = message.content;

        if (author === username){
            msgListTag.className='sent';
        }
        else{
            msgListTag.className = 'replies';
        }
        msgListTag.appendChild(pTag);
        document.querySelector('#chat-log').appendChild(msgListTag);
    };

    chatSocket.onclose = function(e) {
        console.error('Chat socket closed unexpectedly');
    };

    document.querySelector('#chat-message-input').onkeyup = function(e) {
        if (e.keyCode === 13) {  // enter, return
            document.querySelector('#chat-message-submit').click();
        }
    };

    document.querySelector('#chat-message-submit').onclick = function(e) {
        var messageInputDom = document.getElementById('#chat-message-input');
        var message = messageInputDom.value;
        chatSocket.send(JSON.stringify({
            'command': 'new_message',
            'message': message,
            'from': username
        }));
        messageInputDom.value = '';
    };
</script>

    class ChatConsumer(WebsocketConsumer):
        def fetch_messages(self, data):
            messages = Message.last_10_messages()
            content = {
                'messages': self.messages_to_json(messages)
            }
            self.send_message(content)
        def new_message(self, data):
            author = data['from']
            author_user =User.objects.filter(username=author)[0]
            message = Message.objects.create(
                author=author_user,
                content=data['message']
            )
            content = {
                'command': 'new_message',
                'message': self.messages_to_json(message)
            }
            return  self.send_chat_message(content)

        def messages_to_json(self, messages):
            result = []
            for message in messages:
                result.append(self.message_to_json(message))
            return result
        def message_to_json(self, message):
            return {
                'author':message.author.username,
                'content': message.content,
                'timestamp': str(message.timestamp)
            }
        commands = {
            'fetch_messages': fetch_messages,
            'new_message': new_message
        }
        def connect(self):
            self.room_name = self.scope['url_route']['kwargs']['room_name']
            self.room_group_name = 'chat_%s' % self.room_name
            async_to_sync(self.channel_layer.group_add)(
                self.room_group_name,
                self.channel_name
            )
            self.accept()

        def disconnect(self, close_code):
            async_to_sync(self.channel_layer.group_discard)(
                self.room_group_name,
                self.channel_name
            )
        def receive(self, text_data):
            data = json.loads(text_data)
            self.commands[data['command']](self, data)

        def send_chat_message(self, message):
            async_to_sync(self.channel_layer.group_send)(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'message': message
                }
            )

        def send_message(self, message):
            self.send(text_data=json.dump(message))

        def chat_message(self, event):
            message = event['message']
            self.send(text_data=json.dump(message))
</code>```

my views.py

```<code> return render(request, 'chat/room.html', {
        'room_name_json': mark_safe(json.dumps(room_name)),
        'username':mark_safe(json.dumps(request.user.username)),
    })
</code>```

my models.py

```<code>class Message(models.Model):
    author = models.ForeignKey(User, related_name='author_messages', on_delete=models.CASCADE)
    content = models.TextField(null=True, blank=True)
    timestamp = models.DateTimeField(auto_now_add=True,null=True, blank=True)

    def __str__(self):
        return self.author.username

    def last_10_messages(self):
        return Message.objects.order_by('-timestamp').all()[:10]
</code>```

this is the error i get

i get error from this line

```<code>def messages_to_json(self, messages):
    result = []
    for message in messages:
        result.append(self.message_to_json(message))
    return result
</code>```

for message in messages:

UPDATE when i tried this

```<code>def messages_to_json(self, messages):
    content = {
        'command': 'new_message',
        'message': self.message_to_json(messages)
    }
</code>```

I get this error

答:
your messages instance is not iterable,so you cannot use it in for loop,it is an instance of your Messages model that inherit from models.Model that is not an iterable,so you can simply use your message_to_json function:</p>

```<code> content = {
                'command': 'new_message',
                'message': self.message_to_json(message)
            }
</code>```

Title: Django Saving and loading messages

Body:
i am making chat app using django, and i follow the tutorial in youtube and documentation and i follow everything they say, but i still get the error

chat/
    __init__.py
    consumers.py
    routing.py
    templates/
    urls.py
    views.py

This is my code in consumers.py

this is the script in my room.html, i already have script in ReconnectingWebSocket.js

    class ChatConsumer(WebsocketConsumer):
        def fetch_messages(self, data):
            messages = Message.last_10_messages()
            content = {
                'messages': self.messages_to_json(messages)
            }
            self.send_message(content)
        def new_message(self, data):
            author = data['from']
            author_user =User.objects.filter(username=author)[0]
            message = Message.objects.create(
                author=author_user,
                content=data['message']
            )
            content = {
                'command': 'new_message',
                'message': self.messages_to_json(message)
            }
            return  self.send_chat_message(content)

        def messages_to_json(self, messages):
            result = []
            for message in messages:
                result.append(self.message_to_json(message))
            return result
        def message_to_json(self, message):
            return {
                'author':message.author.username,
                'content': message.content,
                'timestamp': str(message.timestamp)
            }
        commands = {
            'fetch_messages': fetch_messages,
            'new_message': new_message
        }
        def connect(self):
            self.room_name = self.scope['url_route']['kwargs']['room_name']
            self.room_group_name = 'chat_%s' % self.room_name
            async_to_sync(self.channel_layer.group_add)(
                self.room_group_name,
                self.channel_name
            )
            self.accept()

        def disconnect(self, close_code):
            async_to_sync(self.channel_layer.group_discard)(
                self.room_group_name,
                self.channel_name
            )
        def receive(self, text_data):
            data = json.loads(text_data)
            self.commands[data['command']](self, data)

        def send_chat_message(self, message):
            async_to_sync(self.channel_layer.group_send)(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'message': message
                }
            )

        def send_message(self, message):
            self.send(text_data=json.dump(message))

        def chat_message(self, event):
            message = event['message']
            self.send(text_data=json.dump(message))

my views.py

 return render(request, 'chat/room.html', {
        'room_name_json': mark_safe(json.dumps(room_name)),
        'username':mark_safe(json.dumps(request.user.username)),
    })

my models.py

class Message(models.Model):
    author = models.ForeignKey(User, related_name='author_messages', on_delete=models.CASCADE)
    content = models.TextField(null=True, blank=True)
    timestamp = models.DateTimeField(auto_now_add=True,null=True, blank=True)

    def __str__(self):
        return self.author.username

    def last_10_messages(self):
        return Message.objects.order_by('-timestamp').all()[:10]

this is the error i get

i get error from this line

def messages_to_json(self, messages):
    result = []
    for message in messages:
        result.append(self.message_to_json(message))
    return result

for message in messages:

UPDATE when i tried this

def messages_to_json(self, messages):
    content = {
        'command': 'new_message',
        'message': self.message_to_json(messages)
    }

I get this error

Body:
your messages instance is not iterable,so you cannot use it in for loop,it is an instance of your Messages model that inherit from models.Model that is not an iterable,so you can simply use your message_to_json function:

 content = {
                'command': 'new_message',
                'message': self.message_to_json(message)
            }